qywechat.class.php 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242
  1. <?php
  2. /**
  3. * 微信公众平台企业号PHP-SDK, 官方API类库
  4. * @author binsee <binsee@163.com>
  5. * @link https://github.com/binsee/wechat-php-sdk
  6. * @version 1.0
  7. * usage:
  8. * $options = array(
  9. * 'token'=>'tokenaccesskey', //填写应用接口的Token
  10. * 'encodingaeskey'=>'encodingaeskey', //填写加密用的EncodingAESKey
  11. * 'appid'=>'wxdk1234567890', //填写高级调用功能的app id
  12. * 'appsecret'=>'xxxxxxxxxxxxxxxxxxx', //填写高级调用功能的密钥
  13. * 'agentid'=>'1', //应用的id
  14. * 'debug'=>false, //调试开关
  15. * 'logcallback'=>'logg', //调试输出方法,需要有一个string类型的参数
  16. * );
  17. *
  18. */
  19. class Wechat
  20. {
  21. const MSGTYPE_TEXT = 'text';
  22. const MSGTYPE_IMAGE = 'image';
  23. const MSGTYPE_LOCATION = 'location';
  24. const MSGTYPE_LINK = 'link'; //暂不支持
  25. const MSGTYPE_EVENT = 'event';
  26. const MSGTYPE_MUSIC = 'music'; //暂不支持
  27. const MSGTYPE_NEWS = 'news';
  28. const MSGTYPE_VOICE = 'voice';
  29. const MSGTYPE_VIDEO = 'video';
  30. const EVENT_SUBSCRIBE = 'subscribe'; //订阅
  31. const EVENT_UNSUBSCRIBE = 'unsubscribe'; //取消订阅
  32. const EVENT_LOCATION = 'LOCATION'; //上报地理位置
  33. const EVENT_ENTER_AGENT = 'enter_agent'; //用户进入应用
  34. const EVENT_MENU_VIEW = 'VIEW'; //菜单 - 点击菜单跳转链接
  35. const EVENT_MENU_CLICK = 'CLICK'; //菜单 - 点击菜单拉取消息
  36. const EVENT_MENU_SCAN_PUSH = 'scancode_push'; //菜单 - 扫码推事件(客户端跳URL)
  37. const EVENT_MENU_SCAN_WAITMSG = 'scancode_waitmsg'; //菜单 - 扫码推事件(客户端不跳URL)
  38. const EVENT_MENU_PIC_SYS = 'pic_sysphoto'; //菜单 - 弹出系统拍照发图
  39. const EVENT_MENU_PIC_PHOTO = 'pic_photo_or_album'; //菜单 - 弹出拍照或者相册发图
  40. const EVENT_MENU_PIC_WEIXIN = 'pic_weixin'; //菜单 - 弹出微信相册发图器
  41. const EVENT_MENU_LOCATION = 'location_select'; //菜单 - 弹出地理位置选择器
  42. const EVENT_SEND_MASS = 'MASSSENDJOBFINISH'; //发送结果 - 高级群发完成
  43. const EVENT_SEND_TEMPLATE = 'TEMPLATESENDJOBFINISH';//发送结果 - 模板消息发送结果
  44. const API_URL_PREFIX = 'https://qyapi.weixin.qq.com/cgi-bin';
  45. const USER_CREATE_URL = '/user/create?';
  46. const USER_UPDATE_URL = '/user/update?';
  47. const USER_DELETE_URL = '/user/delete?';
  48. const USER_BATCHDELETE_URL = '/user/batchdelete?';
  49. const USER_GET_URL = '/user/get?';
  50. const USER_LIST_URL = '/user/simplelist?';
  51. const USER_LIST_INFO_URL = '/user/list?';
  52. const USER_GETINFO_URL = '/user/getuserinfo?';
  53. const USER_INVITE_URL = '/invite/send?';
  54. const DEPARTMENT_CREATE_URL = '/department/create?';
  55. const DEPARTMENT_UPDATE_URL = '/department/update?';
  56. const DEPARTMENT_DELETE_URL = '/department/delete?';
  57. const DEPARTMENT_MOVE_URL = '/department/move?';
  58. const DEPARTMENT_LIST_URL = '/department/list?';
  59. const TAG_CREATE_URL = '/tag/create?';
  60. const TAG_UPDATE_URL = '/tag/update?';
  61. const TAG_DELETE_URL = '/tag/delete?';
  62. const TAG_GET_URL = '/tag/get?';
  63. const TAG_ADDUSER_URL = '/tag/addtagusers?';
  64. const TAG_DELUSER_URL = '/tag/deltagusers?';
  65. const TAG_LIST_URL = '/tag/list?';
  66. const MEDIA_UPLOAD_URL = '/media/upload?';
  67. const MEDIA_GET_URL = '/media/get?';
  68. const AUTHSUCC_URL = '/user/authsucc?';
  69. const MASS_SEND_URL = '/message/send?';
  70. const MENU_CREATE_URL = '/menu/create?';
  71. const MENU_GET_URL = '/menu/get?';
  72. const MENU_DELETE_URL = '/menu/delete?';
  73. const TOKEN_GET_URL = '/gettoken?';
  74. const 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. //TODO: set cache implementation
  793. return false;
  794. }
  795. /**
  796. * 获取缓存,按需重载
  797. * @param string $cachename
  798. * @return mixed
  799. */
  800. protected function getCache($cachename){
  801. //TODO: get cache implementation
  802. return false;
  803. }
  804. /**
  805. * 清除缓存,按需重载
  806. * @param string $cachename
  807. * @return boolean
  808. */
  809. protected function removeCache($cachename){
  810. //TODO: remove cache implementation
  811. return false;
  812. }
  813. /**
  814. * 通用auth验证方法
  815. * @param string $appid
  816. * @param string $appsecret
  817. * @param string $token 手动指定access_token,非必要情况不建议用
  818. */
  819. public function checkAuth($appid='',$appsecret='',$token=''){
  820. if (!$appid || !$appsecret) {
  821. $appid = $this->appid;
  822. $appsecret = $this->appsecret;
  823. }
  824. if ($token) { //手动指定token,优先使用
  825. $this->access_token=$token;
  826. return $this->access_token;
  827. }
  828. $authname = 'qywechat_access_token'.$appid;
  829. if ($rs = $this->getCache($authname)) {
  830. $this->access_token = $rs;
  831. return $rs;
  832. }
  833. $result = $this->http_get(self::API_URL_PREFIX.self::TOKEN_GET_URL.'corpid='.$appid.'&corpsecret='.$appsecret);
  834. if ($result)
  835. {
  836. $json = json_decode($result,true);
  837. if (!$json || isset($json['errcode'])) {
  838. $this->errCode = $json['errcode'];
  839. $this->errMsg = $json['errmsg'];
  840. return false;
  841. }
  842. $this->access_token = $json['access_token'];
  843. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  844. $this->setCache($authname,$this->access_token,$expire);
  845. return $this->access_token;
  846. }
  847. return false;
  848. }
  849. /**
  850. * 删除验证数据
  851. * @param string $appid
  852. */
  853. public function resetAuth($appid=''){
  854. if (!$appid) $appid = $this->appid;
  855. $this->access_token = '';
  856. $authname = 'qywechat_access_token'.$appid;
  857. $this->removeCache($authname);
  858. return true;
  859. }
  860. /**
  861. * 删除JSAPI授权TICKET
  862. * @param string $appid 用于多个appid时使用
  863. */
  864. public function resetJsTicket($appid=''){
  865. if (!$appid) $appid = $this->appid;
  866. $this->jsapi_ticket = '';
  867. $authname = 'qywechat_jsapi_ticket'.$appid;
  868. $this->removeCache($authname);
  869. return true;
  870. }
  871. /**
  872. * 获取JSAPI授权TICKET
  873. * @param string $appid 用于多个appid时使用,可空
  874. * @param string $jsapi_ticket 手动指定jsapi_ticket,非必要情况不建议用
  875. */
  876. public function getJsTicket($appid='',$jsapi_ticket=''){
  877. if (!$this->access_token && !$this->checkAuth()) return false;
  878. if (!$appid) $appid = $this->appid;
  879. if ($jsapi_ticket) { //手动指定token,优先使用
  880. $this->jsapi_ticket = $jsapi_ticket;
  881. return $this->jsapi_ticket;
  882. }
  883. $authname = 'qywechat_jsapi_ticket'.$appid;
  884. if ($rs = $this->getCache($authname)) {
  885. $this->jsapi_ticket = $rs;
  886. return $rs;
  887. }
  888. $result = $this->http_get(self::API_URL_PREFIX.self::TICKET_GET_URL.'access_token='.$this->access_token);
  889. if ($result)
  890. {
  891. $json = json_decode($result,true);
  892. if (!$json || !empty($json['errcode'])) {
  893. $this->errCode = $json['errcode'];
  894. $this->errMsg = $json['errmsg'];
  895. return false;
  896. }
  897. $this->jsapi_ticket = $json['ticket'];
  898. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  899. $this->setCache($authname, $this->jsapi_ticket, $expire);
  900. return $this->jsapi_ticket;
  901. }
  902. return false;
  903. }
  904. /**
  905. * 获取JsApi使用签名
  906. * @param string $url 网页的URL,自动处理#及其后面部分
  907. * @param string $timestamp 当前时间戳 (为空则自动生成)
  908. * @param string $noncestr 随机串 (为空则自动生成)
  909. * @param string $appid 用于多个appid时使用,可空
  910. * @return array|bool 返回签名字串
  911. */
  912. public function getJsSign($url, $timestamp=0, $noncestr='', $appid=''){
  913. if (!$this->jsapi_ticket && !$this->getJsTicket($appid) || !$url) return false;
  914. if (!$timestamp)
  915. $timestamp = time();
  916. if (!$noncestr)
  917. $noncestr = $this->generateNonceStr();
  918. $ret = strpos($url,'#');
  919. if ($ret)
  920. $url = substr($url,0,$ret);
  921. $url = trim($url);
  922. if (empty($url))
  923. return false;
  924. $arrdata = array("timestamp" => $timestamp, "noncestr" => $noncestr, "url" => $url, "jsapi_ticket" => $this->jsapi_ticket);
  925. $sign = $this->getSignature($arrdata);
  926. if (!$sign)
  927. return false;
  928. $signPackage = array(
  929. "appid" => $this->appid,
  930. "noncestr" => $noncestr,
  931. "timestamp" => $timestamp,
  932. "url" => $url,
  933. "signature" => $sign
  934. );
  935. return $signPackage;
  936. }
  937. /**
  938. * 获取签名
  939. * @param array $arrdata 签名数组
  940. * @param string $method 签名方法
  941. * @return boolean|string 签名值
  942. */
  943. public function getSignature($arrdata,$method="sha1") {
  944. if (!function_exists($method)) return false;
  945. ksort($arrdata);
  946. $paramstring = "";
  947. foreach($arrdata as $key => $value)
  948. {
  949. if(strlen($paramstring) == 0)
  950. $paramstring .= $key . "=" . $value;
  951. else
  952. $paramstring .= "&" . $key . "=" . $value;
  953. }
  954. $Sign = $method($paramstring);
  955. return $Sign;
  956. }
  957. /**
  958. * 生成随机字串
  959. * @param number $length 长度,默认为16,最长为32字节
  960. * @return string
  961. */
  962. public function generateNonceStr($length=16){
  963. // 密码字符集,可任意添加你需要的字符
  964. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  965. $str = "";
  966. for($i = 0; $i < $length; $i++)
  967. {
  968. $str .= $chars[mt_rand(0, strlen($chars) - 1)];
  969. }
  970. return $str;
  971. }
  972. /**
  973. * 创建菜单
  974. * @param array $data 菜单数组数据
  975. * example:
  976. * array (
  977. * 'button' => array (
  978. * 0 => array (
  979. * 'name' => '扫码',
  980. * 'sub_button' => array (
  981. * 0 => array (
  982. * 'type' => 'scancode_waitmsg',
  983. * 'name' => '扫码带提示',
  984. * 'key' => 'rselfmenu_0_0',
  985. * ),
  986. * 1 => array (
  987. * 'type' => 'scancode_push',
  988. * 'name' => '扫码推事件',
  989. * 'key' => 'rselfmenu_0_1',
  990. * ),
  991. * ),
  992. * ),
  993. * 1 => array (
  994. * 'name' => '发图',
  995. * 'sub_button' => array (
  996. * 0 => array (
  997. * 'type' => 'pic_sysphoto',
  998. * 'name' => '系统拍照发图',
  999. * 'key' => 'rselfmenu_1_0',
  1000. * ),
  1001. * 1 => array (
  1002. * 'type' => 'pic_photo_or_album',
  1003. * 'name' => '拍照或者相册发图',
  1004. * 'key' => 'rselfmenu_1_1',
  1005. * )
  1006. * ),
  1007. * ),
  1008. * 2 => array (
  1009. * 'type' => 'location_select',
  1010. * 'name' => '发送位置',
  1011. * 'key' => 'rselfmenu_2_0'
  1012. * ),
  1013. * ),
  1014. * )
  1015. * type可以选择为以下几种,会收到相应类型的事件推送。请注意,3到8的所有事件,仅支持微信iPhone5.4.1以上版本,
  1016. * 和Android5.4以上版本的微信用户,旧版本微信用户点击后将没有回应,开发者也不能正常接收到事件推送。
  1017. * 1、click:点击推事件
  1018. * 2、view:跳转URL
  1019. * 3、scancode_push:扫码推事件
  1020. * 4、scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
  1021. * 5、pic_sysphoto:弹出系统拍照发图
  1022. * 6、pic_photo_or_album:弹出拍照或者相册发图
  1023. * 7、pic_weixin:弹出微信相册发图器
  1024. * 8、location_select:弹出地理位置选择器
  1025. */
  1026. public function createMenu($data,$agentid=''){
  1027. if ($agentid=='') {
  1028. $agentid=$this->agentid;
  1029. }
  1030. if (!$this->access_token && !$this->checkAuth()) return false;
  1031. $result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token.'&agentid='.$agentid,self::json_encode($data));
  1032. if ($result)
  1033. {
  1034. $json = json_decode($result,true);
  1035. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1036. $this->errCode = $json['errcode'];
  1037. $this->errMsg = $json['errmsg'];
  1038. return false;
  1039. }
  1040. return true;
  1041. }
  1042. return false;
  1043. }
  1044. /**
  1045. * 获取菜单
  1046. * @return array('menu'=>array(....s))
  1047. */
  1048. public function getMenu($agentid=''){
  1049. if ($agentid=='') {
  1050. $agentid=$this->agentid;
  1051. }
  1052. if (!$this->access_token && !$this->checkAuth()) return false;
  1053. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token.'&agentid='.$agentid);
  1054. if ($result)
  1055. {
  1056. $json = json_decode($result,true);
  1057. if (!$json || isset($json['errcode']) || $json['errcode']!=0) {
  1058. $this->errCode = $json['errcode'];
  1059. $this->errMsg = $json['errmsg'];
  1060. return false;
  1061. }
  1062. return $json;
  1063. }
  1064. return false;
  1065. }
  1066. /**
  1067. * 删除菜单
  1068. * @return boolean
  1069. */
  1070. public function deleteMenu($agentid=''){
  1071. if ($agentid=='') {
  1072. $agentid=$this->agentid;
  1073. }
  1074. if (!$this->access_token && !$this->checkAuth()) return false;
  1075. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token.'&agentid='.$agentid);
  1076. if ($result)
  1077. {
  1078. $json = json_decode($result,true);
  1079. if (!$json || !empty($json['errcode'])) {
  1080. $this->errCode = $json['errcode'];
  1081. $this->errMsg = $json['errmsg'];
  1082. return false;
  1083. }
  1084. return true;
  1085. }
  1086. return false;
  1087. }
  1088. /**
  1089. * 上传多媒体文件 (只有三天的有效期,过期自动被删除)
  1090. * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
  1091. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1092. * @param array $data {"media":'@Path\filename.jpg'}
  1093. * @param type 媒体文件类型:图片(image)、语音(voice)、视频(video),普通文件(file)
  1094. * @return boolean|array
  1095. * {
  1096. * "type": "image",
  1097. * "media_id": "0000001",
  1098. * "created_at": "1380000000"
  1099. * }
  1100. */
  1101. public function uploadMedia($data, $type){
  1102. if (!$this->access_token && !$this->checkAuth()) return false;
  1103. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOAD_URL.'access_token='.$this->access_token.'&type='.$type,$data,true);
  1104. if ($result)
  1105. {
  1106. $json = json_decode($result,true);
  1107. if (!$json || !empty($json['errcode'])) {
  1108. $this->errCode = $json['errcode'];
  1109. $this->errMsg = $json['errmsg'];
  1110. return false;
  1111. }
  1112. return $json;
  1113. }
  1114. return false;
  1115. }
  1116. /**
  1117. * 根据媒体文件ID获取媒体文件
  1118. * @param string $media_id 媒体文件id
  1119. * @return raw data
  1120. */
  1121. public function getMedia($media_id){
  1122. if (!$this->access_token && !$this->checkAuth()) return false;
  1123. $result = $this->http_get(self::API_URL_PREFIX.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
  1124. if ($result)
  1125. {
  1126. $json = json_decode($result,true);
  1127. if (isset($json['errcode'])) {
  1128. $this->errCode = $json['errcode'];
  1129. $this->errMsg = $json['errmsg'];
  1130. return false;
  1131. }
  1132. return $result;
  1133. }
  1134. return false;
  1135. }
  1136. /**
  1137. * 获取企业微信服务器IP地址列表
  1138. * @return array('127.0.0.1','127.0.0.1')
  1139. */
  1140. public function getServerIp(){
  1141. if (!$this->access_token && !$this->checkAuth()) return false;
  1142. $result = $this->http_get(self::API_URL_PREFIX.self::CALLBACKSERVER_GET_URL.'access_token='.$this->access_token);
  1143. if ($result)
  1144. {
  1145. $json = json_decode($result,true);
  1146. if (!$json || isset($json['errcode'])) {
  1147. $this->errCode = $json['errcode'];
  1148. $this->errMsg = $json['errmsg'];
  1149. return false;
  1150. }
  1151. return $json['ip_list'];
  1152. }
  1153. return false;
  1154. }
  1155. /**
  1156. * 创建部门
  1157. * @param array $data 结构体为:
  1158. * array (
  1159. * "name" => "邮箱产品组", //部门名称
  1160. * "parentid" => "1" //父部门id
  1161. * "order" => "1", //(非必须)在父部门中的次序。从1开始,数字越大排序越靠后
  1162. * )
  1163. * @return boolean|array
  1164. * 成功返回结果
  1165. * {
  1166. * "errcode": 0, //返回码
  1167. * "errmsg": "created", //对返回码的文本描述内容
  1168. * "id": 2 //创建的部门id。
  1169. * }
  1170. */
  1171. public function createDepartment($data){
  1172. if (!$this->access_token && !$this->checkAuth()) return false;
  1173. $result = $this->http_post(self::API_URL_PREFIX.self::DEPARTMENT_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1174. if ($result)
  1175. {
  1176. $json = json_decode($result,true);
  1177. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1178. $this->errCode = $json['errcode'];
  1179. $this->errMsg = $json['errmsg'];
  1180. return false;
  1181. }
  1182. return $json;
  1183. }
  1184. return false;
  1185. }
  1186. /**
  1187. * 更新部门
  1188. * @param array $data 结构体为:
  1189. * array(
  1190. * "id" => "1" //(必须)部门id
  1191. * "name" => "邮箱产品组", //(非必须)部门名称
  1192. * "parentid" => "1", //(非必须)父亲部门id。根部门id为1
  1193. * "order" => "1", //(非必须)在父部门中的次序。从1开始,数字越大排序越靠后
  1194. * )
  1195. * @return boolean|array 成功返回结果
  1196. * {
  1197. * "errcode": 0, //返回码
  1198. * "errmsg": "updated" //对返回码的文本描述内容
  1199. * }
  1200. */
  1201. public function updateDepartment($data){
  1202. if (!$this->access_token && !$this->checkAuth()) return false;
  1203. $result = $this->http_post(self::API_URL_PREFIX.self::DEPARTMENT_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1204. if ($result)
  1205. {
  1206. $json = json_decode($result,true);
  1207. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1208. $this->errCode = $json['errcode'];
  1209. $this->errMsg = $json['errmsg'];
  1210. return false;
  1211. }
  1212. return $json;
  1213. }
  1214. return false;
  1215. }
  1216. /**
  1217. * 删除部门
  1218. * @param $id
  1219. * @return boolean|array 成功返回结果
  1220. * {
  1221. * "errcode": 0, //返回码
  1222. * "errmsg": "deleted" //对返回码的文本描述内容
  1223. * }
  1224. */
  1225. public function deleteDepartment($id){
  1226. if (!$this->access_token && !$this->checkAuth()) return false;
  1227. $result = $this->http_get(self::API_URL_PREFIX.self::DEPARTMENT_DELETE_URL.'access_token='.$this->access_token.'&id='.$id);
  1228. if ($result)
  1229. {
  1230. $json = json_decode($result,true);
  1231. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1232. $this->errCode = $json['errcode'];
  1233. $this->errMsg = $json['errmsg'];
  1234. return false;
  1235. }
  1236. return $json;
  1237. }
  1238. return false;
  1239. }
  1240. /**
  1241. * 移动部门
  1242. * @param $data
  1243. * array(
  1244. * "department_id" => "5", //所要移动的部门
  1245. * "to_parentid" => "2", //想移动到的父部门节点,根部门为1
  1246. * "to_position" => "1" //(非必须)想移动到的父部门下的位置,1表示最上方,往后位置为2,3,4,以此类推,默认为1
  1247. * )
  1248. * @return boolean|array 成功返回结果
  1249. * {
  1250. * "errcode": 0, //返回码
  1251. * "errmsg": "ok" //对返回码的文本描述内容
  1252. * }
  1253. */
  1254. public function moveDepartment($data){
  1255. if (!$this->access_token && !$this->checkAuth()) return false;
  1256. $result = $this->http_post(self::API_URL_PREFIX.self::DEPARTMENT_MOVE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1257. if ($result)
  1258. {
  1259. $json = json_decode($result,true);
  1260. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1261. $this->errCode = $json['errcode'];
  1262. $this->errMsg = $json['errmsg'];
  1263. return false;
  1264. }
  1265. return $json;
  1266. }
  1267. return false;
  1268. }
  1269. /**
  1270. * 获取部门列表
  1271. * @return boolean|array 成功返回结果
  1272. * {
  1273. * "errcode": 0,
  1274. * "errmsg": "ok",
  1275. * "department": [ //部门列表数据。以部门的order字段从小到大排列
  1276. * {
  1277. * "id": 1,
  1278. * "name": "广州研发中心",
  1279. * "parentid": 0,
  1280. * "order": 40
  1281. * },
  1282. * {
  1283. * "id": 2
  1284. * "name": "邮箱产品部",
  1285. * "parentid": 1,
  1286. * "order": 40
  1287. * }
  1288. * ]
  1289. * }
  1290. */
  1291. public function getDepartment(){
  1292. if (!$this->access_token && !$this->checkAuth()) return false;
  1293. $result = $this->http_get(self::API_URL_PREFIX.self::DEPARTMENT_LIST_URL.'access_token='.$this->access_token);
  1294. if ($result)
  1295. {
  1296. $json = json_decode($result,true);
  1297. if (!$json || !empty($json['errcode'])) {
  1298. $this->errCode = $json['errcode'];
  1299. $this->errMsg = $json['errmsg'];
  1300. return false;
  1301. }
  1302. return $json;
  1303. }
  1304. return false;
  1305. }
  1306. /**
  1307. * 创建成员
  1308. * @param array $data 结构体为:
  1309. * array(
  1310. * "userid" => "zhangsan",
  1311. * "name" => "张三",
  1312. * "department" => [1, 2],
  1313. * "position" => "产品经理",
  1314. * "mobile" => "15913215421",
  1315. * "gender" => 1, //性别。gender=0表示男,=1表示女
  1316. * "tel" => "62394",
  1317. * "email" => "zhangsan@gzdev.com",
  1318. * "weixinid" => "zhangsan4dev"
  1319. * )
  1320. * @return boolean|array
  1321. * 成功返回结果
  1322. * {
  1323. * "errcode": 0, //返回码
  1324. * "errmsg": "created", //对返回码的文本描述内容
  1325. * }
  1326. */
  1327. public function createUser($data){
  1328. if (!$this->access_token && !$this->checkAuth()) return false;
  1329. $result = $this->http_post(self::API_URL_PREFIX.self::USER_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1330. if ($result)
  1331. {
  1332. $json = json_decode($result,true);
  1333. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1334. $this->errCode = $json['errcode'];
  1335. $this->errMsg = $json['errmsg'];
  1336. return false;
  1337. }
  1338. return $json;
  1339. }
  1340. return false;
  1341. }
  1342. /**
  1343. * 更新成员
  1344. * @param array $data 结构体为:
  1345. * array(
  1346. * "userid" => "zhangsan",
  1347. * "name" => "张三",
  1348. * "department" => [1, 2],
  1349. * "position" => "产品经理",
  1350. * "mobile" => "15913215421",
  1351. * "gender" => 1, //性别。gender=0表示男,=1表示女
  1352. * "tel" => "62394",
  1353. * "email" => "zhangsan@gzdev.com",
  1354. * "weixinid" => "zhangsan4dev"
  1355. * )
  1356. * @return boolean|array 成功返回结果
  1357. * {
  1358. * "errcode": 0, //返回码
  1359. * "errmsg": "updated" //对返回码的文本描述内容
  1360. * }
  1361. */
  1362. public function updateUser($data){
  1363. if (!$this->access_token && !$this->checkAuth()) return false;
  1364. $result = $this->http_post(self::API_URL_PREFIX.self::USER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1365. if ($result)
  1366. {
  1367. $json = json_decode($result,true);
  1368. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1369. $this->errCode = $json['errcode'];
  1370. $this->errMsg = $json['errmsg'];
  1371. return false;
  1372. }
  1373. return $json;
  1374. }
  1375. return false;
  1376. }
  1377. /**
  1378. * 删除成员
  1379. * @param $userid 员工UserID。对应管理端的帐号
  1380. * @return boolean|array 成功返回结果
  1381. * {
  1382. * "errcode": 0, //返回码
  1383. * "errmsg": "deleted" //对返回码的文本描述内容
  1384. * }
  1385. */
  1386. public function deleteUser($userid){
  1387. if (!$this->access_token && !$this->checkAuth()) return false;
  1388. $result = $this->http_get(self::API_URL_PREFIX.self::USER_DELETE_URL.'access_token='.$this->access_token.'&userid='.$userid);
  1389. if ($result)
  1390. {
  1391. $json = json_decode($result,true);
  1392. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1393. $this->errCode = $json['errcode'];
  1394. $this->errMsg = $json['errmsg'];
  1395. return false;
  1396. }
  1397. return $json;
  1398. }
  1399. return false;
  1400. }
  1401. /**
  1402. * 批量删除成员
  1403. * @param array $userid 员工UserID数组。对应管理端的帐号
  1404. * {
  1405. * 'userid1',
  1406. * 'userid2',
  1407. * 'userid3',
  1408. * }
  1409. * @return boolean|array 成功返回结果
  1410. * {
  1411. * "errcode": 0, //返回码
  1412. * "errmsg": "deleted" //对返回码的文本描述内容
  1413. * }
  1414. */
  1415. public function deleteUsers($userids){
  1416. if (!$userids) return false;
  1417. $data = array('useridlist'=>$userids);
  1418. if (!$this->access_token && !$this->checkAuth()) return false;
  1419. $result = $this->http_post(self::API_URL_PREFIX.self::USER_BATCHDELETE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1420. if ($result)
  1421. {
  1422. $json = json_decode($result,true);
  1423. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1424. $this->errCode = $json['errcode'];
  1425. $this->errMsg = $json['errmsg'];
  1426. return false;
  1427. }
  1428. return $json;
  1429. }
  1430. return false;
  1431. }
  1432. /**
  1433. * 获取成员信息
  1434. * @param $userid 员工UserID。对应管理端的帐号
  1435. * @return boolean|array 成功返回结果
  1436. * {
  1437. * "errcode": 0,
  1438. * "errmsg": "ok",
  1439. * "userid": "zhangsan",
  1440. * "name": "李四",
  1441. * "department": [1, 2],
  1442. * "position": "后台工程师",
  1443. * "mobile": "15913215421",
  1444. * "gender": 1, //性别。gender=0表示男,=1表示女
  1445. * "tel": "62394",
  1446. * "email": "zhangsan@gzdev.com",
  1447. * "weixinid": "lisifordev", //微信号
  1448. * "avatar": "http://wx.qlogo.cn/mmopen/ajNVdqHZLLA3W..../0", //头像url。注:如果要获取小图将url最后的"/0"改成"/64"即可
  1449. * "status": 1 //关注状态: 1=已关注,2=已冻结,4=未关注
  1450. * "extattr": {"attrs":[{"name":"爱好","value":"旅游"},{"name":"卡号","value":"1234567234"}]}
  1451. * }
  1452. */
  1453. public function getUserInfo($userid){
  1454. if (!$this->access_token && !$this->checkAuth()) return false;
  1455. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&userid='.$userid);
  1456. if ($result)
  1457. {
  1458. $json = json_decode($result,true);
  1459. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1460. $this->errCode = $json['errcode'];
  1461. $this->errMsg = $json['errmsg'];
  1462. return false;
  1463. }
  1464. return $json;
  1465. }
  1466. return false;
  1467. }
  1468. /**
  1469. * 获取部门成员
  1470. * @param $department_id 部门id
  1471. * @param $fetch_child 1/0:是否递归获取子部门下面的成员
  1472. * @param $status 0获取全部员工,1获取已关注成员列表,2获取禁用成员列表,4获取未关注成员列表。status可叠加
  1473. * @return boolean|array 成功返回结果
  1474. * {
  1475. * "errcode": 0,
  1476. * "errmsg": "ok",
  1477. * "userlist": [
  1478. * {
  1479. * "userid": "zhangsan",
  1480. * "name": "李四"
  1481. * }
  1482. * ]
  1483. * }
  1484. */
  1485. public function getUserList($department_id,$fetch_child=0,$status=0){
  1486. if (!$this->access_token && !$this->checkAuth()) return false;
  1487. $result = $this->http_get(self::API_URL_PREFIX.self::USER_LIST_URL.'access_token='.$this->access_token
  1488. .'&department_id='.$department_id.'&fetch_child='.$fetch_child.'&status='.$status);
  1489. if ($result)
  1490. {
  1491. $json = json_decode($result,true);
  1492. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1493. $this->errCode = $json['errcode'];
  1494. $this->errMsg = $json['errmsg'];
  1495. return false;
  1496. }
  1497. return $json;
  1498. }
  1499. return false;
  1500. }
  1501. /**
  1502. * 获取部门成员详情
  1503. * @param $department_id 部门id
  1504. * @param $fetch_child 1/0:是否递归获取子部门下面的成员
  1505. * @param $status 0获取全部员工,1获取已关注成员列表,2获取禁用成员列表,4获取未关注成员列表。status可叠加
  1506. * @return boolean|array 成功返回结果
  1507. * {
  1508. * "errcode": 0,
  1509. * "errmsg": "ok",
  1510. * "userlist": [
  1511. * {
  1512. * "userid": "zhangsan",
  1513. * "name": "李四",
  1514. * "department": [1, 2],
  1515. * "position": "后台工程师",
  1516. * "mobile": "15913215421",
  1517. * "gender": 1, //性别。gender=0表示男,=1表示女
  1518. * "tel": "62394",
  1519. * "email": "zhangsan@gzdev.com",
  1520. * "weixinid": "lisifordev", //微信号
  1521. * "avatar": "http://wx.qlogo.cn/mmopen/ajNVdqHZLLA3W..../0", //头像url。注:如果要获取小图将url最后的"/0"改成"/64"即可
  1522. * "status": 1 //关注状态: 1=已关注,2=已冻结,4=未关注
  1523. * "extattr": {"attrs":[{"name":"爱好","value":"旅游"},{"name":"卡号","value":"1234567234"}]}
  1524. * }
  1525. * ]
  1526. * }
  1527. */
  1528. public function getUserListInfo($department_id,$fetch_child=0,$status=0){
  1529. if (!$this->access_token && !$this->checkAuth()) return false;
  1530. $result = $this->http_get(self::API_URL_PREFIX.self::USER_LIST_INFO_URL.'access_token='.$this->access_token
  1531. .'&department_id='.$department_id.'&fetch_child='.$fetch_child.'&status='.$status);
  1532. if ($result)
  1533. {
  1534. $json = json_decode($result,true);
  1535. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1536. $this->errCode = $json['errcode'];
  1537. $this->errMsg = $json['errmsg'];
  1538. return false;
  1539. }
  1540. return $json;
  1541. }
  1542. return false;
  1543. }
  1544. /**
  1545. * 根据code获取成员信息
  1546. * 通过Oauth2.0或者设置了二次验证时获取的code,用于换取成员的UserId和DeviceId
  1547. *
  1548. * @param $code Oauth2.0或者二次验证时返回的code值
  1549. * @param $agentid 跳转链接时所在的企业应用ID,未填则默认为当前配置的应用id
  1550. * @return boolean|array 成功返回数组
  1551. * array(
  1552. * 'UserId' => 'USERID', //员工UserID
  1553. * 'DeviceId' => 'DEVICEID' //手机设备号(由微信在安装时随机生成)
  1554. * )
  1555. */
  1556. public function getUserId($code,$agentid=0){
  1557. if (!$agentid) $agentid=$this->agentid;
  1558. if (!$this->access_token && !$this->checkAuth()) return false;
  1559. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GETINFO_URL.'access_token='.$this->access_token.'&code='.$code.'&agentid'.$agentid);
  1560. if ($result)
  1561. {
  1562. $json = json_decode($result,true);
  1563. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1564. $this->errCode = $json['errcode'];
  1565. $this->errMsg = $json['errmsg'];
  1566. return false;
  1567. }
  1568. return $json;
  1569. }
  1570. return false;
  1571. }
  1572. /**
  1573. * 邀请成员关注
  1574. * 向未关注企业号的成员发送关注邀请。认证号优先判断顺序weixinid>手机号>邮箱绑定>邮件;非认证号只能邮件邀请
  1575. *
  1576. * @param $userid 用户的userid
  1577. * @param $invite_tips 推送到微信上的提示语(只有认证号可以使用)。当使用微信推送时,该字段默认为“请关注XXX企业号”,邮件邀请时,该字段无效。
  1578. * @return boolean|array 成功返回数组
  1579. * array(
  1580. * 'errcode' => 0,
  1581. * 'errmsg' => 'ok',
  1582. * 'type' => 1 //邀请方式 1.微信邀请 2.邮件邀请
  1583. * )
  1584. */
  1585. public function sendInvite($userid,$invite_tips=''){
  1586. $data = array( 'userid' => $userid );
  1587. if (!$invite_tips) {
  1588. $data['invite_tips'] = $invite_tips;
  1589. }
  1590. if (!$this->access_token && !$this->checkAuth()) return false;
  1591. $result = $this->http_post(self::API_URL_PREFIX.self::USER_INVITE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1592. if ($result)
  1593. {
  1594. $json = json_decode($result,true);
  1595. if (!$json || !empty($json['errcode'])) {
  1596. $this->errCode = $json['errcode'];
  1597. $this->errMsg = $json['errmsg'];
  1598. return false;
  1599. }
  1600. return $json;
  1601. }
  1602. return false;
  1603. }
  1604. /**
  1605. * 创建标签
  1606. * @param array $data 结构体为:
  1607. * array(
  1608. * "tagname" => "UI"
  1609. * )
  1610. * @return boolean|array
  1611. * 成功返回结果
  1612. * {
  1613. * "errcode": 0, //返回码
  1614. * "errmsg": "created", //对返回码的文本描述内容
  1615. * "tagid": "1"
  1616. * }
  1617. */
  1618. public function createTag($data){
  1619. if (!$this->access_token && !$this->checkAuth()) return false;
  1620. $result = $this->http_post(self::API_URL_PREFIX.self::TAG_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1621. if ($result)
  1622. {
  1623. $json = json_decode($result,true);
  1624. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1625. $this->errCode = $json['errcode'];
  1626. $this->errMsg = $json['errmsg'];
  1627. return false;
  1628. }
  1629. return $json;
  1630. }
  1631. return false;
  1632. }
  1633. /**
  1634. * 更新标签
  1635. * @param array $data 结构体为:
  1636. * array(
  1637. * "tagid" => "1",
  1638. * "tagname" => "UI design"
  1639. * )
  1640. * @return boolean|array 成功返回结果
  1641. * {
  1642. * "errcode": 0, //返回码
  1643. * "errmsg": "updated" //对返回码的文本描述内容
  1644. * }
  1645. */
  1646. public function updateTag($data){
  1647. if (!$this->access_token && !$this->checkAuth()) return false;
  1648. $result = $this->http_post(self::API_URL_PREFIX.self::TAG_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1649. if ($result)
  1650. {
  1651. $json = json_decode($result,true);
  1652. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1653. $this->errCode = $json['errcode'];
  1654. $this->errMsg = $json['errmsg'];
  1655. return false;
  1656. }
  1657. return $json;
  1658. }
  1659. return false;
  1660. }
  1661. /**
  1662. * 删除标签
  1663. * @param $tagid 标签TagID
  1664. * @return boolean|array 成功返回结果
  1665. * {
  1666. * "errcode": 0, //返回码
  1667. * "errmsg": "deleted" //对返回码的文本描述内容
  1668. * }
  1669. */
  1670. public function deleteTag($tagid){
  1671. if (!$this->access_token && !$this->checkAuth()) return false;
  1672. $result = $this->http_get(self::API_URL_PREFIX.self::TAG_DELETE_URL.'access_token='.$this->access_token.'&tagid='.$tagid);
  1673. if ($result)
  1674. {
  1675. $json = json_decode($result,true);
  1676. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1677. $this->errCode = $json['errcode'];
  1678. $this->errMsg = $json['errmsg'];
  1679. return false;
  1680. }
  1681. return $json;
  1682. }
  1683. return false;
  1684. }
  1685. /**
  1686. * 获取标签成员
  1687. * @param $tagid 标签TagID
  1688. * @return boolean|array 成功返回结果
  1689. * {
  1690. * "errcode": 0,
  1691. * "errmsg": "ok",
  1692. * "userlist": [
  1693. * {
  1694. * "userid": "zhangsan",
  1695. * "name": "李四"
  1696. * }
  1697. * ]
  1698. * }
  1699. */
  1700. public function getTag($tagid){
  1701. if (!$this->access_token && !$this->checkAuth()) return false;
  1702. $result = $this->http_get(self::API_URL_PREFIX.self::TAG_GET_URL.'access_token='.$this->access_token.'&tagid='.$tagid);
  1703. if ($result)
  1704. {
  1705. $json = json_decode($result,true);
  1706. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1707. $this->errCode = $json['errcode'];
  1708. $this->errMsg = $json['errmsg'];
  1709. return false;
  1710. }
  1711. return $json;
  1712. }
  1713. return false;
  1714. }
  1715. /**
  1716. * 增加标签成员
  1717. * @param array $data 结构体为:
  1718. * array (
  1719. * "tagid" => "1",
  1720. * "userlist" => array( //企业员工ID列表
  1721. * "user1",
  1722. * "user2"
  1723. * )
  1724. * )
  1725. * @return boolean|array
  1726. * 成功返回结果
  1727. * {
  1728. * "errcode": 0, //返回码
  1729. * "errmsg": "ok", //对返回码的文本描述内容
  1730. * "invalidlist":"usr1|usr2|usr" //若部分userid非法,则会有此段。不在权限内的员工ID列表,以“|”分隔
  1731. * }
  1732. */
  1733. public function addTagUser($data){
  1734. if (!$this->access_token && !$this->checkAuth()) return false;
  1735. $result = $this->http_post(self::API_URL_PREFIX.self::TAG_ADDUSER_URL.'access_token='.$this->access_token,self::json_encode($data));
  1736. if ($result)
  1737. {
  1738. $json = json_decode($result,true);
  1739. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1740. $this->errCode = $json['errcode'];
  1741. $this->errMsg = $json['errmsg'];
  1742. return false;
  1743. }
  1744. return $json;
  1745. }
  1746. return false;
  1747. }
  1748. /**
  1749. * 删除标签成员
  1750. * @param array $data 结构体为:
  1751. * array (
  1752. * "tagid" => "1",
  1753. * "userlist" => array( //企业员工ID列表
  1754. * "user1",
  1755. * "user2"
  1756. * )
  1757. * )
  1758. * @return boolean|array
  1759. * 成功返回结果
  1760. * {
  1761. * "errcode": 0, //返回码
  1762. * "errmsg": "deleted", //对返回码的文本描述内容
  1763. * "invalidlist":"usr1|usr2|usr" //若部分userid非法,则会有此段。不在权限内的员工ID列表,以“|”分隔
  1764. * }
  1765. */
  1766. public function delTagUser($data){
  1767. if (!$this->access_token && !$this->checkAuth()) return false;
  1768. $result = $this->http_post(self::API_URL_PREFIX.self::TAG_DELUSER_URL.'access_token='.$this->access_token,self::json_encode($data));
  1769. if ($result)
  1770. {
  1771. $json = json_decode($result,true);
  1772. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1773. $this->errCode = $json['errcode'];
  1774. $this->errMsg = $json['errmsg'];
  1775. return false;
  1776. }
  1777. return $json;
  1778. }
  1779. return false;
  1780. }
  1781. /**
  1782. * 获取标签列表
  1783. * @return boolean|array 成功返回数组结果,这里附上json样例
  1784. * {
  1785. * "errcode": 0,
  1786. * "errmsg": "ok",
  1787. * "taglist":[
  1788. * {"tagid":1,"tagname":"a"},
  1789. * {"tagid":2,"tagname":"b"}
  1790. * ]
  1791. * }
  1792. */
  1793. public function getTagList(){
  1794. if (!$this->access_token && !$this->checkAuth()) return false;
  1795. $result = $this->http_get(self::API_URL_PREFIX.self::TAG_LIST_URL.'access_token='.$this->access_token);
  1796. if ($result)
  1797. {
  1798. $json = json_decode($result,true);
  1799. if (!$json || !empty($json['errcode'])) {
  1800. $this->errCode = $json['errcode'];
  1801. $this->errMsg = $json['errmsg'];
  1802. return false;
  1803. }
  1804. return $json;
  1805. }
  1806. return false;
  1807. }
  1808. /**
  1809. * 主动发送信息接口
  1810. * @param array $data 结构体为:
  1811. * array(
  1812. * "touser" => "UserID1|UserID2|UserID3",
  1813. * "toparty" => "PartyID1|PartyID2 ",
  1814. * "totag" => "TagID1|TagID2 ",
  1815. * "safe":"0" //是否为保密消息,对于news无效
  1816. * "agentid" => "001", //应用id
  1817. * "msgtype" => "text", //根据信息类型,选择下面对应的信息结构体
  1818. *
  1819. * "text" => array(
  1820. * "content" => "Holiday Request For Pony(http://xxxxx)"
  1821. * ),
  1822. *
  1823. * "image" => array(
  1824. * "media_id" => "MEDIA_ID"
  1825. * ),
  1826. *
  1827. * "voice" => array(
  1828. * "media_id" => "MEDIA_ID"
  1829. * ),
  1830. *
  1831. * " video" => array(
  1832. * "media_id" => "MEDIA_ID",
  1833. * "title" => "Title",
  1834. * "description" => "Description"
  1835. * ),
  1836. *
  1837. * "file" => array(
  1838. * "media_id" => "MEDIA_ID"
  1839. * ),
  1840. *
  1841. * "news" => array( //不支持保密
  1842. * "articles" => array( //articles 图文消息,一个图文消息支持1到10个图文
  1843. * array(
  1844. * "title" => "Title", //标题
  1845. * "description" => "Description", //描述
  1846. * "url" => "URL", //点击后跳转的链接。可根据url里面带的code参数校验员工的真实身份。
  1847. * "picurl" => "PIC_URL", //图文消息的图片链接,支持JPG、PNG格式,较好的效果为大图640*320,
  1848. * //小图80*80。如不填,在客户端不显示图片
  1849. * ),
  1850. * )
  1851. * ),
  1852. *
  1853. * "mpnews" => array(
  1854. * "articles" => array( //articles 图文消息,一个图文消息支持1到10个图文
  1855. * array(
  1856. * "title" => "Title", //图文消息的标题
  1857. * "thumb_media_id" => "id", //图文消息缩略图的media_id
  1858. * "author" => "Author", //图文消息的作者(可空)
  1859. * "content_source_url" => "URL", //图文消息点击“阅读原文”之后的页面链接(可空)
  1860. * "content" => "Content" //图文消息的内容,支持html标签
  1861. * "digest" => "Digest description", //图文消息的描述
  1862. * "show_cover_pic" => "0" //是否显示封面,1为显示,0为不显示(可空)
  1863. * ),
  1864. * )
  1865. * )
  1866. * )
  1867. * 请查看官方开发文档中的 发送消息 -> 消息类型及数据格式
  1868. *
  1869. * @return boolean|array
  1870. * 如果对应用或收件人、部门、标签任何一个无权限,则本次发送失败;
  1871. * 如果收件人、部门或标签不存在,发送仍然执行,但返回无效的部分。
  1872. * {
  1873. * "errcode": 0,
  1874. * "errmsg": "ok",
  1875. * "invaliduser": "UserID1",
  1876. * "invalidparty":"PartyID1",
  1877. * "invalidtag":"TagID1"
  1878. * }
  1879. */
  1880. public function sendMessage($data){
  1881. if (!$this->access_token && !$this->checkAuth()) return false;
  1882. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1883. if ($result)
  1884. {
  1885. $json = json_decode($result,true);
  1886. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1887. $this->errCode = $json['errcode'];
  1888. $this->errMsg = $json['errmsg'];
  1889. return false;
  1890. }
  1891. return $json;
  1892. }
  1893. return false;
  1894. }
  1895. /**
  1896. * 二次验证
  1897. * 企业在开启二次验证时,必须填写企业二次验证页面的url。
  1898. * 当员工绑定通讯录中的帐号后,会收到一条图文消息,
  1899. * 引导员工到企业的验证页面验证身份,企业在员工验证成功后,
  1900. * 调用如下接口即可让员工关注成功。
  1901. *
  1902. * @param $userid
  1903. * @return boolean|array 成功返回结果
  1904. * {
  1905. * "errcode": 0, //返回码
  1906. * "errmsg": "ok" //对返回码的文本描述内容
  1907. * }
  1908. */
  1909. public function authSucc($userid){
  1910. if (!$this->access_token && !$this->checkAuth()) return false;
  1911. $result = $this->http_get(self::API_URL_PREFIX.self::AUTHSUCC_URL.'access_token='.$this->access_token.'&userid='.$userid);
  1912. if ($result)
  1913. {
  1914. $json = json_decode($result,true);
  1915. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1916. $this->errCode = $json['errcode'];
  1917. $this->errMsg = $json['errmsg'];
  1918. return false;
  1919. }
  1920. return $json;
  1921. }
  1922. return false;
  1923. }
  1924. /**
  1925. * oauth 授权跳转接口
  1926. * @param string $callback 回调URI
  1927. * @param string $state 重定向后会带上state参数,企业可以填写a-zA-Z0-9的参数值
  1928. * @return string
  1929. */
  1930. public function getOauthRedirect($callback,$state='STATE',$scope='snsapi_base'){
  1931. return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  1932. }
  1933. }
  1934. /**
  1935. * PKCS7Encoder class
  1936. *
  1937. * 提供基于PKCS7算法的加解密接口.
  1938. */
  1939. class PKCS7Encoder
  1940. {
  1941. public static $block_size = 32;
  1942. /**
  1943. * 对需要加密的明文进行填充补位
  1944. * @param $text 需要进行填充补位操作的明文
  1945. * @return 补齐明文字符串
  1946. */
  1947. function encode($text)
  1948. {
  1949. $block_size = PKCS7Encoder::$block_size;
  1950. $text_length = strlen($text);
  1951. //计算需要填充的位数
  1952. $amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
  1953. if ($amount_to_pad == 0) {
  1954. $amount_to_pad = PKCS7Encoder::block_size;
  1955. }
  1956. //获得补位所用的字符
  1957. $pad_chr = chr($amount_to_pad);
  1958. $tmp = "";
  1959. for ($index = 0; $index < $amount_to_pad; $index++) {
  1960. $tmp .= $pad_chr;
  1961. }
  1962. return $text . $tmp;
  1963. }
  1964. /**
  1965. * 对解密后的明文进行补位删除
  1966. * @param decrypted 解密后的明文
  1967. * @return 删除填充补位后的明文
  1968. */
  1969. function decode($text)
  1970. {
  1971. $pad = ord(substr($text, -1));
  1972. if ($pad < 1 || $pad > PKCS7Encoder::$block_size) {
  1973. $pad = 0;
  1974. }
  1975. return substr($text, 0, (strlen($text) - $pad));
  1976. }
  1977. }
  1978. /**
  1979. * Prpcrypt class
  1980. *
  1981. * 提供接收和推送给公众平台消息的加解密接口.
  1982. */
  1983. class Prpcrypt
  1984. {
  1985. public $key;
  1986. function __construct($k) {
  1987. $this->key = base64_decode($k . "=");
  1988. }
  1989. /**
  1990. * 兼容老版本php构造函数,不能在 __construct() 方法前边,否则报错
  1991. */
  1992. function Prpcrypt($k)
  1993. {
  1994. $this->key = base64_decode($k . "=");
  1995. }
  1996. /**
  1997. * 对明文进行加密
  1998. * @param string $text 需要加密的明文
  1999. * @return string 加密后的密文
  2000. */
  2001. public function encrypt($text, $appid)
  2002. {
  2003. try {
  2004. //获得16位随机字符串,填充到明文之前
  2005. $random = $this->getRandomStr();//"aaaabbbbccccdddd";
  2006. $text = $random . pack("N", strlen($text)) . $text . $appid;
  2007. // 网络字节序
  2008. $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  2009. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  2010. $iv = substr($this->key, 0, 16);
  2011. //使用自定义的填充方式对明文进行补位填充
  2012. $pkc_encoder = new PKCS7Encoder;
  2013. $text = $pkc_encoder->encode($text);
  2014. mcrypt_generic_init($module, $this->key, $iv);
  2015. //加密
  2016. $encrypted = mcrypt_generic($module, $text);
  2017. mcrypt_generic_deinit($module);
  2018. mcrypt_module_close($module);
  2019. // print(base64_encode($encrypted));
  2020. //使用BASE64对加密后的字符串进行编码
  2021. return array(ErrorCode::$OK, base64_encode($encrypted));
  2022. } catch (Exception $e) {
  2023. //print $e;
  2024. return array(ErrorCode::$EncryptAESError, null);
  2025. }
  2026. }
  2027. /**
  2028. * 对密文进行解密
  2029. * @param string $encrypted 需要解密的密文
  2030. * @return string 解密得到的明文
  2031. */
  2032. public function decrypt($encrypted, $appid)
  2033. {
  2034. try {
  2035. //使用BASE64对需要解密的字符串进行解码
  2036. $ciphertext_dec = base64_decode($encrypted);
  2037. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  2038. $iv = substr($this->key, 0, 16);
  2039. mcrypt_generic_init($module, $this->key, $iv);
  2040. //解密
  2041. $decrypted = mdecrypt_generic($module, $ciphertext_dec);
  2042. mcrypt_generic_deinit($module);
  2043. mcrypt_module_close($module);
  2044. } catch (Exception $e) {
  2045. return array(ErrorCode::$DecryptAESError, null);
  2046. }
  2047. try {
  2048. //去除补位字符
  2049. $pkc_encoder = new PKCS7Encoder;
  2050. $result = $pkc_encoder->decode($decrypted);
  2051. //去除16位随机字符串,网络字节序和AppId
  2052. if (strlen($result) < 16)
  2053. return "";
  2054. $content = substr($result, 16, strlen($result));
  2055. $len_list = unpack("N", substr($content, 0, 4));
  2056. $xml_len = $len_list[1];
  2057. $xml_content = substr($content, 4, $xml_len);
  2058. $from_appid = substr($content, $xml_len + 4);
  2059. } catch (Exception $e) {
  2060. //print $e;
  2061. return array(ErrorCode::$IllegalBuffer, null);
  2062. }
  2063. if ($from_appid != $appid)
  2064. return array(ErrorCode::$ValidateAppidError, null);
  2065. return array(0, $xml_content);
  2066. }
  2067. /**
  2068. * 随机生成16位字符串
  2069. * @return string 生成的字符串
  2070. */
  2071. function getRandomStr()
  2072. {
  2073. $str = "";
  2074. $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  2075. $max = strlen($str_pol) - 1;
  2076. for ($i = 0; $i < 16; $i++) {
  2077. $str .= $str_pol[mt_rand(0, $max)];
  2078. }
  2079. return $str;
  2080. }
  2081. }
  2082. /**
  2083. * error code
  2084. * 仅用作类内部使用,不用于官方API接口的errCode码
  2085. */
  2086. class ErrorCode
  2087. {
  2088. public static $OK = 0;
  2089. public static $ValidateSignatureError = 40001;
  2090. public static $ParseXmlError = 40002;
  2091. public static $ComputeSignatureError = 40003;
  2092. public static $IllegalAesKey = 40004;
  2093. public static $ValidateAppidError = 40005;
  2094. public static $EncryptAESError = 40006;
  2095. public static $DecryptAESError = 40007;
  2096. public static $IllegalBuffer = 40008;
  2097. public static $EncodeBase64Error = 40009;
  2098. public static $DecodeBase64Error = 40010;
  2099. public static $GenReturnXmlError = 40011;
  2100. public static $errCode=array(
  2101. '0'=>'无问题',
  2102. '40001'=>'签名验证错误',
  2103. '40002'=>'xml解析失败',
  2104. '40003'=>'sha加密生成签名失败',
  2105. '40004'=>'encodingAesKey 非法',
  2106. '40005'=>'appid 校验错误',
  2107. '40006'=>'aes 加密失败',
  2108. '40007'=>'aes 解密失败',
  2109. '40008'=>'解密后得到的buffer非法',
  2110. '40009'=>'base64加密失败',
  2111. '40010'=>'base64解密失败',
  2112. '40011'=>'生成xml失败',
  2113. );
  2114. public static function getErrText($err) {
  2115. if (isset(self::$errCode[$err])) {
  2116. return self::$errCode[$err];
  2117. }else {
  2118. return false;
  2119. };
  2120. }
  2121. }