qywechat.class.php 54 KB

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