qywechat.class.php 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045
  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 DEPARTMENT_CREATE_URL = '/department/create?';
  54. const DEPARTMENT_UPDATE_URL = '/department/update?';
  55. const DEPARTMENT_DELETE_URL = '/department/delete?';
  56. const DEPARTMENT_MOVE_URL = '/department/move?';
  57. const DEPARTMENT_LIST_URL = '/department/list?';
  58. const TAG_CREATE_URL = '/tag/create?';
  59. const TAG_UPDATE_URL = '/tag/update?';
  60. const TAG_DELETE_URL = '/tag/delete?';
  61. const TAG_GET_URL = '/tag/get?';
  62. const TAG_ADDUSER_URL = '/tag/addtagusers?';
  63. const TAG_DELUSER_URL = '/tag/deltagusers?';
  64. const TAG_LIST_URL = '/tag/list?';
  65. const MEDIA_UPLOAD_URL = '/media/upload?';
  66. const MEDIA_GET_URL = '/media/get?';
  67. const AUTHSUCC_URL = '/user/authsucc?';
  68. const MASS_SEND_URL = '/message/send?';
  69. const MENU_CREATE_URL = '/menu/create?';
  70. const MENU_GET_URL = '/menu/get?';
  71. const MENU_DELETE_URL = '/menu/delete?';
  72. const TOKEN_GET_URL = '/gettoken?';
  73. const CALLBACKSERVER_GET_URL = '/getcallbackip?';
  74. const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
  75. const OAUTH_AUTHORIZE_URL = '/authorize?';
  76. private $token;
  77. private $encodingAesKey;
  78. private $appid; //也就是企业号的CorpID
  79. private $appsecret;
  80. private $access_token;
  81. private $agentid; //应用id AgentID
  82. private $postxml;
  83. private $agentidxml; //接收的应用id AgentID
  84. private $_msg;
  85. private $_receive;
  86. private $_sendmsg; //主动发送消息的内容
  87. private $_text_filter = true;
  88. public $debug = false;
  89. public $errCode = 40001;
  90. public $errMsg = "no access";
  91. private $_logcallback;
  92. public function __construct($options)
  93. {
  94. $this->token = isset($options['token'])?$options['token']:'';
  95. $this->encodingAesKey = isset($options['encodingaeskey'])?$options['encodingaeskey']:'';
  96. $this->appid = isset($options['appid'])?$options['appid']:'';
  97. $this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
  98. $this->agentid = isset($options['agentid'])?$options['agentid']:'';
  99. $this->debug = isset($options['debug'])?$options['debug']:false;
  100. $this->_logcallback = isset($options['logcallback'])?$options['logcallback']:false;
  101. }
  102. private function log($log){
  103. if ($this->debug ) {
  104. if (function_exists($this->_logcallback)) {
  105. if (is_array($log)) $log = print_r($log,true);
  106. return call_user_func($this->_logcallback,$log);
  107. }elseif (class_exists('Log')) {
  108. Log::write('qywechat:'.$log, Log::DEBUG);
  109. }
  110. }
  111. return false;
  112. }
  113. /**
  114. * 数据XML编码
  115. * @param mixed $data 数据
  116. * @return string
  117. */
  118. public static function data_to_xml($data) {
  119. $xml = '';
  120. foreach ($data as $key => $val) {
  121. is_numeric($key) && $key = "item id=\"$key\"";
  122. $xml .= "<$key>";
  123. $xml .= ( is_array($val) || is_object($val)) ? self::data_to_xml($val) : self::xmlSafeStr($val);
  124. list($key, ) = explode(' ', $key);
  125. $xml .= "</$key>";
  126. }
  127. return $xml;
  128. }
  129. public static function xmlSafeStr($str)
  130. {
  131. return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
  132. }
  133. /**
  134. * XML编码
  135. * @param mixed $data 数据
  136. * @param string $root 根节点名
  137. * @param string $item 数字索引的子节点名
  138. * @param string $attr 根节点属性
  139. * @param string $id 数字索引子节点key转换的属性名
  140. * @param string $encoding 数据编码
  141. * @return string
  142. */
  143. public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
  144. if(is_array($attr)){
  145. $_attr = array();
  146. foreach ($attr as $key => $value) {
  147. $_attr[] = "{$key}=\"{$value}\"";
  148. }
  149. $attr = implode(' ', $_attr);
  150. }
  151. $attr = trim($attr);
  152. $attr = empty($attr) ? '' : " {$attr}";
  153. $xml = "<{$root}{$attr}>";
  154. $xml .= self::data_to_xml($data, $item, $id);
  155. $xml .= "</{$root}>";
  156. return $xml;
  157. }
  158. /**
  159. * 微信api不支持中文转义的json结构
  160. * @param array $arr
  161. */
  162. static function json_encode($arr) {
  163. $parts = array ();
  164. $is_list = false;
  165. //Find out if the given array is a numerical array
  166. $keys = array_keys ( $arr );
  167. $max_length = count ( $arr ) - 1;
  168. if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
  169. $is_list = true;
  170. for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
  171. if ($i != $keys [$i]) { //A key fails at position check.
  172. $is_list = false; //It is an associative array.
  173. break;
  174. }
  175. }
  176. }
  177. foreach ( $arr as $key => $value ) {
  178. if (is_array ( $value )) { //Custom handling for arrays
  179. if ($is_list)
  180. $parts [] = self::json_encode ( $value ); /* :RECURSION: */
  181. else
  182. $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
  183. } else {
  184. $str = '';
  185. if (! $is_list)
  186. $str = '"' . $key . '":';
  187. //Custom handling for multiple data types
  188. if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)
  189. $str .= $value; //Numbers
  190. elseif ($value === false)
  191. $str .= 'false'; //The booleans
  192. elseif ($value === true)
  193. $str .= 'true';
  194. else
  195. $str .= '"' . addslashes ( $value ) . '"'; //All other things
  196. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  197. $parts [] = $str;
  198. }
  199. }
  200. $json = implode ( ',', $parts );
  201. if ($is_list)
  202. return '[' . $json . ']'; //Return numerical JSON
  203. return '{' . $json . '}'; //Return associative JSON
  204. }
  205. /**
  206. * 过滤文字回复\r\n换行符
  207. * @param string $text
  208. * @return string|mixed
  209. */
  210. private function _auto_text_filter($text) {
  211. if (!$this->_text_filter) return $text;
  212. return str_replace("\r\n", "\n", $text);
  213. }
  214. /**
  215. * GET 请求
  216. * @param string $url
  217. */
  218. private function http_get($url){
  219. $oCurl = curl_init();
  220. if(stripos($url,"https://")!==FALSE){
  221. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  222. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  223. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  224. }
  225. curl_setopt($oCurl, CURLOPT_URL, $url);
  226. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  227. $sContent = curl_exec($oCurl);
  228. $aStatus = curl_getinfo($oCurl);
  229. curl_close($oCurl);
  230. if(intval($aStatus["http_code"])==200){
  231. return $sContent;
  232. }else{
  233. return false;
  234. }
  235. }
  236. /**
  237. * POST 请求
  238. * @param string $url
  239. * @param array $param
  240. * @param boolean $post_file 是否文件上传
  241. * @return string content
  242. */
  243. private function http_post($url,$param,$post_file=false){
  244. $oCurl = curl_init();
  245. if(stripos($url,"https://")!==FALSE){
  246. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  247. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
  248. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  249. }
  250. if (is_string($param) || $post_file) {
  251. $strPOST = $param;
  252. } else {
  253. $aPOST = array();
  254. foreach($param as $key=>$val){
  255. $aPOST[] = $key."=".urlencode($val);
  256. }
  257. $strPOST = join("&", $aPOST);
  258. }
  259. curl_setopt($oCurl, CURLOPT_URL, $url);
  260. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  261. curl_setopt($oCurl, CURLOPT_POST,true);
  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. * 通用auth验证方法
  789. * @param string $appid
  790. * @param string $appsecret
  791. * @param string $token 手动指定access_token,非必要情况不建议用
  792. */
  793. public function checkAuth($appid='',$appsecret='',$token=''){
  794. if (!$appid || !$appsecret) {
  795. $appid = $this->appid;
  796. $appsecret = $this->appsecret;
  797. }
  798. $authname = 'qywechat_access_token'.$appid;
  799. if ($token) { //手动指定token,优先使用
  800. $this->access_token=$token;
  801. return $this->access_token;
  802. }
  803. if ($rs = S($authname)) {
  804. $this->access_token = $rs;
  805. return $rs;
  806. }
  807. $result = $this->http_get(self::API_URL_PREFIX.self::TOKEN_GET_URL.'corpid='.$appid.'&corpsecret='.$appsecret);
  808. if ($result)
  809. {
  810. $json = json_decode($result,true);
  811. if (!$json || isset($json['errcode'])) {
  812. $this->errCode = $json['errcode'];
  813. $this->errMsg = $json['errmsg'];
  814. return false;
  815. }
  816. $this->access_token = $json['access_token'];
  817. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  818. S($authname,$this->access_token,$expire);
  819. return $this->access_token;
  820. }
  821. return false;
  822. }
  823. /**
  824. * 删除验证数据
  825. * @param string $appid
  826. */
  827. public function resetAuth($appid=''){
  828. if (!$appid) $appid = $this->appid;
  829. $this->access_token = '';
  830. //TODO: remove cache
  831. return true;
  832. }
  833. /**
  834. * 创建菜单
  835. * @param array $data 菜单数组数据
  836. * example:
  837. * array (
  838. * 'button' => array (
  839. * 0 => array (
  840. * 'name' => '扫码',
  841. * 'sub_button' => array (
  842. * 0 => array (
  843. * 'type' => 'scancode_waitmsg',
  844. * 'name' => '扫码带提示',
  845. * 'key' => 'rselfmenu_0_0',
  846. * ),
  847. * 1 => array (
  848. * 'type' => 'scancode_push',
  849. * 'name' => '扫码推事件',
  850. * 'key' => 'rselfmenu_0_1',
  851. * ),
  852. * ),
  853. * ),
  854. * 1 => array (
  855. * 'name' => '发图',
  856. * 'sub_button' => array (
  857. * 0 => array (
  858. * 'type' => 'pic_sysphoto',
  859. * 'name' => '系统拍照发图',
  860. * 'key' => 'rselfmenu_1_0',
  861. * ),
  862. * 1 => array (
  863. * 'type' => 'pic_photo_or_album',
  864. * 'name' => '拍照或者相册发图',
  865. * 'key' => 'rselfmenu_1_1',
  866. * )
  867. * ),
  868. * ),
  869. * 2 => array (
  870. * 'type' => 'location_select',
  871. * 'name' => '发送位置',
  872. * 'key' => 'rselfmenu_2_0'
  873. * ),
  874. * ),
  875. * )
  876. * type可以选择为以下几种,会收到相应类型的事件推送。请注意,3到8的所有事件,仅支持微信iPhone5.4.1以上版本,
  877. * 和Android5.4以上版本的微信用户,旧版本微信用户点击后将没有回应,开发者也不能正常接收到事件推送。
  878. * 1、click:点击推事件
  879. * 2、view:跳转URL
  880. * 3、scancode_push:扫码推事件
  881. * 4、scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
  882. * 5、pic_sysphoto:弹出系统拍照发图
  883. * 6、pic_photo_or_album:弹出拍照或者相册发图
  884. * 7、pic_weixin:弹出微信相册发图器
  885. * 8、location_select:弹出地理位置选择器
  886. */
  887. public function createMenu($data,$agentid=''){
  888. if ($agentid=='') {
  889. $agentid=$this->agentid;
  890. }
  891. if (!$this->access_token && !$this->checkAuth()) return false;
  892. $result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token.'&agentid='.$agentid,self::json_encode($data));
  893. if ($result)
  894. {
  895. $json = json_decode($result,true);
  896. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  897. $this->errCode = $json['errcode'];
  898. $this->errMsg = $json['errmsg'];
  899. return false;
  900. }
  901. return true;
  902. }
  903. return false;
  904. }
  905. /**
  906. * 获取菜单
  907. * @return array('menu'=>array(....s))
  908. */
  909. public function getMenu($agentid=''){
  910. if ($agentid=='') {
  911. $agentid=$this->agentid;
  912. }
  913. if (!$this->access_token && !$this->checkAuth()) return false;
  914. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token.'&agentid='.$agentid);
  915. if ($result)
  916. {
  917. $json = json_decode($result,true);
  918. if (!$json || isset($json['errcode']) || $json['errcode']!=0) {
  919. $this->errCode = $json['errcode'];
  920. $this->errMsg = $json['errmsg'];
  921. return false;
  922. }
  923. return $json;
  924. }
  925. return false;
  926. }
  927. /**
  928. * 删除菜单
  929. * @return boolean
  930. */
  931. public function deleteMenu($agentid=''){
  932. if ($agentid=='') {
  933. $agentid=$this->agentid;
  934. }
  935. if (!$this->access_token && !$this->checkAuth()) return false;
  936. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token.'&agentid='.$agentid);
  937. if ($result)
  938. {
  939. $json = json_decode($result,true);
  940. if (!$json || !empty($json['errcode'])) {
  941. $this->errCode = $json['errcode'];
  942. $this->errMsg = $json['errmsg'];
  943. return false;
  944. }
  945. return true;
  946. }
  947. return false;
  948. }
  949. /**
  950. * 上传多媒体文件 (只有三天的有效期,过期自动被删除)
  951. * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
  952. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  953. * @param array $data {"media":'@Path\filename.jpg'}
  954. * @param type 媒体文件类型:图片(image)、语音(voice)、视频(video),普通文件(file)
  955. * @return boolean|array
  956. * {
  957. * "type": "image",
  958. * "media_id": "0000001",
  959. * "created_at": "1380000000"
  960. * }
  961. */
  962. public function uploadMedia($data, $type){
  963. if (!$this->access_token && !$this->checkAuth()) return false;
  964. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOAD.'access_token='.$this->access_token.'&type='.$type,$data,true);
  965. if ($result)
  966. {
  967. $json = json_decode($result,true);
  968. if (!$json || !empty($json['errcode'])) {
  969. $this->errCode = $json['errcode'];
  970. $this->errMsg = $json['errmsg'];
  971. return false;
  972. }
  973. return $json;
  974. }
  975. return false;
  976. }
  977. /**
  978. * 根据媒体文件ID获取媒体文件
  979. * @param string $media_id 媒体文件id
  980. * @return raw data
  981. */
  982. public function getMedia($media_id){
  983. if (!$this->access_token && !$this->checkAuth()) return false;
  984. $result = $this->http_get(self::API_URL_PREFIX.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
  985. if ($result)
  986. {
  987. $json = json_decode($result,true);
  988. if (isset($json['errcode'])) {
  989. $this->errCode = $json['errcode'];
  990. $this->errMsg = $json['errmsg'];
  991. return false;
  992. }
  993. return $result;
  994. }
  995. return false;
  996. }
  997. /**
  998. * 获取企业微信服务器IP地址列表
  999. * @return array('127.0.0.1','127.0.0.1')
  1000. */
  1001. public function getServerIp(){
  1002. if (!$this->access_token && !$this->checkAuth()) return false;
  1003. $result = $this->http_get(self::API_URL_PREFIX.self::CALLBACKSERVER_GET_URL.'access_token='.$this->access_token);
  1004. if ($result)
  1005. {
  1006. $json = json_decode($result,true);
  1007. if (!$json || isset($json['errcode'])) {
  1008. $this->errCode = $json['errcode'];
  1009. $this->errMsg = $json['errmsg'];
  1010. return false;
  1011. }
  1012. return $json['ip_list'];
  1013. }
  1014. return false;
  1015. }
  1016. /**
  1017. * 创建部门
  1018. * @param array $data 结构体为:
  1019. * array (
  1020. * "name" => "邮箱产品组", //部门名称
  1021. * "parentid" => "1" //父部门id
  1022. * "order" => "1", //(非必须)在父部门中的次序。从1开始,数字越大排序越靠后
  1023. * )
  1024. * @return boolean|array
  1025. * 成功返回结果
  1026. * {
  1027. * "errcode": 0, //返回码
  1028. * "errmsg": "created", //对返回码的文本描述内容
  1029. * "id": 2 //创建的部门id。
  1030. * }
  1031. */
  1032. public function createDepartment($data){
  1033. if (!$this->access_token && !$this->checkAuth()) return false;
  1034. $result = $this->http_post(self::API_URL_PREFIX.self::DEPARTMENT_CREATE_URL.'access_token='.$this->access_token,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 $json;
  1044. }
  1045. return false;
  1046. }
  1047. /**
  1048. * 更新部门
  1049. * @param array $data 结构体为:
  1050. * array(
  1051. * "id" => "1" //(必须)部门id
  1052. * "name" => "邮箱产品组", //(非必须)部门名称
  1053. * "parentid" => "1", //(非必须)父亲部门id。根部门id为1
  1054. * "order" => "1", //(非必须)在父部门中的次序。从1开始,数字越大排序越靠后
  1055. * )
  1056. * @return boolean|array 成功返回结果
  1057. * {
  1058. * "errcode": 0, //返回码
  1059. * "errmsg": "updated" //对返回码的文本描述内容
  1060. * }
  1061. */
  1062. public function updateDepartment($data){
  1063. if (!$this->access_token && !$this->checkAuth()) return false;
  1064. $result = $this->http_post(self::API_URL_PREFIX.self::DEPARTMENT_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1065. if ($result)
  1066. {
  1067. $json = json_decode($result,true);
  1068. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1069. $this->errCode = $json['errcode'];
  1070. $this->errMsg = $json['errmsg'];
  1071. return false;
  1072. }
  1073. return $json;
  1074. }
  1075. return false;
  1076. }
  1077. /**
  1078. * 删除部门
  1079. * @param $id
  1080. * @return boolean|array 成功返回结果
  1081. * {
  1082. * "errcode": 0, //返回码
  1083. * "errmsg": "deleted" //对返回码的文本描述内容
  1084. * }
  1085. */
  1086. public function deleteDepartment($id){
  1087. if (!$this->access_token && !$this->checkAuth()) return false;
  1088. $result = $this->http_get(self::API_URL_PREFIX.self::DEPARTMENT_DELETE_URL.'access_token='.$this->access_token.'&id='.$id);
  1089. if ($result)
  1090. {
  1091. $json = json_decode($result,true);
  1092. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1093. $this->errCode = $json['errcode'];
  1094. $this->errMsg = $json['errmsg'];
  1095. return false;
  1096. }
  1097. return $json;
  1098. }
  1099. return false;
  1100. }
  1101. /**
  1102. * 移动部门
  1103. * @param $data
  1104. * array(
  1105. * "department_id" => "5", //所要移动的部门
  1106. * "to_parentid" => "2", //想移动到的父部门节点,根部门为1
  1107. * "to_position" => "1" //(非必须)想移动到的父部门下的位置,1表示最上方,往后位置为2,3,4,以此类推,默认为1
  1108. * )
  1109. * @return boolean|array 成功返回结果
  1110. * {
  1111. * "errcode": 0, //返回码
  1112. * "errmsg": "ok" //对返回码的文本描述内容
  1113. * }
  1114. */
  1115. public function moveDepartment($data){
  1116. if (!$this->access_token && !$this->checkAuth()) return false;
  1117. $result = $this->http_get(self::API_URL_PREFIX.self::DEPARTMENT_MOVE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1118. if ($result)
  1119. {
  1120. $json = json_decode($result,true);
  1121. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1122. $this->errCode = $json['errcode'];
  1123. $this->errMsg = $json['errmsg'];
  1124. return false;
  1125. }
  1126. return $json;
  1127. }
  1128. return false;
  1129. }
  1130. /**
  1131. * 获取部门列表
  1132. * @return boolean|array 成功返回结果
  1133. * {
  1134. * "errcode": 0,
  1135. * "errmsg": "ok",
  1136. * "department": [ //部门列表数据。以部门的order字段从小到大排列
  1137. * {
  1138. * "id": 1,
  1139. * "name": "广州研发中心",
  1140. * "parentid": 0
  1141. * },
  1142. * {
  1143. * "id": 2
  1144. * "name": "邮箱产品部",
  1145. * "parentid": 1
  1146. * }
  1147. * ]
  1148. * }
  1149. */
  1150. public function getDepartment(){
  1151. if (!$this->access_token && !$this->checkAuth()) return false;
  1152. $result = $this->http_get(self::API_URL_PREFIX.self::DEPARTMENT_LIST_URL.'access_token='.$this->access_token);
  1153. if ($result)
  1154. {
  1155. $json = json_decode($result,true);
  1156. if (!$json || !empty($json['errcode'])) {
  1157. $this->errCode = $json['errcode'];
  1158. $this->errMsg = $json['errmsg'];
  1159. return false;
  1160. }
  1161. return $json;
  1162. }
  1163. return false;
  1164. }
  1165. /**
  1166. * 创建成员
  1167. * @param array $data 结构体为:
  1168. * array(
  1169. * "userid" => "zhangsan",
  1170. * "name" => "张三",
  1171. * "department" => [1, 2],
  1172. * "position" => "产品经理",
  1173. * "mobile" => "15913215421",
  1174. * "gender" => 1, //性别。gender=0表示男,=1表示女
  1175. * "tel" => "62394",
  1176. * "email" => "zhangsan@gzdev.com",
  1177. * "weixinid" => "zhangsan4dev"
  1178. * )
  1179. * @return boolean|array
  1180. * 成功返回结果
  1181. * {
  1182. * "errcode": 0, //返回码
  1183. * "errmsg": "created", //对返回码的文本描述内容
  1184. * }
  1185. */
  1186. public function createUser($data){
  1187. if (!$this->access_token && !$this->checkAuth()) return false;
  1188. $result = $this->http_post(self::API_URL_PREFIX.self::USER_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1189. if ($result)
  1190. {
  1191. $json = json_decode($result,true);
  1192. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1193. $this->errCode = $json['errcode'];
  1194. $this->errMsg = $json['errmsg'];
  1195. return false;
  1196. }
  1197. return $json;
  1198. }
  1199. return false;
  1200. }
  1201. /**
  1202. * 更新成员
  1203. * @param array $data 结构体为:
  1204. * array(
  1205. * "userid" => "zhangsan",
  1206. * "name" => "张三",
  1207. * "department" => [1, 2],
  1208. * "position" => "产品经理",
  1209. * "mobile" => "15913215421",
  1210. * "gender" => 1, //性别。gender=0表示男,=1表示女
  1211. * "tel" => "62394",
  1212. * "email" => "zhangsan@gzdev.com",
  1213. * "weixinid" => "zhangsan4dev"
  1214. * )
  1215. * @return boolean|array 成功返回结果
  1216. * {
  1217. * "errcode": 0, //返回码
  1218. * "errmsg": "updated" //对返回码的文本描述内容
  1219. * }
  1220. */
  1221. public function updateUser($data){
  1222. if (!$this->access_token && !$this->checkAuth()) return false;
  1223. $result = $this->http_post(self::API_URL_PREFIX.self::USER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1224. if ($result)
  1225. {
  1226. $json = json_decode($result,true);
  1227. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1228. $this->errCode = $json['errcode'];
  1229. $this->errMsg = $json['errmsg'];
  1230. return false;
  1231. }
  1232. return $json;
  1233. }
  1234. return false;
  1235. }
  1236. /**
  1237. * 删除成员
  1238. * @param $userid 员工UserID。对应管理端的帐号
  1239. * @return boolean|array 成功返回结果
  1240. * {
  1241. * "errcode": 0, //返回码
  1242. * "errmsg": "deleted" //对返回码的文本描述内容
  1243. * }
  1244. */
  1245. public function deleteUser($userid){
  1246. if (!$this->access_token && !$this->checkAuth()) return false;
  1247. $result = $this->http_get(self::API_URL_PREFIX.self::USER_DELETE_URL.'access_token='.$this->access_token.'&userid='.$userid);
  1248. if ($result)
  1249. {
  1250. $json = json_decode($result,true);
  1251. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1252. $this->errCode = $json['errcode'];
  1253. $this->errMsg = $json['errmsg'];
  1254. return false;
  1255. }
  1256. return $json;
  1257. }
  1258. return false;
  1259. }
  1260. /**
  1261. * 批量删除成员
  1262. * @param array $userid 员工UserID数组。对应管理端的帐号
  1263. * {
  1264. * 'userid1',
  1265. * 'userid2',
  1266. * 'userid3',
  1267. * }
  1268. * @return boolean|array 成功返回结果
  1269. * {
  1270. * "errcode": 0, //返回码
  1271. * "errmsg": "deleted" //对返回码的文本描述内容
  1272. * }
  1273. */
  1274. public function deleteUsers($userids){
  1275. if (!$userids) return false;
  1276. $data = array('useridlist'=>$userids);
  1277. if (!$this->access_token && !$this->checkAuth()) return false;
  1278. $result = $this->http_get(self::API_URL_PREFIX.self::USER_BATCHDELETE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1279. if ($result)
  1280. {
  1281. $json = json_decode($result,true);
  1282. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1283. $this->errCode = $json['errcode'];
  1284. $this->errMsg = $json['errmsg'];
  1285. return false;
  1286. }
  1287. return $json;
  1288. }
  1289. return false;
  1290. }
  1291. /**
  1292. * 获取成员信息
  1293. * @param $userid 员工UserID。对应管理端的帐号
  1294. * @return boolean|array 成功返回结果
  1295. * {
  1296. * "errcode": 0,
  1297. * "errmsg": "ok",
  1298. * "userid": "zhangsan",
  1299. * "name": "李四",
  1300. * "department": [1, 2],
  1301. * "position": "后台工程师",
  1302. * "mobile": "15913215421",
  1303. * "gender": 1, //性别。gender=0表示男,=1表示女
  1304. * "tel": "62394",
  1305. * "email": "zhangsan@gzdev.com",
  1306. * "weixinid": "lisifordev", //微信号
  1307. * "avatar": "http://wx.qlogo.cn/mmopen/ajNVdqHZLLA3W..../0", //头像url。注:如果要获取小图将url最后的"/0"改成"/64"即可
  1308. * "status": 1 //关注状态: 1=已关注,2=已冻结,4=未关注
  1309. * "extattr": {"attrs":[{"name":"爱好","value":"旅游"},{"name":"卡号","value":"1234567234"}]}
  1310. * }
  1311. */
  1312. public function getUserInfo($userid){
  1313. if (!$this->access_token && !$this->checkAuth()) return false;
  1314. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&userid='.$userid);
  1315. if ($result)
  1316. {
  1317. $json = json_decode($result,true);
  1318. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1319. $this->errCode = $json['errcode'];
  1320. $this->errMsg = $json['errmsg'];
  1321. return false;
  1322. }
  1323. return $json;
  1324. }
  1325. return false;
  1326. }
  1327. /**
  1328. * 获取部门成员
  1329. * @param $department_id 部门id
  1330. * @param $fetch_child 1/0:是否递归获取子部门下面的成员
  1331. * @param $status 0获取全部员工,1获取已关注成员列表,2获取禁用成员列表,4获取未关注成员列表。status可叠加
  1332. * @return boolean|array 成功返回结果
  1333. * {
  1334. * "errcode": 0,
  1335. * "errmsg": "ok",
  1336. * "userlist": [
  1337. * {
  1338. * "userid": "zhangsan",
  1339. * "name": "李四"
  1340. * }
  1341. * ]
  1342. * }
  1343. */
  1344. public function getUserList($department_id,$fetch_child=0,$status=0){
  1345. if (!$this->access_token && !$this->checkAuth()) return false;
  1346. $result = $this->http_get(self::API_URL_PREFIX.self::USER_LIST_URL.'access_token='.$this->access_token
  1347. .'&department_id='.$department_id.'&fetch_child='.$fetch_child.'&status='.$status);
  1348. if ($result)
  1349. {
  1350. $json = json_decode($result,true);
  1351. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1352. $this->errCode = $json['errcode'];
  1353. $this->errMsg = $json['errmsg'];
  1354. return false;
  1355. }
  1356. return $json;
  1357. }
  1358. return false;
  1359. }
  1360. /**
  1361. * 获取部门成员详情
  1362. * @param $department_id 部门id
  1363. * @param $fetch_child 1/0:是否递归获取子部门下面的成员
  1364. * @param $status 0获取全部员工,1获取已关注成员列表,2获取禁用成员列表,4获取未关注成员列表。status可叠加
  1365. * @return boolean|array 成功返回结果
  1366. * {
  1367. * "errcode": 0,
  1368. * "errmsg": "ok",
  1369. * "userlist": [
  1370. * {
  1371. * "userid": "zhangsan",
  1372. * "name": "李四",
  1373. * "department": [1, 2],
  1374. * "position": "后台工程师",
  1375. * "mobile": "15913215421",
  1376. * "gender": 1, //性别。gender=0表示男,=1表示女
  1377. * "tel": "62394",
  1378. * "email": "zhangsan@gzdev.com",
  1379. * "weixinid": "lisifordev", //微信号
  1380. * "avatar": "http://wx.qlogo.cn/mmopen/ajNVdqHZLLA3W..../0", //头像url。注:如果要获取小图将url最后的"/0"改成"/64"即可
  1381. * "status": 1 //关注状态: 1=已关注,2=已冻结,4=未关注
  1382. * "extattr": {"attrs":[{"name":"爱好","value":"旅游"},{"name":"卡号","value":"1234567234"}]}
  1383. * }
  1384. * ]
  1385. * }
  1386. */
  1387. public function getUserListInfo($department_id,$fetch_child=0,$status=0){
  1388. if (!$this->access_token && !$this->checkAuth()) return false;
  1389. $result = $this->http_get(self::API_URL_PREFIX.self::USER_LIST_INFO_URL.'access_token='.$this->access_token
  1390. .'&department_id='.$department_id.'&fetch_child='.$fetch_child.'&status='.$status);
  1391. if ($result)
  1392. {
  1393. $json = json_decode($result,true);
  1394. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1395. $this->errCode = $json['errcode'];
  1396. $this->errMsg = $json['errmsg'];
  1397. return false;
  1398. }
  1399. return $json;
  1400. }
  1401. return false;
  1402. }
  1403. /**
  1404. * 根据code获取成员信息
  1405. * 通过Oauth2.0或者设置了二次验证时获取的code,用于换取成员的UserId和DeviceId
  1406. *
  1407. * @param $code Oauth2.0或者二次验证时返回的code值
  1408. * @param $agentid 跳转链接时所在的企业应用ID,未填则默认为当前配置的应用id
  1409. * @return boolean|array 成功返回数组
  1410. * array(
  1411. * 'UserId' => 'USERID', //员工UserID
  1412. * 'DeviceId' => 'DEVICEID' //手机设备号(由微信在安装时随机生成)
  1413. * )
  1414. */
  1415. public function getUserId($code,$agentid=0){
  1416. if (!$agentid) $agentid=$this->agentid;
  1417. if (!$this->access_token && !$this->checkAuth()) return false;
  1418. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GETINFO_URL.'access_token='.$this->access_token.'&code='.$code.'&agentid'.$agentid);
  1419. if ($result)
  1420. {
  1421. $json = json_decode($result,true);
  1422. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1423. $this->errCode = $json['errcode'];
  1424. $this->errMsg = $json['errmsg'];
  1425. return false;
  1426. }
  1427. return $json;
  1428. }
  1429. return false;
  1430. }
  1431. /**
  1432. * 创建标签
  1433. * @param array $data 结构体为:
  1434. * array(
  1435. * "tagname" => "UI"
  1436. * )
  1437. * @return boolean|array
  1438. * 成功返回结果
  1439. * {
  1440. * "errcode": 0, //返回码
  1441. * "errmsg": "created", //对返回码的文本描述内容
  1442. * "tagid": "1"
  1443. * }
  1444. */
  1445. public function createTag($data){
  1446. if (!$this->access_token && !$this->checkAuth()) return false;
  1447. $result = $this->http_post(self::API_URL_PREFIX.self::TAG_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1448. if ($result)
  1449. {
  1450. $json = json_decode($result,true);
  1451. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1452. $this->errCode = $json['errcode'];
  1453. $this->errMsg = $json['errmsg'];
  1454. return false;
  1455. }
  1456. return $json;
  1457. }
  1458. return false;
  1459. }
  1460. /**
  1461. * 更新标签
  1462. * @param array $data 结构体为:
  1463. * array(
  1464. * "tagid" => "1",
  1465. * "tagname" => "UI design"
  1466. * )
  1467. * @return boolean|array 成功返回结果
  1468. * {
  1469. * "errcode": 0, //返回码
  1470. * "errmsg": "updated" //对返回码的文本描述内容
  1471. * }
  1472. */
  1473. public function updateTag($data){
  1474. if (!$this->access_token && !$this->checkAuth()) return false;
  1475. $result = $this->http_post(self::API_URL_PREFIX.self::TAG_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1476. if ($result)
  1477. {
  1478. $json = json_decode($result,true);
  1479. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1480. $this->errCode = $json['errcode'];
  1481. $this->errMsg = $json['errmsg'];
  1482. return false;
  1483. }
  1484. return $json;
  1485. }
  1486. return false;
  1487. }
  1488. /**
  1489. * 删除标签
  1490. * @param $tagid 标签TagID
  1491. * @return boolean|array 成功返回结果
  1492. * {
  1493. * "errcode": 0, //返回码
  1494. * "errmsg": "deleted" //对返回码的文本描述内容
  1495. * }
  1496. */
  1497. public function deleteTag($tagid){
  1498. if (!$this->access_token && !$this->checkAuth()) return false;
  1499. $result = $this->http_get(self::API_URL_PREFIX.self::TAG_DELETE_URL.'access_token='.$this->access_token.'&tagid='.$tagid);
  1500. if ($result)
  1501. {
  1502. $json = json_decode($result,true);
  1503. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1504. $this->errCode = $json['errcode'];
  1505. $this->errMsg = $json['errmsg'];
  1506. return false;
  1507. }
  1508. return $json;
  1509. }
  1510. return false;
  1511. }
  1512. /**
  1513. * 获取标签成员
  1514. * @param $tagid 标签TagID
  1515. * @return boolean|array 成功返回结果
  1516. * {
  1517. * "errcode": 0,
  1518. * "errmsg": "ok",
  1519. * "userlist": [
  1520. * {
  1521. * "userid": "zhangsan",
  1522. * "name": "李四"
  1523. * }
  1524. * ]
  1525. * }
  1526. */
  1527. public function getTag($tagid){
  1528. if (!$this->access_token && !$this->checkAuth()) return false;
  1529. $result = $this->http_get(self::API_URL_PREFIX.self::TAG_GET_URL.'access_token='.$this->access_token.'&tagid='.$tagid);
  1530. if ($result)
  1531. {
  1532. $json = json_decode($result,true);
  1533. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1534. $this->errCode = $json['errcode'];
  1535. $this->errMsg = $json['errmsg'];
  1536. return false;
  1537. }
  1538. return $json;
  1539. }
  1540. return false;
  1541. }
  1542. /**
  1543. * 增加标签成员
  1544. * @param array $data 结构体为:
  1545. * array (
  1546. * "tagid" => "1",
  1547. * "userlist" => array( //企业员工ID列表
  1548. * "user1",
  1549. * "user2"
  1550. * )
  1551. * )
  1552. * @return boolean|array
  1553. * 成功返回结果
  1554. * {
  1555. * "errcode": 0, //返回码
  1556. * "errmsg": "ok", //对返回码的文本描述内容
  1557. * "invalidlist":"usr1|usr2|usr" //若部分userid非法,则会有此段。不在权限内的员工ID列表,以“|”分隔
  1558. * }
  1559. */
  1560. public function addTagUser($data){
  1561. if (!$this->access_token && !$this->checkAuth()) return false;
  1562. $result = $this->http_post(self::API_URL_PREFIX.self::TAG_ADDUSER_URL.'access_token='.$this->access_token,self::json_encode($data));
  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. * @param array $data 结构体为:
  1578. * array (
  1579. * "tagid" => "1",
  1580. * "userlist" => array( //企业员工ID列表
  1581. * "user1",
  1582. * "user2"
  1583. * )
  1584. * )
  1585. * @return boolean|array
  1586. * 成功返回结果
  1587. * {
  1588. * "errcode": 0, //返回码
  1589. * "errmsg": "deleted", //对返回码的文本描述内容
  1590. * "invalidlist":"usr1|usr2|usr" //若部分userid非法,则会有此段。不在权限内的员工ID列表,以“|”分隔
  1591. * }
  1592. */
  1593. public function delTagUser($data){
  1594. if (!$this->access_token && !$this->checkAuth()) return false;
  1595. $result = $this->http_post(self::API_URL_PREFIX.self::TAG_DELUSER_URL.'access_token='.$this->access_token,self::json_encode($data));
  1596. if ($result)
  1597. {
  1598. $json = json_decode($result,true);
  1599. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1600. $this->errCode = $json['errcode'];
  1601. $this->errMsg = $json['errmsg'];
  1602. return false;
  1603. }
  1604. return $json;
  1605. }
  1606. return false;
  1607. }
  1608. /**
  1609. * 获取标签列表
  1610. * @return boolean|array 成功返回数组结果,这里附上json样例
  1611. * {
  1612. * "errcode": 0,
  1613. * "errmsg": "ok",
  1614. * "taglist":[
  1615. * {"tagid":1,"tagname":"a"},
  1616. * {"tagid":2,"tagname":"b"}
  1617. * ]
  1618. * }
  1619. */
  1620. public function getTagList(){
  1621. if (!$this->access_token && !$this->checkAuth()) return false;
  1622. $result = $this->http_get(self::API_URL_PREFIX.self::TAG_LIST_URL.'access_token='.$this->access_token);
  1623. if ($result)
  1624. {
  1625. $json = json_decode($result,true);
  1626. if (!$json || !empty($json['errcode'])) {
  1627. $this->errCode = $json['errcode'];
  1628. $this->errMsg = $json['errmsg'];
  1629. return false;
  1630. }
  1631. return $json;
  1632. }
  1633. return false;
  1634. }
  1635. /**
  1636. * 主动发送信息接口
  1637. * @param array $data 结构体为:
  1638. * array(
  1639. * "touser" => "UserID1|UserID2|UserID3",
  1640. * "toparty" => "PartyID1|PartyID2 ",
  1641. * "totag" => "TagID1|TagID2 ",
  1642. * "safe":"0" //是否为保密消息,对于news无效
  1643. * "agentid" => "001", //应用id
  1644. * "msgtype" => "text", //根据信息类型,选择下面对应的信息结构体
  1645. *
  1646. * "text" => array(
  1647. * "content" => "Holiday Request For Pony(http://xxxxx)"
  1648. * ),
  1649. *
  1650. * "image" => array(
  1651. * "media_id" => "MEDIA_ID"
  1652. * ),
  1653. *
  1654. * "voice" => array(
  1655. * "media_id" => "MEDIA_ID"
  1656. * ),
  1657. *
  1658. * " video" => array(
  1659. * "media_id" => "MEDIA_ID",
  1660. * "title" => "Title",
  1661. * "description" => "Description"
  1662. * ),
  1663. *
  1664. * "file" => array(
  1665. * "media_id" => "MEDIA_ID"
  1666. * ),
  1667. *
  1668. * "news" => array( //不支持保密
  1669. * "articles" => array( //articles 图文消息,一个图文消息支持1到10个图文
  1670. * array(
  1671. * "title" => "Title", //标题
  1672. * "description" => "Description", //描述
  1673. * "url" => "URL", //点击后跳转的链接。可根据url里面带的code参数校验员工的真实身份。
  1674. * "picurl" => "PIC_URL", //图文消息的图片链接,支持JPG、PNG格式,较好的效果为大图640*320,
  1675. * //小图80*80。如不填,在客户端不显示图片
  1676. * ),
  1677. * )
  1678. * ),
  1679. *
  1680. * "mpnews" => array(
  1681. * "articles" => array( //articles 图文消息,一个图文消息支持1到10个图文
  1682. * array(
  1683. * "title" => "Title", //图文消息的标题
  1684. * "thumb_media_id" => "id", //图文消息缩略图的media_id
  1685. * "author" => "Author", //图文消息的作者(可空)
  1686. * "content_source_url" => "URL", //图文消息点击“阅读原文”之后的页面链接(可空)
  1687. * "content" => "Content" //图文消息的内容,支持html标签
  1688. * "digest" => "Digest description", //图文消息的描述
  1689. * "show_cover_pic" => "0" //是否显示封面,1为显示,0为不显示(可空)
  1690. * ),
  1691. * )
  1692. * )
  1693. * )
  1694. * 请查看官方开发文档中的 发送消息 -> 消息类型及数据格式
  1695. *
  1696. * @return boolean|array
  1697. * 如果对应用或收件人、部门、标签任何一个无权限,则本次发送失败;
  1698. * 如果收件人、部门或标签不存在,发送仍然执行,但返回无效的部分。
  1699. * {
  1700. * "errcode": 0,
  1701. * "errmsg": "ok",
  1702. * "invaliduser": "UserID1",
  1703. * "invalidparty":"PartyID1",
  1704. * "invalidtag":"TagID1"
  1705. * }
  1706. */
  1707. public function sendMessage($data){
  1708. if (!$this->access_token && !$this->checkAuth()) return false;
  1709. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1710. if ($result)
  1711. {
  1712. $json = json_decode($result,true);
  1713. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1714. $this->errCode = $json['errcode'];
  1715. $this->errMsg = $json['errmsg'];
  1716. return false;
  1717. }
  1718. return $json;
  1719. }
  1720. return false;
  1721. }
  1722. /**
  1723. * 二次验证
  1724. * 企业在开启二次验证时,必须填写企业二次验证页面的url。
  1725. * 当员工绑定通讯录中的帐号后,会收到一条图文消息,
  1726. * 引导员工到企业的验证页面验证身份,企业在员工验证成功后,
  1727. * 调用如下接口即可让员工关注成功。
  1728. *
  1729. * @param $userid
  1730. * @return boolean|array 成功返回结果
  1731. * {
  1732. * "errcode": 0, //返回码
  1733. * "errmsg": "ok" //对返回码的文本描述内容
  1734. * }
  1735. */
  1736. public function authSucc($userid){
  1737. if (!$this->access_token && !$this->checkAuth()) return false;
  1738. $result = $this->http_get(self::API_URL_PREFIX.self::AUTHSUCC_URL.'access_token='.$this->access_token.'&userid='.$userid);
  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. * oauth 授权跳转接口
  1753. * @param string $callback 回调URI
  1754. * @param string $state 重定向后会带上state参数,企业可以填写a-zA-Z0-9的参数值
  1755. * @return string
  1756. */
  1757. public function getOauthRedirect($callback,$state='STATE',$scope='snsapi_base'){
  1758. return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  1759. }
  1760. }
  1761. /**
  1762. * PKCS7Encoder class
  1763. *
  1764. * 提供基于PKCS7算法的加解密接口.
  1765. */
  1766. class PKCS7Encoder
  1767. {
  1768. public static $block_size = 32;
  1769. /**
  1770. * 对需要加密的明文进行填充补位
  1771. * @param $text 需要进行填充补位操作的明文
  1772. * @return 补齐明文字符串
  1773. */
  1774. function encode($text)
  1775. {
  1776. $block_size = PKCS7Encoder::$block_size;
  1777. $text_length = strlen($text);
  1778. //计算需要填充的位数
  1779. $amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
  1780. if ($amount_to_pad == 0) {
  1781. $amount_to_pad = PKCS7Encoder::block_size;
  1782. }
  1783. //获得补位所用的字符
  1784. $pad_chr = chr($amount_to_pad);
  1785. $tmp = "";
  1786. for ($index = 0; $index < $amount_to_pad; $index++) {
  1787. $tmp .= $pad_chr;
  1788. }
  1789. return $text . $tmp;
  1790. }
  1791. /**
  1792. * 对解密后的明文进行补位删除
  1793. * @param decrypted 解密后的明文
  1794. * @return 删除填充补位后的明文
  1795. */
  1796. function decode($text)
  1797. {
  1798. $pad = ord(substr($text, -1));
  1799. if ($pad < 1 || $pad > PKCS7Encoder::$block_size) {
  1800. $pad = 0;
  1801. }
  1802. return substr($text, 0, (strlen($text) - $pad));
  1803. }
  1804. }
  1805. /**
  1806. * Prpcrypt class
  1807. *
  1808. * 提供接收和推送给公众平台消息的加解密接口.
  1809. */
  1810. class Prpcrypt
  1811. {
  1812. public $key;
  1813. function Prpcrypt($k)
  1814. {
  1815. $this->key = base64_decode($k . "=");
  1816. }
  1817. /**
  1818. * 对明文进行加密
  1819. * @param string $text 需要加密的明文
  1820. * @return string 加密后的密文
  1821. */
  1822. public function encrypt($text, $appid)
  1823. {
  1824. try {
  1825. //获得16位随机字符串,填充到明文之前
  1826. $random = $this->getRandomStr();//"aaaabbbbccccdddd";
  1827. $text = $random . pack("N", strlen($text)) . $text . $appid;
  1828. // 网络字节序
  1829. $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  1830. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  1831. $iv = substr($this->key, 0, 16);
  1832. //使用自定义的填充方式对明文进行补位填充
  1833. $pkc_encoder = new PKCS7Encoder;
  1834. $text = $pkc_encoder->encode($text);
  1835. mcrypt_generic_init($module, $this->key, $iv);
  1836. //加密
  1837. $encrypted = mcrypt_generic($module, $text);
  1838. mcrypt_generic_deinit($module);
  1839. mcrypt_module_close($module);
  1840. // print(base64_encode($encrypted));
  1841. //使用BASE64对加密后的字符串进行编码
  1842. return array(ErrorCode::$OK, base64_encode($encrypted));
  1843. } catch (Exception $e) {
  1844. //print $e;
  1845. return array(ErrorCode::$EncryptAESError, null);
  1846. }
  1847. }
  1848. /**
  1849. * 对密文进行解密
  1850. * @param string $encrypted 需要解密的密文
  1851. * @return string 解密得到的明文
  1852. */
  1853. public function decrypt($encrypted, $appid)
  1854. {
  1855. try {
  1856. //使用BASE64对需要解密的字符串进行解码
  1857. $ciphertext_dec = base64_decode($encrypted);
  1858. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  1859. $iv = substr($this->key, 0, 16);
  1860. mcrypt_generic_init($module, $this->key, $iv);
  1861. //解密
  1862. $decrypted = mdecrypt_generic($module, $ciphertext_dec);
  1863. mcrypt_generic_deinit($module);
  1864. mcrypt_module_close($module);
  1865. } catch (Exception $e) {
  1866. return array(ErrorCode::$DecryptAESError, null);
  1867. }
  1868. try {
  1869. //去除补位字符
  1870. $pkc_encoder = new PKCS7Encoder;
  1871. $result = $pkc_encoder->decode($decrypted);
  1872. //去除16位随机字符串,网络字节序和AppId
  1873. if (strlen($result) < 16)
  1874. return "";
  1875. $content = substr($result, 16, strlen($result));
  1876. $len_list = unpack("N", substr($content, 0, 4));
  1877. $xml_len = $len_list[1];
  1878. $xml_content = substr($content, 4, $xml_len);
  1879. $from_appid = substr($content, $xml_len + 4);
  1880. } catch (Exception $e) {
  1881. //print $e;
  1882. return array(ErrorCode::$IllegalBuffer, null);
  1883. }
  1884. if ($from_appid != $appid)
  1885. return array(ErrorCode::$ValidateAppidError, null);
  1886. return array(0, $xml_content);
  1887. }
  1888. /**
  1889. * 随机生成16位字符串
  1890. * @return string 生成的字符串
  1891. */
  1892. function getRandomStr()
  1893. {
  1894. $str = "";
  1895. $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  1896. $max = strlen($str_pol) - 1;
  1897. for ($i = 0; $i < 16; $i++) {
  1898. $str .= $str_pol[mt_rand(0, $max)];
  1899. }
  1900. return $str;
  1901. }
  1902. }
  1903. /**
  1904. * error code
  1905. * 仅用作类内部使用,不用于官方API接口的errCode码
  1906. */
  1907. class ErrorCode
  1908. {
  1909. public static $OK = 0;
  1910. public static $ValidateSignatureError = 40001;
  1911. public static $ParseXmlError = 40002;
  1912. public static $ComputeSignatureError = 40003;
  1913. public static $IllegalAesKey = 40004;
  1914. public static $ValidateAppidError = 40005;
  1915. public static $EncryptAESError = 40006;
  1916. public static $DecryptAESError = 40007;
  1917. public static $IllegalBuffer = 40008;
  1918. public static $EncodeBase64Error = 40009;
  1919. public static $DecodeBase64Error = 40010;
  1920. public static $GenReturnXmlError = 40011;
  1921. public static $errCode=array(
  1922. '0'=>'无问题',
  1923. '40001'=>'签名验证错误',
  1924. '40002'=>'xml解析失败',
  1925. '40003'=>'sha加密生成签名失败',
  1926. '40004'=>'encodingAesKey 非法',
  1927. '40005'=>'appid 校验错误',
  1928. '40006'=>'aes 加密失败',
  1929. '40007'=>'aes 解密失败',
  1930. '40008'=>'解密后得到的buffer非法',
  1931. '40009'=>'base64加密失败',
  1932. '40010'=>'base64解密失败',
  1933. '40011'=>'生成xml失败',
  1934. );
  1935. public static function getErrText($err) {
  1936. if (isset(self::$errCode[$err])) {
  1937. return self::$errCode[$err];
  1938. }else {
  1939. return false;
  1940. };
  1941. }
  1942. }