qywechat.class.php 54 KB

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