QyWechat.php 70 KB

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