qywechat.class.php 51 KB

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