qywechat.class.php 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246
  1. <?php
  2. /**
  3. * 微信公众平台企业号PHP-SDK, 官方API类库
  4. * @author binsee <binsee@163.com>
  5. * @link https://github.com/binsee/wechat-php-sdk
  6. * @version 1.0
  7. * usage:
  8. * $options = array(
  9. * 'token'=>'tokenaccesskey', //填写应用接口的Token
  10. * 'encodingaeskey'=>'encodingaeskey', //填写加密用的EncodingAESKey
  11. * 'appid'=>'wxdk1234567890', //填写高级调用功能的app id
  12. * 'appsecret'=>'xxxxxxxxxxxxxxxxxxx', //填写高级调用功能的密钥
  13. * 'agentid'=>'1', //应用的id
  14. * 'debug'=>false, //调试开关
  15. * 'logcallback'=>'logg', //调试输出方法,需要有一个string类型的参数
  16. * );
  17. *
  18. */
  19. class Wechat
  20. {
  21. const MSGTYPE_TEXT = 'text';
  22. const MSGTYPE_IMAGE = 'image';
  23. const MSGTYPE_LOCATION = 'location';
  24. const MSGTYPE_LINK = 'link'; //暂不支持
  25. const MSGTYPE_EVENT = 'event';
  26. const MSGTYPE_MUSIC = 'music'; //暂不支持
  27. const MSGTYPE_NEWS = 'news';
  28. const MSGTYPE_VOICE = 'voice';
  29. const MSGTYPE_VIDEO = 'video';
  30. const EVENT_SUBSCRIBE = 'subscribe'; //订阅
  31. const EVENT_UNSUBSCRIBE = 'unsubscribe'; //取消订阅
  32. const EVENT_LOCATION = 'LOCATION'; //上报地理位置
  33. const EVENT_ENTER_AGENT = 'enter_agent'; //用户进入应用
  34. const EVENT_MENU_VIEW = 'VIEW'; //菜单 - 点击菜单跳转链接
  35. const EVENT_MENU_CLICK = 'CLICK'; //菜单 - 点击菜单拉取消息
  36. const EVENT_MENU_SCAN_PUSH = 'scancode_push'; //菜单 - 扫码推事件(客户端跳URL)
  37. const EVENT_MENU_SCAN_WAITMSG = 'scancode_waitmsg'; //菜单 - 扫码推事件(客户端不跳URL)
  38. const EVENT_MENU_PIC_SYS = 'pic_sysphoto'; //菜单 - 弹出系统拍照发图
  39. const EVENT_MENU_PIC_PHOTO = 'pic_photo_or_album'; //菜单 - 弹出拍照或者相册发图
  40. const EVENT_MENU_PIC_WEIXIN = 'pic_weixin'; //菜单 - 弹出微信相册发图器
  41. const EVENT_MENU_LOCATION = 'location_select'; //菜单 - 弹出地理位置选择器
  42. const EVENT_SEND_MASS = 'MASSSENDJOBFINISH'; //发送结果 - 高级群发完成
  43. const EVENT_SEND_TEMPLATE = 'TEMPLATESENDJOBFINISH';//发送结果 - 模板消息发送结果
  44. const API_URL_PREFIX = 'https://qyapi.weixin.qq.com/cgi-bin';
  45. const USER_CREATE_URL = '/user/create?';
  46. const USER_UPDATE_URL = '/user/update?';
  47. const USER_DELETE_URL = '/user/delete?';
  48. const USER_BATCHDELETE_URL = '/user/batchdelete?';
  49. const USER_GET_URL = '/user/get?';
  50. const USER_LIST_URL = '/user/simplelist?';
  51. const USER_LIST_INFO_URL = '/user/list?';
  52. const USER_GETINFO_URL = '/user/getuserinfo?';
  53. const USER_INVITE_URL = '/invite/send?';
  54. const DEPARTMENT_CREATE_URL = '/department/create?';
  55. const DEPARTMENT_UPDATE_URL = '/department/update?';
  56. const DEPARTMENT_DELETE_URL = '/department/delete?';
  57. const DEPARTMENT_MOVE_URL = '/department/move?';
  58. const DEPARTMENT_LIST_URL = '/department/list?';
  59. const TAG_CREATE_URL = '/tag/create?';
  60. const TAG_UPDATE_URL = '/tag/update?';
  61. const TAG_DELETE_URL = '/tag/delete?';
  62. const TAG_GET_URL = '/tag/get?';
  63. const TAG_ADDUSER_URL = '/tag/addtagusers?';
  64. const TAG_DELUSER_URL = '/tag/deltagusers?';
  65. const TAG_LIST_URL = '/tag/list?';
  66. const MEDIA_UPLOAD_URL = '/media/upload?';
  67. const MEDIA_GET_URL = '/media/get?';
  68. const AUTHSUCC_URL = '/user/authsucc?';
  69. const MASS_SEND_URL = '/message/send?';
  70. const MENU_CREATE_URL = '/menu/create?';
  71. const MENU_GET_URL = '/menu/get?';
  72. const MENU_DELETE_URL = '/menu/delete?';
  73. const TOKEN_GET_URL = '/gettoken?';
  74. const TICKET_GET_URL = '/get_jsapi_ticket?';
  75. const CALLBACKSERVER_GET_URL = '/getcallbackip?';
  76. const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
  77. const OAUTH_AUTHORIZE_URL = '/authorize?';
  78. private $token;
  79. private $encodingAesKey;
  80. private $appid; //也就是企业号的CorpID
  81. private $appsecret;
  82. private $access_token;
  83. private $agentid; //应用id AgentID
  84. private $postxml;
  85. private $agentidxml; //接收的应用id AgentID
  86. private $_msg;
  87. private $_receive;
  88. private $_sendmsg; //主动发送消息的内容
  89. private $_text_filter = true;
  90. public $debug = false;
  91. public $errCode = 40001;
  92. public $errMsg = "no access";
  93. public $logcallback;
  94. public function __construct($options)
  95. {
  96. $this->token = isset($options['token'])?$options['token']:'';
  97. $this->encodingAesKey = isset($options['encodingaeskey'])?$options['encodingaeskey']:'';
  98. $this->appid = isset($options['appid'])?$options['appid']:'';
  99. $this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
  100. $this->agentid = isset($options['agentid'])?$options['agentid']:'';
  101. $this->debug = isset($options['debug'])?$options['debug']:false;
  102. $this->logcallback = isset($options['logcallback'])?$options['logcallback']:false;
  103. }
  104. protected function log($log){
  105. if ($this->debug && function_exists($this->logcallback)) {
  106. if (is_array($log)) $log = print_r($log,true);
  107. return call_user_func($this->logcallback,$log);
  108. }
  109. }
  110. /**
  111. * 数据XML编码
  112. * @param mixed $data 数据
  113. * @return string
  114. */
  115. public static function data_to_xml($data) {
  116. $xml = '';
  117. foreach ($data as $key => $val) {
  118. is_numeric($key) && $key = "item id=\"$key\"";
  119. $xml .= "<$key>";
  120. $xml .= ( is_array($val) || is_object($val)) ? self::data_to_xml($val) : self::xmlSafeStr($val);
  121. list($key, ) = explode(' ', $key);
  122. $xml .= "</$key>";
  123. }
  124. return $xml;
  125. }
  126. public static function xmlSafeStr($str)
  127. {
  128. return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
  129. }
  130. /**
  131. * XML编码
  132. * @param mixed $data 数据
  133. * @param string $root 根节点名
  134. * @param string $item 数字索引的子节点名
  135. * @param string $attr 根节点属性
  136. * @param string $id 数字索引子节点key转换的属性名
  137. * @param string $encoding 数据编码
  138. * @return string
  139. */
  140. public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
  141. if(is_array($attr)){
  142. $_attr = array();
  143. foreach ($attr as $key => $value) {
  144. $_attr[] = "{$key}=\"{$value}\"";
  145. }
  146. $attr = implode(' ', $_attr);
  147. }
  148. $attr = trim($attr);
  149. $attr = empty($attr) ? '' : " {$attr}";
  150. $xml = "<{$root}{$attr}>";
  151. $xml .= self::data_to_xml($data, $item, $id);
  152. $xml .= "</{$root}>";
  153. return $xml;
  154. }
  155. /**
  156. * 微信api不支持中文转义的json结构
  157. * @param array $arr
  158. */
  159. static function json_encode($arr) {
  160. $parts = array ();
  161. $is_list = false;
  162. //Find out if the given array is a numerical array
  163. $keys = array_keys ( $arr );
  164. $max_length = count ( $arr ) - 1;
  165. if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
  166. $is_list = true;
  167. for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
  168. if ($i != $keys [$i]) { //A key fails at position check.
  169. $is_list = false; //It is an associative array.
  170. break;
  171. }
  172. }
  173. }
  174. foreach ( $arr as $key => $value ) {
  175. if (is_array ( $value )) { //Custom handling for arrays
  176. if ($is_list)
  177. $parts [] = self::json_encode ( $value ); /* :RECURSION: */
  178. else
  179. $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
  180. } else {
  181. $str = '';
  182. if (! $is_list)
  183. $str = '"' . $key . '":';
  184. //Custom handling for multiple data types
  185. if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)
  186. $str .= $value; //Numbers
  187. elseif ($value === false)
  188. $str .= 'false'; //The booleans
  189. elseif ($value === true)
  190. $str .= 'true';
  191. else
  192. $str .= '"' .addcslashes($value, "\\\"\n\r\t/"). '"'; //All other things
  193. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  194. $parts [] = $str;
  195. }
  196. }
  197. $json = implode ( ',', $parts );
  198. if ($is_list)
  199. return '[' . $json . ']'; //Return numerical JSON
  200. return '{' . $json . '}'; //Return associative JSON
  201. }
  202. /**
  203. * 过滤文字回复\r\n换行符
  204. * @param string $text
  205. * @return string|mixed
  206. */
  207. private function _auto_text_filter($text) {
  208. if (!$this->_text_filter) return $text;
  209. return str_replace("\r\n", "\n", $text);
  210. }
  211. /**
  212. * GET 请求
  213. * @param string $url
  214. */
  215. private function http_get($url){
  216. $oCurl = curl_init();
  217. if(stripos($url,"https://")!==FALSE){
  218. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  219. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  220. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  221. }
  222. curl_setopt($oCurl, CURLOPT_URL, $url);
  223. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  224. $sContent = curl_exec($oCurl);
  225. $aStatus = curl_getinfo($oCurl);
  226. curl_close($oCurl);
  227. if(intval($aStatus["http_code"])==200){
  228. return $sContent;
  229. }else{
  230. return false;
  231. }
  232. }
  233. /**
  234. * POST 请求
  235. * @param string $url
  236. * @param array $param
  237. * @param boolean $post_file 是否文件上传
  238. * @return string content
  239. */
  240. private function http_post($url,$param,$post_file=false){
  241. $oCurl = curl_init();
  242. if(stripos($url,"https://")!==FALSE){
  243. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  244. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
  245. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  246. }
  247. if (is_string($param) || $post_file) {
  248. $strPOST = $param;
  249. } else {
  250. $aPOST = array();
  251. foreach($param as $key=>$val){
  252. $aPOST[] = $key."=".urlencode($val);
  253. }
  254. $strPOST = join("&", $aPOST);
  255. }
  256. curl_setopt($oCurl, CURLOPT_URL, $url);
  257. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  258. curl_setopt($oCurl, CURLOPT_POST,true);
  259. if(PHP_VERSION_ID >= 50500){
  260. curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, FALSE);
  261. }
  262. curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
  263. $sContent = curl_exec($oCurl);
  264. $aStatus = curl_getinfo($oCurl);
  265. curl_close($oCurl);
  266. if(intval($aStatus["http_code"])==200){
  267. return $sContent;
  268. }else{
  269. return false;
  270. }
  271. }
  272. /**
  273. * For weixin server validation
  274. */
  275. private function checkSignature($str)
  276. {
  277. $signature = isset($_GET["msg_signature"])?$_GET["msg_signature"]:'';
  278. $timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:'';
  279. $nonce = isset($_GET["nonce"])?$_GET["nonce"]:'';
  280. $tmpArr = array($str,$this->token, $timestamp, $nonce);//比普通公众平台多了一个加密的密文
  281. sort($tmpArr, SORT_STRING);
  282. $tmpStr = implode($tmpArr);
  283. $shaStr = sha1($tmpStr);
  284. if( $shaStr == $signature ){
  285. return true;
  286. }else{
  287. return false;
  288. }
  289. }
  290. /**
  291. * 微信验证,包括post来的xml解密
  292. * @param bool $return 是否返回
  293. */
  294. public function valid($return=false)
  295. {
  296. $encryptStr="";
  297. if ($_SERVER['REQUEST_METHOD'] == "POST") {
  298. $postStr = file_get_contents("php://input");
  299. $array = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  300. $this->log($postStr);
  301. if (isset($array['Encrypt'])) {
  302. $encryptStr = $array['Encrypt'];
  303. $this->agentidxml = isset($array['AgentID']) ? $array['AgentID']: '';
  304. }
  305. } else {
  306. $encryptStr = isset($_GET["echostr"]) ? $_GET["echostr"]: '';
  307. }
  308. if ($encryptStr) {
  309. $ret=$this->checkSignature($encryptStr);
  310. }
  311. if (!isset($ret) || !$ret) {
  312. if (!$return) {
  313. die('no access');
  314. } else {
  315. return false;
  316. }
  317. }
  318. $pc = new Prpcrypt($this->encodingAesKey);
  319. $array = $pc->decrypt($encryptStr,$this->appid);
  320. if (!isset($array[0]) || ($array[0] != 0)) {
  321. if (!$return) {
  322. die('解密失败!');
  323. } else {
  324. return false;
  325. }
  326. }
  327. if ($_SERVER['REQUEST_METHOD'] == "POST") {
  328. $this->postxml = $array[1];
  329. //$this->log($array[1]);
  330. return ($this->postxml!="");
  331. } else {
  332. $echoStr = $array[1];
  333. if ($return) {
  334. return $echoStr;
  335. } else {
  336. die($echoStr);
  337. }
  338. }
  339. return false;
  340. }
  341. /**
  342. * 获取微信服务器发来的信息
  343. */
  344. public function getRev()
  345. {
  346. if ($this->_receive) return $this;
  347. $postStr = $this->postxml;
  348. $this->log($postStr);
  349. if (!empty($postStr)) {
  350. $this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  351. if (!isset($this->_receive['AgentID'])) {
  352. $this->_receive['AgentID']=$this->agentidxml; //当前接收消息的应用id
  353. }
  354. }
  355. return $this;
  356. }
  357. /**
  358. * 获取微信服务器发来的信息
  359. */
  360. public function getRevData()
  361. {
  362. return $this->_receive;
  363. }
  364. /**
  365. * 获取微信服务器发来的原始加密信息
  366. */
  367. public function getRevPostXml()
  368. {
  369. return $this->postxml;
  370. }
  371. /**
  372. * 获取消息发送者
  373. */
  374. public function getRevFrom() {
  375. if (isset($this->_receive['FromUserName']))
  376. return $this->_receive['FromUserName'];
  377. else
  378. return false;
  379. }
  380. /**
  381. * 获取消息接受者
  382. */
  383. public function getRevTo() {
  384. if (isset($this->_receive['ToUserName']))
  385. return $this->_receive['ToUserName'];
  386. else
  387. return false;
  388. }
  389. /**
  390. * 获取接收消息的应用id
  391. */
  392. public function getRevAgentID() {
  393. if (isset($this->_receive['AgentID']))
  394. return $this->_receive['AgentID'];
  395. else
  396. return false;
  397. }
  398. /**
  399. * 获取接收消息的类型
  400. */
  401. public function getRevType() {
  402. if (isset($this->_receive['MsgType']))
  403. return $this->_receive['MsgType'];
  404. else
  405. return false;
  406. }
  407. /**
  408. * 获取消息ID
  409. */
  410. public function getRevID() {
  411. if (isset($this->_receive['MsgId']))
  412. return $this->_receive['MsgId'];
  413. else
  414. return false;
  415. }
  416. /**
  417. * 获取消息发送时间
  418. */
  419. public function getRevCtime() {
  420. if (isset($this->_receive['CreateTime']))
  421. return $this->_receive['CreateTime'];
  422. else
  423. return false;
  424. }
  425. /**
  426. * 获取接收消息内容正文
  427. */
  428. public function getRevContent(){
  429. if (isset($this->_receive['Content']))
  430. return $this->_receive['Content'];
  431. else
  432. return false;
  433. }
  434. /**
  435. * 获取接收消息图片
  436. */
  437. public function getRevPic(){
  438. if (isset($this->_receive['PicUrl']))
  439. return array(
  440. 'mediaid'=>$this->_receive['MediaId'],
  441. 'picurl'=>(string)$this->_receive['PicUrl'], //防止picurl为空导致解析出错
  442. );
  443. else
  444. return false;
  445. }
  446. /**
  447. * 获取接收地理位置
  448. */
  449. public function getRevGeo(){
  450. if (isset($this->_receive['Location_X'])){
  451. return array(
  452. 'x'=>$this->_receive['Location_X'],
  453. 'y'=>$this->_receive['Location_Y'],
  454. 'scale'=>(string)$this->_receive['Scale'],
  455. 'label'=>(string)$this->_receive['Label']
  456. );
  457. } else
  458. return false;
  459. }
  460. /**
  461. * 获取上报地理位置事件
  462. */
  463. public function getRevEventGeo(){
  464. if (isset($this->_receive['Latitude'])){
  465. return array(
  466. 'x'=>$this->_receive['Latitude'],
  467. 'y'=>$this->_receive['Longitude'],
  468. 'precision'=>$this->_receive['Precision'],
  469. );
  470. } else
  471. return false;
  472. }
  473. /**
  474. * 获取接收事件推送
  475. */
  476. public function getRevEvent(){
  477. if (isset($this->_receive['Event'])){
  478. $array['event'] = $this->_receive['Event'];
  479. }
  480. if (isset($this->_receive['EventKey']) && !empty($this->_receive['EventKey'])){
  481. $array['key'] = $this->_receive['EventKey'];
  482. }
  483. if (isset($array) && count($array) > 0) {
  484. return $array;
  485. } else {
  486. return false;
  487. }
  488. }
  489. /**
  490. * 获取自定义菜单的扫码推事件信息
  491. *
  492. * 事件类型为以下两种时则调用此方法有效
  493. * Event 事件类型,scancode_push
  494. * Event 事件类型,scancode_waitmsg
  495. *
  496. * @return: array | false
  497. * array (
  498. * 'ScanType'=>'qrcode',
  499. * 'ScanResult'=>'123123'
  500. * )
  501. */
  502. public function getRevScanInfo(){
  503. if (isset($this->_receive['ScanCodeInfo'])){
  504. if (!is_array($this->_receive['SendPicsInfo'])) {
  505. $array=(array)$this->_receive['ScanCodeInfo'];
  506. $this->_receive['ScanCodeInfo']=$array;
  507. }else {
  508. $array=$this->_receive['ScanCodeInfo'];
  509. }
  510. }
  511. if (isset($array) && count($array) > 0) {
  512. return $array;
  513. } else {
  514. return false;
  515. }
  516. }
  517. /**
  518. * 获取自定义菜单的图片发送事件信息
  519. *
  520. * 事件类型为以下三种时则调用此方法有效
  521. * Event 事件类型,pic_sysphoto 弹出系统拍照发图的事件推送
  522. * Event 事件类型,pic_photo_or_album 弹出拍照或者相册发图的事件推送
  523. * Event 事件类型,pic_weixin 弹出微信相册发图器的事件推送
  524. *
  525. * @return: array | false
  526. * array (
  527. * 'Count' => '2',
  528. * 'PicList' =>array (
  529. * 'item' =>array (
  530. * 0 =>array ('PicMd5Sum' => 'aaae42617cf2a14342d96005af53624c'),
  531. * 1 =>array ('PicMd5Sum' => '149bd39e296860a2adc2f1bb81616ff8'),
  532. * ),
  533. * ),
  534. * )
  535. *
  536. */
  537. public function getRevSendPicsInfo(){
  538. if (isset($this->_receive['SendPicsInfo'])){
  539. if (!is_array($this->_receive['SendPicsInfo'])) {
  540. $array=(array)$this->_receive['SendPicsInfo'];
  541. if (isset($array['PicList'])){
  542. $array['PicList']=(array)$array['PicList'];
  543. $item=$array['PicList']['item'];
  544. $array['PicList']['item']=array();
  545. foreach ( $item as $key => $value ){
  546. $array['PicList']['item'][$key]=(array)$value;
  547. }
  548. }
  549. $this->_receive['SendPicsInfo']=$array;
  550. } else {
  551. $array=$this->_receive['SendPicsInfo'];
  552. }
  553. }
  554. if (isset($array) && count($array) > 0) {
  555. return $array;
  556. } else {
  557. return false;
  558. }
  559. }
  560. /**
  561. * 获取自定义菜单的地理位置选择器事件推送
  562. *
  563. * 事件类型为以下时则可以调用此方法有效
  564. * Event 事件类型,location_select 弹出系统拍照发图的事件推送
  565. *
  566. * @return: array | false
  567. * array (
  568. * 'Location_X' => '33.731655000061',
  569. * 'Location_Y' => '113.29955200008047',
  570. * 'Scale' => '16',
  571. * 'Label' => '某某市某某区某某路',
  572. * 'Poiname' => '',
  573. * )
  574. *
  575. */
  576. public function getRevSendGeoInfo(){
  577. if (isset($this->_receive['SendLocationInfo'])){
  578. if (!is_array($this->_receive['SendLocationInfo'])) {
  579. $array=(array)$this->_receive['SendLocationInfo'];
  580. if (empty($array['Poiname'])) {
  581. $array['Poiname']="";
  582. }
  583. if (empty($array['Label'])) {
  584. $array['Label']="";
  585. }
  586. $this->_receive['SendLocationInfo']=$array;
  587. } else {
  588. $array=$this->_receive['SendLocationInfo'];
  589. }
  590. }
  591. if (isset($array) && count($array) > 0) {
  592. return $array;
  593. } else {
  594. return false;
  595. }
  596. }
  597. /**
  598. * 获取接收语音推送
  599. */
  600. public function getRevVoice(){
  601. if (isset($this->_receive['MediaId'])){
  602. return array(
  603. 'mediaid'=>$this->_receive['MediaId'],
  604. 'format'=>$this->_receive['Format'],
  605. );
  606. } else
  607. return false;
  608. }
  609. /**
  610. * 获取接收视频推送
  611. */
  612. public function getRevVideo(){
  613. if (isset($this->_receive['MediaId'])){
  614. return array(
  615. 'mediaid'=>$this->_receive['MediaId'],
  616. 'thumbmediaid'=>$this->_receive['ThumbMediaId']
  617. );
  618. } else
  619. return false;
  620. }
  621. /**
  622. * 设置回复消息
  623. * Example: $obj->text('hello')->reply();
  624. * @param string $text
  625. */
  626. public function text($text='')
  627. {
  628. $msg = array(
  629. 'ToUserName' => $this->getRevFrom(),
  630. 'FromUserName'=>$this->getRevTo(),
  631. 'MsgType'=>self::MSGTYPE_TEXT,
  632. 'Content'=>$this->_auto_text_filter($text),
  633. 'CreateTime'=>time(),
  634. );
  635. $this->Message($msg);
  636. return $this;
  637. }
  638. /**
  639. * 设置回复消息
  640. * Example: $obj->image('media_id')->reply();
  641. * @param string $mediaid
  642. */
  643. public function image($mediaid='')
  644. {
  645. $msg = array(
  646. 'ToUserName' => $this->getRevFrom(),
  647. 'FromUserName'=>$this->getRevTo(),
  648. 'MsgType'=>self::MSGTYPE_IMAGE,
  649. 'Image'=>array('MediaId'=>$mediaid),
  650. 'CreateTime'=>time(),
  651. );
  652. $this->Message($msg);
  653. return $this;
  654. }
  655. /**
  656. * 设置回复消息
  657. * Example: $obj->voice('media_id')->reply();
  658. * @param string $mediaid
  659. */
  660. public function voice($mediaid='')
  661. {
  662. $msg = array(
  663. 'ToUserName' => $this->getRevFrom(),
  664. 'FromUserName'=>$this->getRevTo(),
  665. 'MsgType'=>self::MSGTYPE_IMAGE,
  666. 'Voice'=>array('MediaId'=>$mediaid),
  667. 'CreateTime'=>time(),
  668. );
  669. $this->Message($msg);
  670. return $this;
  671. }
  672. /**
  673. * 设置回复消息
  674. * Example: $obj->video('media_id','title','description')->reply();
  675. * @param string $mediaid
  676. */
  677. public function video($mediaid='',$title='',$description='')
  678. {
  679. $msg = array(
  680. 'ToUserName' => $this->getRevFrom(),
  681. 'FromUserName'=>$this->getRevTo(),
  682. 'MsgType'=>self::MSGTYPE_IMAGE,
  683. 'Video'=>array(
  684. 'MediaId'=>$mediaid,
  685. 'Title'=>$title,
  686. 'Description'=>$description
  687. ),
  688. 'CreateTime'=>time(),
  689. );
  690. $this->Message($msg);
  691. return $this;
  692. }
  693. /**
  694. * 设置回复图文
  695. * @param array $newsData
  696. * 数组结构:
  697. * array(
  698. * "0"=>array(
  699. * 'Title'=>'msg title',
  700. * 'Description'=>'summary text',
  701. * 'PicUrl'=>'http://www.domain.com/1.jpg',
  702. * 'Url'=>'http://www.domain.com/1.html'
  703. * ),
  704. * "1"=>....
  705. * )
  706. */
  707. public function news($newsData=array())
  708. {
  709. $count = count($newsData);
  710. $msg = array(
  711. 'ToUserName' => $this->getRevFrom(),
  712. 'FromUserName'=>$this->getRevTo(),
  713. 'MsgType'=>self::MSGTYPE_NEWS,
  714. 'CreateTime'=>time(),
  715. 'ArticleCount'=>$count,
  716. 'Articles'=>$newsData,
  717. );
  718. $this->Message($msg);
  719. return $this;
  720. }
  721. /**
  722. * 设置发送消息
  723. * @param array $msg 消息数组
  724. * @param bool $append 是否在原消息数组追加
  725. */
  726. public function Message($msg = '',$append = false){
  727. if (is_null($msg)) {
  728. $this->_msg =array();
  729. }elseif (is_array($msg)) {
  730. if ($append)
  731. $this->_msg = array_merge($this->_msg,$msg);
  732. else
  733. $this->_msg = $msg;
  734. return $this->_msg;
  735. } else {
  736. return $this->_msg;
  737. }
  738. }
  739. /**
  740. *
  741. * 回复微信服务器, 此函数支持链式操作
  742. * Example: $this->text('msg tips')->reply();
  743. * @param string $msg 要发送的信息, 默认取$this->_msg
  744. * @param bool $return 是否返回信息而不抛出到浏览器 默认:否
  745. */
  746. public function reply($msg=array(),$return = false)
  747. {
  748. if (empty($msg))
  749. $msg = $this->_msg;
  750. $xmldata= $this->xml_encode($msg);
  751. $this->log($xmldata);
  752. $pc = new Prpcrypt($this->encodingAesKey);
  753. $array = $pc->encrypt($xmldata, $this->appid);
  754. $ret = $array[0];
  755. if ($ret != 0) {
  756. $this->log('encrypt err!');
  757. return false;
  758. }
  759. $timestamp = time();
  760. $nonce = rand(77,999)*rand(605,888)*rand(11,99);
  761. $encrypt = $array[1];
  762. $tmpArr = array($this->token, $timestamp, $nonce,$encrypt);//比普通公众平台多了一个加密的密文
  763. sort($tmpArr, SORT_STRING);
  764. $signature = implode($tmpArr);
  765. $signature = sha1($signature);
  766. $smsg = $this->generate($encrypt, $signature, $timestamp, $nonce);
  767. $this->log($smsg);
  768. if ($return)
  769. return $smsg;
  770. elseif ($smsg){
  771. echo $smsg;
  772. return true;
  773. }else
  774. return false;
  775. }
  776. private function generate($encrypt, $signature, $timestamp, $nonce)
  777. {
  778. //格式化加密信息
  779. $format = "<xml>
  780. <Encrypt><![CDATA[%s]]></Encrypt>
  781. <MsgSignature><![CDATA[%s]]></MsgSignature>
  782. <TimeStamp>%s</TimeStamp>
  783. <Nonce><![CDATA[%s]]></Nonce>
  784. </xml>";
  785. return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
  786. }
  787. /**
  788. * 设置缓存,按需重载
  789. * @param string $cachename
  790. * @param mixed $value
  791. * @param int $expired
  792. * @return boolean
  793. */
  794. protected function setCache($cachename,$value,$expired){
  795. //TODO: set cache implementation
  796. return false;
  797. }
  798. /**
  799. * 获取缓存,按需重载
  800. * @param string $cachename
  801. * @return mixed
  802. */
  803. protected function getCache($cachename){
  804. //TODO: get cache implementation
  805. return false;
  806. }
  807. /**
  808. * 清除缓存,按需重载
  809. * @param string $cachename
  810. * @return boolean
  811. */
  812. protected function removeCache($cachename){
  813. //TODO: remove cache implementation
  814. return false;
  815. }
  816. /**
  817. * 通用auth验证方法
  818. * @param string $appid
  819. * @param string $appsecret
  820. * @param string $token 手动指定access_token,非必要情况不建议用
  821. */
  822. public function checkAuth($appid='',$appsecret='',$token=''){
  823. if (!$appid || !$appsecret) {
  824. $appid = $this->appid;
  825. $appsecret = $this->appsecret;
  826. }
  827. if ($token) { //手动指定token,优先使用
  828. $this->access_token=$token;
  829. return $this->access_token;
  830. }
  831. $authname = 'qywechat_access_token'.$appid;
  832. if ($rs = $this->getCache($authname)) {
  833. $this->access_token = $rs;
  834. return $rs;
  835. }
  836. $result = $this->http_get(self::API_URL_PREFIX.self::TOKEN_GET_URL.'corpid='.$appid.'&corpsecret='.$appsecret);
  837. if ($result)
  838. {
  839. $json = json_decode($result,true);
  840. if (!$json || isset($json['errcode'])) {
  841. $this->errCode = $json['errcode'];
  842. $this->errMsg = $json['errmsg'];
  843. return false;
  844. }
  845. $this->access_token = $json['access_token'];
  846. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  847. $this->setCache($authname,$this->access_token,$expire);
  848. return $this->access_token;
  849. }
  850. return false;
  851. }
  852. /**
  853. * 删除验证数据
  854. * @param string $appid
  855. */
  856. public function resetAuth($appid=''){
  857. if (!$appid) $appid = $this->appid;
  858. $this->access_token = '';
  859. $authname = 'qywechat_access_token'.$appid;
  860. $this->removeCache($authname);
  861. return true;
  862. }
  863. /**
  864. * 删除JSAPI授权TICKET
  865. * @param string $appid 用于多个appid时使用
  866. */
  867. public function resetJsTicket($appid=''){
  868. if (!$appid) $appid = $this->appid;
  869. $this->jsapi_ticket = '';
  870. $authname = 'qywechat_jsapi_ticket'.$appid;
  871. $this->removeCache($authname);
  872. return true;
  873. }
  874. /**
  875. * 获取JSAPI授权TICKET
  876. * @param string $appid 用于多个appid时使用,可空
  877. * @param string $jsapi_ticket 手动指定jsapi_ticket,非必要情况不建议用
  878. */
  879. public function getJsTicket($appid='',$jsapi_ticket=''){
  880. if (!$this->access_token && !$this->checkAuth()) return false;
  881. if (!$appid) $appid = $this->appid;
  882. if ($jsapi_ticket) { //手动指定token,优先使用
  883. $this->jsapi_ticket = $jsapi_ticket;
  884. return $this->jsapi_ticket;
  885. }
  886. $authname = 'qywechat_jsapi_ticket'.$appid;
  887. if ($rs = $this->getCache($authname)) {
  888. $this->jsapi_ticket = $rs;
  889. return $rs;
  890. }
  891. $result = $this->http_get(self::API_URL_PREFIX.self::TICKET_GET_URL.'access_token='.$this->access_token);
  892. if ($result)
  893. {
  894. $json = json_decode($result,true);
  895. if (!$json || !empty($json['errcode'])) {
  896. $this->errCode = $json['errcode'];
  897. $this->errMsg = $json['errmsg'];
  898. return false;
  899. }
  900. $this->jsapi_ticket = $json['ticket'];
  901. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  902. $this->setCache($authname, $this->jsapi_ticket, $expire);
  903. return $this->jsapi_ticket;
  904. }
  905. return false;
  906. }
  907. /**
  908. * 获取JsApi使用签名
  909. * @param string $url 网页的URL,自动处理#及其后面部分
  910. * @param string $timestamp 当前时间戳 (为空则自动生成)
  911. * @param string $noncestr 随机串 (为空则自动生成)
  912. * @param string $appid 用于多个appid时使用,可空
  913. * @return array|bool 返回签名字串
  914. */
  915. public function getJsSign($url, $timestamp=0, $noncestr='', $appid=''){
  916. if (!$this->jsapi_ticket && !$this->getJsTicket($appid) || !$url) return false;
  917. if (!$timestamp)
  918. $timestamp = time();
  919. if (!$noncestr)
  920. $noncestr = $this->generateNonceStr();
  921. $ret = strpos($url,'#');
  922. if ($ret)
  923. $url = substr($url,0,$ret);
  924. $url = trim($url);
  925. if (empty($url))
  926. return false;
  927. $arrdata = array("timestamp" => $timestamp, "noncestr" => $noncestr, "url" => $url, "jsapi_ticket" => $this->jsapi_ticket);
  928. $sign = $this->getSignature($arrdata);
  929. if (!$sign)
  930. return false;
  931. $signPackage = array(
  932. "appid" => $this->appid,
  933. "noncestr" => $noncestr,
  934. "timestamp" => $timestamp,
  935. "url" => $url,
  936. "signature" => $sign
  937. );
  938. return $signPackage;
  939. }
  940. /**
  941. * 获取签名
  942. * @param array $arrdata 签名数组
  943. * @param string $method 签名方法
  944. * @return boolean|string 签名值
  945. */
  946. public function getSignature($arrdata,$method="sha1") {
  947. if (!function_exists($method)) return false;
  948. ksort($arrdata);
  949. $paramstring = "";
  950. foreach($arrdata as $key => $value)
  951. {
  952. if(strlen($paramstring) == 0)
  953. $paramstring .= $key . "=" . $value;
  954. else
  955. $paramstring .= "&" . $key . "=" . $value;
  956. }
  957. $Sign = $method($paramstring);
  958. return $Sign;
  959. }
  960. /**
  961. * 生成随机字串
  962. * @param number $length 长度,默认为16,最长为32字节
  963. * @return string
  964. */
  965. public function generateNonceStr($length=16){
  966. // 密码字符集,可任意添加你需要的字符
  967. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  968. $str = "";
  969. for($i = 0; $i < $length; $i++)
  970. {
  971. $str .= $chars[mt_rand(0, strlen($chars) - 1)];
  972. }
  973. return $str;
  974. }
  975. /**
  976. * 创建菜单
  977. * @param array $data 菜单数组数据
  978. * example:
  979. * array (
  980. * 'button' => array (
  981. * 0 => array (
  982. * 'name' => '扫码',
  983. * 'sub_button' => array (
  984. * 0 => array (
  985. * 'type' => 'scancode_waitmsg',
  986. * 'name' => '扫码带提示',
  987. * 'key' => 'rselfmenu_0_0',
  988. * ),
  989. * 1 => array (
  990. * 'type' => 'scancode_push',
  991. * 'name' => '扫码推事件',
  992. * 'key' => 'rselfmenu_0_1',
  993. * ),
  994. * ),
  995. * ),
  996. * 1 => array (
  997. * 'name' => '发图',
  998. * 'sub_button' => array (
  999. * 0 => array (
  1000. * 'type' => 'pic_sysphoto',
  1001. * 'name' => '系统拍照发图',
  1002. * 'key' => 'rselfmenu_1_0',
  1003. * ),
  1004. * 1 => array (
  1005. * 'type' => 'pic_photo_or_album',
  1006. * 'name' => '拍照或者相册发图',
  1007. * 'key' => 'rselfmenu_1_1',
  1008. * )
  1009. * ),
  1010. * ),
  1011. * 2 => array (
  1012. * 'type' => 'location_select',
  1013. * 'name' => '发送位置',
  1014. * 'key' => 'rselfmenu_2_0'
  1015. * ),
  1016. * ),
  1017. * )
  1018. * type可以选择为以下几种,会收到相应类型的事件推送。请注意,3到8的所有事件,仅支持微信iPhone5.4.1以上版本,
  1019. * 和Android5.4以上版本的微信用户,旧版本微信用户点击后将没有回应,开发者也不能正常接收到事件推送。
  1020. * 1、click:点击推事件
  1021. * 2、view:跳转URL
  1022. * 3、scancode_push:扫码推事件
  1023. * 4、scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
  1024. * 5、pic_sysphoto:弹出系统拍照发图
  1025. * 6、pic_photo_or_album:弹出拍照或者相册发图
  1026. * 7、pic_weixin:弹出微信相册发图器
  1027. * 8、location_select:弹出地理位置选择器
  1028. */
  1029. public function createMenu($data,$agentid=''){
  1030. if ($agentid=='') {
  1031. $agentid=$this->agentid;
  1032. }
  1033. if (!$this->access_token && !$this->checkAuth()) return false;
  1034. $result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token.'&agentid='.$agentid,self::json_encode($data));
  1035. if ($result)
  1036. {
  1037. $json = json_decode($result,true);
  1038. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1039. $this->errCode = $json['errcode'];
  1040. $this->errMsg = $json['errmsg'];
  1041. return false;
  1042. }
  1043. return true;
  1044. }
  1045. return false;
  1046. }
  1047. /**
  1048. * 获取菜单
  1049. * @return array('menu'=>array(....s))
  1050. */
  1051. public function getMenu($agentid=''){
  1052. if ($agentid=='') {
  1053. $agentid=$this->agentid;
  1054. }
  1055. if (!$this->access_token && !$this->checkAuth()) return false;
  1056. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token.'&agentid='.$agentid);
  1057. if ($result)
  1058. {
  1059. $json = json_decode($result,true);
  1060. if (!$json || isset($json['errcode']) || $json['errcode']!=0) {
  1061. $this->errCode = $json['errcode'];
  1062. $this->errMsg = $json['errmsg'];
  1063. return false;
  1064. }
  1065. return $json;
  1066. }
  1067. return false;
  1068. }
  1069. /**
  1070. * 删除菜单
  1071. * @return boolean
  1072. */
  1073. public function deleteMenu($agentid=''){
  1074. if ($agentid=='') {
  1075. $agentid=$this->agentid;
  1076. }
  1077. if (!$this->access_token && !$this->checkAuth()) return false;
  1078. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token.'&agentid='.$agentid);
  1079. if ($result)
  1080. {
  1081. $json = json_decode($result,true);
  1082. if (!$json || !empty($json['errcode'])) {
  1083. $this->errCode = $json['errcode'];
  1084. $this->errMsg = $json['errmsg'];
  1085. return false;
  1086. }
  1087. return true;
  1088. }
  1089. return false;
  1090. }
  1091. /**
  1092. * 上传多媒体文件 (只有三天的有效期,过期自动被删除)
  1093. * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
  1094. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1095. * @param array $data {"media":'@Path\filename.jpg'}
  1096. * @param type 媒体文件类型:图片(image)、语音(voice)、视频(video),普通文件(file)
  1097. * @return boolean|array
  1098. * {
  1099. * "type": "image",
  1100. * "media_id": "0000001",
  1101. * "created_at": "1380000000"
  1102. * }
  1103. */
  1104. public function uploadMedia($data, $type){
  1105. if (!$this->access_token && !$this->checkAuth()) return false;
  1106. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOAD_URL.'access_token='.$this->access_token.'&type='.$type,$data,true);
  1107. if ($result)
  1108. {
  1109. $json = json_decode($result,true);
  1110. if (!$json || !empty($json['errcode'])) {
  1111. $this->errCode = $json['errcode'];
  1112. $this->errMsg = $json['errmsg'];
  1113. return false;
  1114. }
  1115. return $json;
  1116. }
  1117. return false;
  1118. }
  1119. /**
  1120. * 根据媒体文件ID获取媒体文件
  1121. * @param string $media_id 媒体文件id
  1122. * @return raw data
  1123. */
  1124. public function getMedia($media_id){
  1125. if (!$this->access_token && !$this->checkAuth()) return false;
  1126. $result = $this->http_get(self::API_URL_PREFIX.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
  1127. if ($result)
  1128. {
  1129. $json = json_decode($result,true);
  1130. if (isset($json['errcode'])) {
  1131. $this->errCode = $json['errcode'];
  1132. $this->errMsg = $json['errmsg'];
  1133. return false;
  1134. }
  1135. return $result;
  1136. }
  1137. return false;
  1138. }
  1139. /**
  1140. * 获取企业微信服务器IP地址列表
  1141. * @return array('127.0.0.1','127.0.0.1')
  1142. */
  1143. public function getServerIp(){
  1144. if (!$this->access_token && !$this->checkAuth()) return false;
  1145. $result = $this->http_get(self::API_URL_PREFIX.self::CALLBACKSERVER_GET_URL.'access_token='.$this->access_token);
  1146. if ($result)
  1147. {
  1148. $json = json_decode($result,true);
  1149. if (!$json || isset($json['errcode'])) {
  1150. $this->errCode = $json['errcode'];
  1151. $this->errMsg = $json['errmsg'];
  1152. return false;
  1153. }
  1154. return $json['ip_list'];
  1155. }
  1156. return false;
  1157. }
  1158. /**
  1159. * 创建部门
  1160. * @param array $data 结构体为:
  1161. * array (
  1162. * "name" => "邮箱产品组", //部门名称
  1163. * "parentid" => "1" //父部门id
  1164. * "order" => "1", //(非必须)在父部门中的次序。从1开始,数字越大排序越靠后
  1165. * )
  1166. * @return boolean|array
  1167. * 成功返回结果
  1168. * {
  1169. * "errcode": 0, //返回码
  1170. * "errmsg": "created", //对返回码的文本描述内容
  1171. * "id": 2 //创建的部门id。
  1172. * }
  1173. */
  1174. public function createDepartment($data){
  1175. if (!$this->access_token && !$this->checkAuth()) return false;
  1176. $result = $this->http_post(self::API_URL_PREFIX.self::DEPARTMENT_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1177. if ($result)
  1178. {
  1179. $json = json_decode($result,true);
  1180. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1181. $this->errCode = $json['errcode'];
  1182. $this->errMsg = $json['errmsg'];
  1183. return false;
  1184. }
  1185. return $json;
  1186. }
  1187. return false;
  1188. }
  1189. /**
  1190. * 更新部门
  1191. * @param array $data 结构体为:
  1192. * array(
  1193. * "id" => "1" //(必须)部门id
  1194. * "name" => "邮箱产品组", //(非必须)部门名称
  1195. * "parentid" => "1", //(非必须)父亲部门id。根部门id为1
  1196. * "order" => "1", //(非必须)在父部门中的次序。从1开始,数字越大排序越靠后
  1197. * )
  1198. * @return boolean|array 成功返回结果
  1199. * {
  1200. * "errcode": 0, //返回码
  1201. * "errmsg": "updated" //对返回码的文本描述内容
  1202. * }
  1203. */
  1204. public function updateDepartment($data){
  1205. if (!$this->access_token && !$this->checkAuth()) return false;
  1206. $result = $this->http_post(self::API_URL_PREFIX.self::DEPARTMENT_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1207. if ($result)
  1208. {
  1209. $json = json_decode($result,true);
  1210. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1211. $this->errCode = $json['errcode'];
  1212. $this->errMsg = $json['errmsg'];
  1213. return false;
  1214. }
  1215. return $json;
  1216. }
  1217. return false;
  1218. }
  1219. /**
  1220. * 删除部门
  1221. * @param $id
  1222. * @return boolean|array 成功返回结果
  1223. * {
  1224. * "errcode": 0, //返回码
  1225. * "errmsg": "deleted" //对返回码的文本描述内容
  1226. * }
  1227. */
  1228. public function deleteDepartment($id){
  1229. if (!$this->access_token && !$this->checkAuth()) return false;
  1230. $result = $this->http_get(self::API_URL_PREFIX.self::DEPARTMENT_DELETE_URL.'access_token='.$this->access_token.'&id='.$id);
  1231. if ($result)
  1232. {
  1233. $json = json_decode($result,true);
  1234. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1235. $this->errCode = $json['errcode'];
  1236. $this->errMsg = $json['errmsg'];
  1237. return false;
  1238. }
  1239. return $json;
  1240. }
  1241. return false;
  1242. }
  1243. /**
  1244. * 移动部门
  1245. * @param $data
  1246. * array(
  1247. * "department_id" => "5", //所要移动的部门
  1248. * "to_parentid" => "2", //想移动到的父部门节点,根部门为1
  1249. * "to_position" => "1" //(非必须)想移动到的父部门下的位置,1表示最上方,往后位置为2,3,4,以此类推,默认为1
  1250. * )
  1251. * @return boolean|array 成功返回结果
  1252. * {
  1253. * "errcode": 0, //返回码
  1254. * "errmsg": "ok" //对返回码的文本描述内容
  1255. * }
  1256. */
  1257. public function moveDepartment($data){
  1258. if (!$this->access_token && !$this->checkAuth()) return false;
  1259. $result = $this->http_post(self::API_URL_PREFIX.self::DEPARTMENT_MOVE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1260. if ($result)
  1261. {
  1262. $json = json_decode($result,true);
  1263. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1264. $this->errCode = $json['errcode'];
  1265. $this->errMsg = $json['errmsg'];
  1266. return false;
  1267. }
  1268. return $json;
  1269. }
  1270. return false;
  1271. }
  1272. /**
  1273. * 获取部门列表
  1274. * @return boolean|array 成功返回结果
  1275. * {
  1276. * "errcode": 0,
  1277. * "errmsg": "ok",
  1278. * "department": [ //部门列表数据。以部门的order字段从小到大排列
  1279. * {
  1280. * "id": 1,
  1281. * "name": "广州研发中心",
  1282. * "parentid": 0,
  1283. * "order": 40
  1284. * },
  1285. * {
  1286. * "id": 2
  1287. * "name": "邮箱产品部",
  1288. * "parentid": 1,
  1289. * "order": 40
  1290. * }
  1291. * ]
  1292. * }
  1293. */
  1294. public function getDepartment(){
  1295. if (!$this->access_token && !$this->checkAuth()) return false;
  1296. $result = $this->http_get(self::API_URL_PREFIX.self::DEPARTMENT_LIST_URL.'access_token='.$this->access_token);
  1297. if ($result)
  1298. {
  1299. $json = json_decode($result,true);
  1300. if (!$json || !empty($json['errcode'])) {
  1301. $this->errCode = $json['errcode'];
  1302. $this->errMsg = $json['errmsg'];
  1303. return false;
  1304. }
  1305. return $json;
  1306. }
  1307. return false;
  1308. }
  1309. /**
  1310. * 创建成员
  1311. * @param array $data 结构体为:
  1312. * array(
  1313. * "userid" => "zhangsan",
  1314. * "name" => "张三",
  1315. * "department" => [1, 2],
  1316. * "position" => "产品经理",
  1317. * "mobile" => "15913215421",
  1318. * "gender" => 1, //性别。gender=0表示男,=1表示女
  1319. * "tel" => "62394",
  1320. * "email" => "zhangsan@gzdev.com",
  1321. * "weixinid" => "zhangsan4dev"
  1322. * )
  1323. * @return boolean|array
  1324. * 成功返回结果
  1325. * {
  1326. * "errcode": 0, //返回码
  1327. * "errmsg": "created", //对返回码的文本描述内容
  1328. * }
  1329. */
  1330. public function createUser($data){
  1331. if (!$this->access_token && !$this->checkAuth()) return false;
  1332. $result = $this->http_post(self::API_URL_PREFIX.self::USER_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1333. if ($result)
  1334. {
  1335. $json = json_decode($result,true);
  1336. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1337. $this->errCode = $json['errcode'];
  1338. $this->errMsg = $json['errmsg'];
  1339. return false;
  1340. }
  1341. return $json;
  1342. }
  1343. return false;
  1344. }
  1345. /**
  1346. * 更新成员
  1347. * @param array $data 结构体为:
  1348. * array(
  1349. * "userid" => "zhangsan",
  1350. * "name" => "张三",
  1351. * "department" => [1, 2],
  1352. * "position" => "产品经理",
  1353. * "mobile" => "15913215421",
  1354. * "gender" => 1, //性别。gender=0表示男,=1表示女
  1355. * "tel" => "62394",
  1356. * "email" => "zhangsan@gzdev.com",
  1357. * "weixinid" => "zhangsan4dev"
  1358. * )
  1359. * @return boolean|array 成功返回结果
  1360. * {
  1361. * "errcode": 0, //返回码
  1362. * "errmsg": "updated" //对返回码的文本描述内容
  1363. * }
  1364. */
  1365. public function updateUser($data){
  1366. if (!$this->access_token && !$this->checkAuth()) return false;
  1367. $result = $this->http_post(self::API_URL_PREFIX.self::USER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1368. if ($result)
  1369. {
  1370. $json = json_decode($result,true);
  1371. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1372. $this->errCode = $json['errcode'];
  1373. $this->errMsg = $json['errmsg'];
  1374. return false;
  1375. }
  1376. return $json;
  1377. }
  1378. return false;
  1379. }
  1380. /**
  1381. * 删除成员
  1382. * @param $userid 员工UserID。对应管理端的帐号
  1383. * @return boolean|array 成功返回结果
  1384. * {
  1385. * "errcode": 0, //返回码
  1386. * "errmsg": "deleted" //对返回码的文本描述内容
  1387. * }
  1388. */
  1389. public function deleteUser($userid){
  1390. if (!$this->access_token && !$this->checkAuth()) return false;
  1391. $result = $this->http_get(self::API_URL_PREFIX.self::USER_DELETE_URL.'access_token='.$this->access_token.'&userid='.$userid);
  1392. if ($result)
  1393. {
  1394. $json = json_decode($result,true);
  1395. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1396. $this->errCode = $json['errcode'];
  1397. $this->errMsg = $json['errmsg'];
  1398. return false;
  1399. }
  1400. return $json;
  1401. }
  1402. return false;
  1403. }
  1404. /**
  1405. * 批量删除成员
  1406. * @param array $userid 员工UserID数组。对应管理端的帐号
  1407. * {
  1408. * 'userid1',
  1409. * 'userid2',
  1410. * 'userid3',
  1411. * }
  1412. * @return boolean|array 成功返回结果
  1413. * {
  1414. * "errcode": 0, //返回码
  1415. * "errmsg": "deleted" //对返回码的文本描述内容
  1416. * }
  1417. */
  1418. public function deleteUsers($userids){
  1419. if (!$userids) return false;
  1420. $data = array('useridlist'=>$userids);
  1421. if (!$this->access_token && !$this->checkAuth()) return false;
  1422. $result = $this->http_post(self::API_URL_PREFIX.self::USER_BATCHDELETE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1423. if ($result)
  1424. {
  1425. $json = json_decode($result,true);
  1426. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1427. $this->errCode = $json['errcode'];
  1428. $this->errMsg = $json['errmsg'];
  1429. return false;
  1430. }
  1431. return $json;
  1432. }
  1433. return false;
  1434. }
  1435. /**
  1436. * 获取成员信息
  1437. * @param $userid 员工UserID。对应管理端的帐号
  1438. * @return boolean|array 成功返回结果
  1439. * {
  1440. * "errcode": 0,
  1441. * "errmsg": "ok",
  1442. * "userid": "zhangsan",
  1443. * "name": "李四",
  1444. * "department": [1, 2],
  1445. * "position": "后台工程师",
  1446. * "mobile": "15913215421",
  1447. * "gender": 1, //性别。gender=0表示男,=1表示女
  1448. * "tel": "62394",
  1449. * "email": "zhangsan@gzdev.com",
  1450. * "weixinid": "lisifordev", //微信号
  1451. * "avatar": "http://wx.qlogo.cn/mmopen/ajNVdqHZLLA3W..../0", //头像url。注:如果要获取小图将url最后的"/0"改成"/64"即可
  1452. * "status": 1 //关注状态: 1=已关注,2=已冻结,4=未关注
  1453. * "extattr": {"attrs":[{"name":"爱好","value":"旅游"},{"name":"卡号","value":"1234567234"}]}
  1454. * }
  1455. */
  1456. public function getUserInfo($userid){
  1457. if (!$this->access_token && !$this->checkAuth()) return false;
  1458. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&userid='.$userid);
  1459. if ($result)
  1460. {
  1461. $json = json_decode($result,true);
  1462. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1463. $this->errCode = $json['errcode'];
  1464. $this->errMsg = $json['errmsg'];
  1465. return false;
  1466. }
  1467. return $json;
  1468. }
  1469. return false;
  1470. }
  1471. /**
  1472. * 获取部门成员
  1473. * @param $department_id 部门id
  1474. * @param $fetch_child 1/0:是否递归获取子部门下面的成员
  1475. * @param $status 0获取全部员工,1获取已关注成员列表,2获取禁用成员列表,4获取未关注成员列表。status可叠加
  1476. * @return boolean|array 成功返回结果
  1477. * {
  1478. * "errcode": 0,
  1479. * "errmsg": "ok",
  1480. * "userlist": [
  1481. * {
  1482. * "userid": "zhangsan",
  1483. * "name": "李四"
  1484. * }
  1485. * ]
  1486. * }
  1487. */
  1488. public function getUserList($department_id,$fetch_child=0,$status=0){
  1489. if (!$this->access_token && !$this->checkAuth()) return false;
  1490. $result = $this->http_get(self::API_URL_PREFIX.self::USER_LIST_URL.'access_token='.$this->access_token
  1491. .'&department_id='.$department_id.'&fetch_child='.$fetch_child.'&status='.$status);
  1492. if ($result)
  1493. {
  1494. $json = json_decode($result,true);
  1495. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1496. $this->errCode = $json['errcode'];
  1497. $this->errMsg = $json['errmsg'];
  1498. return false;
  1499. }
  1500. return $json;
  1501. }
  1502. return false;
  1503. }
  1504. /**
  1505. * 获取部门成员详情
  1506. * @param $department_id 部门id
  1507. * @param $fetch_child 1/0:是否递归获取子部门下面的成员
  1508. * @param $status 0获取全部员工,1获取已关注成员列表,2获取禁用成员列表,4获取未关注成员列表。status可叠加
  1509. * @return boolean|array 成功返回结果
  1510. * {
  1511. * "errcode": 0,
  1512. * "errmsg": "ok",
  1513. * "userlist": [
  1514. * {
  1515. * "userid": "zhangsan",
  1516. * "name": "李四",
  1517. * "department": [1, 2],
  1518. * "position": "后台工程师",
  1519. * "mobile": "15913215421",
  1520. * "gender": 1, //性别。gender=0表示男,=1表示女
  1521. * "tel": "62394",
  1522. * "email": "zhangsan@gzdev.com",
  1523. * "weixinid": "lisifordev", //微信号
  1524. * "avatar": "http://wx.qlogo.cn/mmopen/ajNVdqHZLLA3W..../0", //头像url。注:如果要获取小图将url最后的"/0"改成"/64"即可
  1525. * "status": 1 //关注状态: 1=已关注,2=已冻结,4=未关注
  1526. * "extattr": {"attrs":[{"name":"爱好","value":"旅游"},{"name":"卡号","value":"1234567234"}]}
  1527. * }
  1528. * ]
  1529. * }
  1530. */
  1531. public function getUserListInfo($department_id,$fetch_child=0,$status=0){
  1532. if (!$this->access_token && !$this->checkAuth()) return false;
  1533. $result = $this->http_get(self::API_URL_PREFIX.self::USER_LIST_INFO_URL.'access_token='.$this->access_token
  1534. .'&department_id='.$department_id.'&fetch_child='.$fetch_child.'&status='.$status);
  1535. if ($result)
  1536. {
  1537. $json = json_decode($result,true);
  1538. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1539. $this->errCode = $json['errcode'];
  1540. $this->errMsg = $json['errmsg'];
  1541. return false;
  1542. }
  1543. return $json;
  1544. }
  1545. return false;
  1546. }
  1547. /**
  1548. * 根据code获取成员信息
  1549. * 通过Oauth2.0或者设置了二次验证时获取的code,用于换取成员的UserId和DeviceId
  1550. *
  1551. * @param $code Oauth2.0或者二次验证时返回的code值
  1552. * @param $agentid 跳转链接时所在的企业应用ID,未填则默认为当前配置的应用id
  1553. * @return boolean|array 成功返回数组
  1554. * array(
  1555. * 'UserId' => 'USERID', //员工UserID
  1556. * 'DeviceId' => 'DEVICEID' //手机设备号(由微信在安装时随机生成)
  1557. * )
  1558. */
  1559. public function getUserId($code,$agentid=0){
  1560. if (!$agentid) $agentid=$this->agentid;
  1561. if (!$this->access_token && !$this->checkAuth()) return false;
  1562. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GETINFO_URL.'access_token='.$this->access_token.'&code='.$code.'&agentid='.$agentid);
  1563. if ($result)
  1564. {
  1565. $json = json_decode($result,true);
  1566. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1567. $this->errCode = $json['errcode'];
  1568. $this->errMsg = $json['errmsg'];
  1569. return false;
  1570. }
  1571. return $json;
  1572. }
  1573. return false;
  1574. }
  1575. /**
  1576. * 邀请成员关注
  1577. * 向未关注企业号的成员发送关注邀请。认证号优先判断顺序weixinid>手机号>邮箱绑定>邮件;非认证号只能邮件邀请
  1578. *
  1579. * @param $userid 用户的userid
  1580. * @param $invite_tips 推送到微信上的提示语(只有认证号可以使用)。当使用微信推送时,该字段默认为“请关注XXX企业号”,邮件邀请时,该字段无效。
  1581. * @return boolean|array 成功返回数组
  1582. * array(
  1583. * 'errcode' => 0,
  1584. * 'errmsg' => 'ok',
  1585. * 'type' => 1 //邀请方式 1.微信邀请 2.邮件邀请
  1586. * )
  1587. */
  1588. public function sendInvite($userid,$invite_tips=''){
  1589. $data = array( 'userid' => $userid );
  1590. if (!$invite_tips) {
  1591. $data['invite_tips'] = $invite_tips;
  1592. }
  1593. if (!$this->access_token && !$this->checkAuth()) return false;
  1594. $result = $this->http_post(self::API_URL_PREFIX.self::USER_INVITE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1595. if ($result)
  1596. {
  1597. $json = json_decode($result,true);
  1598. if (!$json || !empty($json['errcode'])) {
  1599. $this->errCode = $json['errcode'];
  1600. $this->errMsg = $json['errmsg'];
  1601. return false;
  1602. }
  1603. return $json;
  1604. }
  1605. return false;
  1606. }
  1607. /**
  1608. * 创建标签
  1609. * @param array $data 结构体为:
  1610. * array(
  1611. * "tagname" => "UI"
  1612. * )
  1613. * @return boolean|array
  1614. * 成功返回结果
  1615. * {
  1616. * "errcode": 0, //返回码
  1617. * "errmsg": "created", //对返回码的文本描述内容
  1618. * "tagid": "1"
  1619. * }
  1620. */
  1621. public function createTag($data){
  1622. if (!$this->access_token && !$this->checkAuth()) return false;
  1623. $result = $this->http_post(self::API_URL_PREFIX.self::TAG_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1624. if ($result)
  1625. {
  1626. $json = json_decode($result,true);
  1627. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1628. $this->errCode = $json['errcode'];
  1629. $this->errMsg = $json['errmsg'];
  1630. return false;
  1631. }
  1632. return $json;
  1633. }
  1634. return false;
  1635. }
  1636. /**
  1637. * 更新标签
  1638. * @param array $data 结构体为:
  1639. * array(
  1640. * "tagid" => "1",
  1641. * "tagname" => "UI design"
  1642. * )
  1643. * @return boolean|array 成功返回结果
  1644. * {
  1645. * "errcode": 0, //返回码
  1646. * "errmsg": "updated" //对返回码的文本描述内容
  1647. * }
  1648. */
  1649. public function updateTag($data){
  1650. if (!$this->access_token && !$this->checkAuth()) return false;
  1651. $result = $this->http_post(self::API_URL_PREFIX.self::TAG_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1652. if ($result)
  1653. {
  1654. $json = json_decode($result,true);
  1655. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1656. $this->errCode = $json['errcode'];
  1657. $this->errMsg = $json['errmsg'];
  1658. return false;
  1659. }
  1660. return $json;
  1661. }
  1662. return false;
  1663. }
  1664. /**
  1665. * 删除标签
  1666. * @param $tagid 标签TagID
  1667. * @return boolean|array 成功返回结果
  1668. * {
  1669. * "errcode": 0, //返回码
  1670. * "errmsg": "deleted" //对返回码的文本描述内容
  1671. * }
  1672. */
  1673. public function deleteTag($tagid){
  1674. if (!$this->access_token && !$this->checkAuth()) return false;
  1675. $result = $this->http_get(self::API_URL_PREFIX.self::TAG_DELETE_URL.'access_token='.$this->access_token.'&tagid='.$tagid);
  1676. if ($result)
  1677. {
  1678. $json = json_decode($result,true);
  1679. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1680. $this->errCode = $json['errcode'];
  1681. $this->errMsg = $json['errmsg'];
  1682. return false;
  1683. }
  1684. return $json;
  1685. }
  1686. return false;
  1687. }
  1688. /**
  1689. * 获取标签成员
  1690. * @param $tagid 标签TagID
  1691. * @return boolean|array 成功返回结果
  1692. * {
  1693. * "errcode": 0,
  1694. * "errmsg": "ok",
  1695. * "userlist": [
  1696. * {
  1697. * "userid": "zhangsan",
  1698. * "name": "李四"
  1699. * }
  1700. * ]
  1701. * }
  1702. */
  1703. public function getTag($tagid){
  1704. if (!$this->access_token && !$this->checkAuth()) return false;
  1705. $result = $this->http_get(self::API_URL_PREFIX.self::TAG_GET_URL.'access_token='.$this->access_token.'&tagid='.$tagid);
  1706. if ($result)
  1707. {
  1708. $json = json_decode($result,true);
  1709. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1710. $this->errCode = $json['errcode'];
  1711. $this->errMsg = $json['errmsg'];
  1712. return false;
  1713. }
  1714. return $json;
  1715. }
  1716. return false;
  1717. }
  1718. /**
  1719. * 增加标签成员
  1720. * @param array $data 结构体为:
  1721. * array (
  1722. * "tagid" => "1",
  1723. * "userlist" => array( //企业员工ID列表
  1724. * "user1",
  1725. * "user2"
  1726. * )
  1727. * )
  1728. * @return boolean|array
  1729. * 成功返回结果
  1730. * {
  1731. * "errcode": 0, //返回码
  1732. * "errmsg": "ok", //对返回码的文本描述内容
  1733. * "invalidlist":"usr1|usr2|usr" //若部分userid非法,则会有此段。不在权限内的员工ID列表,以“|”分隔
  1734. * }
  1735. */
  1736. public function addTagUser($data){
  1737. if (!$this->access_token && !$this->checkAuth()) return false;
  1738. $result = $this->http_post(self::API_URL_PREFIX.self::TAG_ADDUSER_URL.'access_token='.$this->access_token,self::json_encode($data));
  1739. if ($result)
  1740. {
  1741. $json = json_decode($result,true);
  1742. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1743. $this->errCode = $json['errcode'];
  1744. $this->errMsg = $json['errmsg'];
  1745. return false;
  1746. }
  1747. return $json;
  1748. }
  1749. return false;
  1750. }
  1751. /**
  1752. * 删除标签成员
  1753. * @param array $data 结构体为:
  1754. * array (
  1755. * "tagid" => "1",
  1756. * "userlist" => array( //企业员工ID列表
  1757. * "user1",
  1758. * "user2"
  1759. * )
  1760. * )
  1761. * @return boolean|array
  1762. * 成功返回结果
  1763. * {
  1764. * "errcode": 0, //返回码
  1765. * "errmsg": "deleted", //对返回码的文本描述内容
  1766. * "invalidlist":"usr1|usr2|usr" //若部分userid非法,则会有此段。不在权限内的员工ID列表,以“|”分隔
  1767. * }
  1768. */
  1769. public function delTagUser($data){
  1770. if (!$this->access_token && !$this->checkAuth()) return false;
  1771. $result = $this->http_post(self::API_URL_PREFIX.self::TAG_DELUSER_URL.'access_token='.$this->access_token,self::json_encode($data));
  1772. if ($result)
  1773. {
  1774. $json = json_decode($result,true);
  1775. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1776. $this->errCode = $json['errcode'];
  1777. $this->errMsg = $json['errmsg'];
  1778. return false;
  1779. }
  1780. return $json;
  1781. }
  1782. return false;
  1783. }
  1784. /**
  1785. * 获取标签列表
  1786. * @return boolean|array 成功返回数组结果,这里附上json样例
  1787. * {
  1788. * "errcode": 0,
  1789. * "errmsg": "ok",
  1790. * "taglist":[
  1791. * {"tagid":1,"tagname":"a"},
  1792. * {"tagid":2,"tagname":"b"}
  1793. * ]
  1794. * }
  1795. */
  1796. public function getTagList(){
  1797. if (!$this->access_token && !$this->checkAuth()) return false;
  1798. $result = $this->http_get(self::API_URL_PREFIX.self::TAG_LIST_URL.'access_token='.$this->access_token);
  1799. if ($result)
  1800. {
  1801. $json = json_decode($result,true);
  1802. if (!$json || !empty($json['errcode'])) {
  1803. $this->errCode = $json['errcode'];
  1804. $this->errMsg = $json['errmsg'];
  1805. return false;
  1806. }
  1807. return $json;
  1808. }
  1809. return false;
  1810. }
  1811. /**
  1812. * 主动发送信息接口
  1813. * @param array $data 结构体为:
  1814. * array(
  1815. * "touser" => "UserID1|UserID2|UserID3",
  1816. * "toparty" => "PartyID1|PartyID2 ",
  1817. * "totag" => "TagID1|TagID2 ",
  1818. * "safe":"0" //是否为保密消息,对于news无效
  1819. * "agentid" => "001", //应用id
  1820. * "msgtype" => "text", //根据信息类型,选择下面对应的信息结构体
  1821. *
  1822. * "text" => array(
  1823. * "content" => "Holiday Request For Pony(http://xxxxx)"
  1824. * ),
  1825. *
  1826. * "image" => array(
  1827. * "media_id" => "MEDIA_ID"
  1828. * ),
  1829. *
  1830. * "voice" => array(
  1831. * "media_id" => "MEDIA_ID"
  1832. * ),
  1833. *
  1834. * " video" => array(
  1835. * "media_id" => "MEDIA_ID",
  1836. * "title" => "Title",
  1837. * "description" => "Description"
  1838. * ),
  1839. *
  1840. * "file" => array(
  1841. * "media_id" => "MEDIA_ID"
  1842. * ),
  1843. *
  1844. * "news" => array( //不支持保密
  1845. * "articles" => array( //articles 图文消息,一个图文消息支持1到10个图文
  1846. * array(
  1847. * "title" => "Title", //标题
  1848. * "description" => "Description", //描述
  1849. * "url" => "URL", //点击后跳转的链接。可根据url里面带的code参数校验员工的真实身份。
  1850. * "picurl" => "PIC_URL", //图文消息的图片链接,支持JPG、PNG格式,较好的效果为大图640*320,
  1851. * //小图80*80。如不填,在客户端不显示图片
  1852. * ),
  1853. * )
  1854. * ),
  1855. *
  1856. * "mpnews" => array(
  1857. * "articles" => array( //articles 图文消息,一个图文消息支持1到10个图文
  1858. * array(
  1859. * "title" => "Title", //图文消息的标题
  1860. * "thumb_media_id" => "id", //图文消息缩略图的media_id
  1861. * "author" => "Author", //图文消息的作者(可空)
  1862. * "content_source_url" => "URL", //图文消息点击“阅读原文”之后的页面链接(可空)
  1863. * "content" => "Content" //图文消息的内容,支持html标签
  1864. * "digest" => "Digest description", //图文消息的描述
  1865. * "show_cover_pic" => "0" //是否显示封面,1为显示,0为不显示(可空)
  1866. * ),
  1867. * )
  1868. * )
  1869. * )
  1870. * 请查看官方开发文档中的 发送消息 -> 消息类型及数据格式
  1871. *
  1872. * @return boolean|array
  1873. * 如果对应用或收件人、部门、标签任何一个无权限,则本次发送失败;
  1874. * 如果收件人、部门或标签不存在,发送仍然执行,但返回无效的部分。
  1875. * {
  1876. * "errcode": 0,
  1877. * "errmsg": "ok",
  1878. * "invaliduser": "UserID1",
  1879. * "invalidparty":"PartyID1",
  1880. * "invalidtag":"TagID1"
  1881. * }
  1882. */
  1883. public function sendMessage($data){
  1884. if (!$this->access_token && !$this->checkAuth()) return false;
  1885. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1886. if ($result)
  1887. {
  1888. $json = json_decode($result,true);
  1889. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1890. $this->errCode = $json['errcode'];
  1891. $this->errMsg = $json['errmsg'];
  1892. return false;
  1893. }
  1894. return $json;
  1895. }
  1896. return false;
  1897. }
  1898. /**
  1899. * 二次验证
  1900. * 企业在开启二次验证时,必须填写企业二次验证页面的url。
  1901. * 当员工绑定通讯录中的帐号后,会收到一条图文消息,
  1902. * 引导员工到企业的验证页面验证身份,企业在员工验证成功后,
  1903. * 调用如下接口即可让员工关注成功。
  1904. *
  1905. * @param $userid
  1906. * @return boolean|array 成功返回结果
  1907. * {
  1908. * "errcode": 0, //返回码
  1909. * "errmsg": "ok" //对返回码的文本描述内容
  1910. * }
  1911. */
  1912. public function authSucc($userid){
  1913. if (!$this->access_token && !$this->checkAuth()) return false;
  1914. $result = $this->http_get(self::API_URL_PREFIX.self::AUTHSUCC_URL.'access_token='.$this->access_token.'&userid='.$userid);
  1915. if ($result)
  1916. {
  1917. $json = json_decode($result,true);
  1918. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1919. $this->errCode = $json['errcode'];
  1920. $this->errMsg = $json['errmsg'];
  1921. return false;
  1922. }
  1923. return $json;
  1924. }
  1925. return false;
  1926. }
  1927. /**
  1928. * oauth 授权跳转接口
  1929. * @param string $callback 回调URI
  1930. * @param string $state 重定向后会带上state参数,企业可以填写a-zA-Z0-9的参数值
  1931. * @return string
  1932. */
  1933. public function getOauthRedirect($callback,$state='STATE',$scope='snsapi_base'){
  1934. return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  1935. }
  1936. }
  1937. /**
  1938. * PKCS7Encoder class
  1939. *
  1940. * 提供基于PKCS7算法的加解密接口.
  1941. */
  1942. class PKCS7Encoder
  1943. {
  1944. public static $block_size = 32;
  1945. /**
  1946. * 对需要加密的明文进行填充补位
  1947. * @param $text 需要进行填充补位操作的明文
  1948. * @return 补齐明文字符串
  1949. */
  1950. function encode($text)
  1951. {
  1952. $block_size = PKCS7Encoder::$block_size;
  1953. $text_length = strlen($text);
  1954. //计算需要填充的位数
  1955. $amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
  1956. if ($amount_to_pad == 0) {
  1957. $amount_to_pad = PKCS7Encoder::block_size;
  1958. }
  1959. //获得补位所用的字符
  1960. $pad_chr = chr($amount_to_pad);
  1961. $tmp = "";
  1962. for ($index = 0; $index < $amount_to_pad; $index++) {
  1963. $tmp .= $pad_chr;
  1964. }
  1965. return $text . $tmp;
  1966. }
  1967. /**
  1968. * 对解密后的明文进行补位删除
  1969. * @param decrypted 解密后的明文
  1970. * @return 删除填充补位后的明文
  1971. */
  1972. function decode($text)
  1973. {
  1974. $pad = ord(substr($text, -1));
  1975. if ($pad < 1 || $pad > PKCS7Encoder::$block_size) {
  1976. $pad = 0;
  1977. }
  1978. return substr($text, 0, (strlen($text) - $pad));
  1979. }
  1980. }
  1981. /**
  1982. * Prpcrypt class
  1983. *
  1984. * 提供接收和推送给公众平台消息的加解密接口.
  1985. */
  1986. class Prpcrypt
  1987. {
  1988. public $key;
  1989. function __construct($k) {
  1990. $this->key = base64_decode($k . "=");
  1991. }
  1992. /**
  1993. * 兼容老版本php构造函数,不能在 __construct() 方法前边,否则报错
  1994. */
  1995. function Prpcrypt($k)
  1996. {
  1997. $this->key = base64_decode($k . "=");
  1998. }
  1999. /**
  2000. * 对明文进行加密
  2001. * @param string $text 需要加密的明文
  2002. * @return string 加密后的密文
  2003. */
  2004. public function encrypt($text, $appid)
  2005. {
  2006. try {
  2007. //获得16位随机字符串,填充到明文之前
  2008. $random = $this->getRandomStr();//"aaaabbbbccccdddd";
  2009. $text = $random . pack("N", strlen($text)) . $text . $appid;
  2010. // 网络字节序
  2011. $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  2012. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  2013. $iv = substr($this->key, 0, 16);
  2014. //使用自定义的填充方式对明文进行补位填充
  2015. $pkc_encoder = new PKCS7Encoder;
  2016. $text = $pkc_encoder->encode($text);
  2017. mcrypt_generic_init($module, $this->key, $iv);
  2018. //加密
  2019. $encrypted = mcrypt_generic($module, $text);
  2020. mcrypt_generic_deinit($module);
  2021. mcrypt_module_close($module);
  2022. // print(base64_encode($encrypted));
  2023. //使用BASE64对加密后的字符串进行编码
  2024. return array(ErrorCode::$OK, base64_encode($encrypted));
  2025. } catch (Exception $e) {
  2026. //print $e;
  2027. return array(ErrorCode::$EncryptAESError, null);
  2028. }
  2029. }
  2030. /**
  2031. * 对密文进行解密
  2032. * @param string $encrypted 需要解密的密文
  2033. * @return string 解密得到的明文
  2034. */
  2035. public function decrypt($encrypted, $appid)
  2036. {
  2037. try {
  2038. //使用BASE64对需要解密的字符串进行解码
  2039. $ciphertext_dec = base64_decode($encrypted);
  2040. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  2041. $iv = substr($this->key, 0, 16);
  2042. mcrypt_generic_init($module, $this->key, $iv);
  2043. //解密
  2044. $decrypted = mdecrypt_generic($module, $ciphertext_dec);
  2045. mcrypt_generic_deinit($module);
  2046. mcrypt_module_close($module);
  2047. } catch (Exception $e) {
  2048. return array(ErrorCode::$DecryptAESError, null);
  2049. }
  2050. try {
  2051. //去除补位字符
  2052. $pkc_encoder = new PKCS7Encoder;
  2053. $result = $pkc_encoder->decode($decrypted);
  2054. //去除16位随机字符串,网络字节序和AppId
  2055. if (strlen($result) < 16)
  2056. return "";
  2057. $content = substr($result, 16, strlen($result));
  2058. $len_list = unpack("N", substr($content, 0, 4));
  2059. $xml_len = $len_list[1];
  2060. $xml_content = substr($content, 4, $xml_len);
  2061. $from_appid = substr($content, $xml_len + 4);
  2062. } catch (Exception $e) {
  2063. //print $e;
  2064. return array(ErrorCode::$IllegalBuffer, null);
  2065. }
  2066. if ($from_appid != $appid)
  2067. return array(ErrorCode::$ValidateAppidError, null);
  2068. return array(0, $xml_content);
  2069. }
  2070. /**
  2071. * 随机生成16位字符串
  2072. * @return string 生成的字符串
  2073. */
  2074. function getRandomStr()
  2075. {
  2076. $str = "";
  2077. $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  2078. $max = strlen($str_pol) - 1;
  2079. for ($i = 0; $i < 16; $i++) {
  2080. $str .= $str_pol[mt_rand(0, $max)];
  2081. }
  2082. return $str;
  2083. }
  2084. }
  2085. /**
  2086. * error code
  2087. * 仅用作类内部使用,不用于官方API接口的errCode码
  2088. */
  2089. class ErrorCode
  2090. {
  2091. public static $OK = 0;
  2092. public static $ValidateSignatureError = 40001;
  2093. public static $ParseXmlError = 40002;
  2094. public static $ComputeSignatureError = 40003;
  2095. public static $IllegalAesKey = 40004;
  2096. public static $ValidateAppidError = 40005;
  2097. public static $EncryptAESError = 40006;
  2098. public static $DecryptAESError = 40007;
  2099. public static $IllegalBuffer = 40008;
  2100. public static $EncodeBase64Error = 40009;
  2101. public static $DecodeBase64Error = 40010;
  2102. public static $GenReturnXmlError = 40011;
  2103. public static $errCode=array(
  2104. '0'=>'无问题',
  2105. '40001'=>'签名验证错误',
  2106. '40002'=>'xml解析失败',
  2107. '40003'=>'sha加密生成签名失败',
  2108. '40004'=>'encodingAesKey 非法',
  2109. '40005'=>'appid 校验错误',
  2110. '40006'=>'aes 加密失败',
  2111. '40007'=>'aes 解密失败',
  2112. '40008'=>'解密后得到的buffer非法',
  2113. '40009'=>'base64加密失败',
  2114. '40010'=>'base64解密失败',
  2115. '40011'=>'生成xml失败',
  2116. );
  2117. public static function getErrText($err) {
  2118. if (isset(self::$errCode[$err])) {
  2119. return self::$errCode[$err];
  2120. }else {
  2121. return false;
  2122. };
  2123. }
  2124. }