qywechat.class.php 63 KB

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