qywechat.class.php 65 KB

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