wechat.class.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894
  1. <?php
  2. /**
  3. * 微信公众平台PHP-SDK, 官方API部分
  4. * @author dodge <dodgepudding@gmail.com>
  5. * @link https://github.com/dodgepudding/wechat-php-sdk
  6. * @version 1.2
  7. * usage:
  8. * $options = array(
  9. * 'token'=>'tokenaccesskey', //填写你设定的key
  10. * 'appid'=>'wxdk1234567890', //填写高级调用功能的app id
  11. * 'appsecret'=>'xxxxxxxxxxxxxxxxxxx', //填写高级调用功能的密钥
  12. * 'partnerid'=>'88888888', //财付通商户身份标识
  13. * 'partnerkey'=>'', //财付通商户权限密钥Key
  14. * 'paysignkey'=>'' //商户签名密钥Key
  15. * );
  16. * $weObj = new Wechat($options);
  17. * $weObj->valid();
  18. * $type = $weObj->getRev()->getRevType();
  19. * switch($type) {
  20. * case Wechat::MSGTYPE_TEXT:
  21. * $weObj->text("hello, I'm wechat")->reply();
  22. * exit;
  23. * break;
  24. * case Wechat::MSGTYPE_EVENT:
  25. * ....
  26. * break;
  27. * case Wechat::MSGTYPE_IMAGE:
  28. * ...
  29. * break;
  30. * default:
  31. * $weObj->text("help info")->reply();
  32. * }
  33. *
  34. * //获取菜单操作:
  35. * $menu = $weObj->getMenu();
  36. * //设置菜单
  37. * $newmenu = array(
  38. * "button"=>
  39. * array(
  40. * array('type'=>'click','name'=>'最新消息','key'=>'MENU_KEY_NEWS'),
  41. * array('type'=>'view','name'=>'我要搜索','url'=>'http://www.baidu.com'),
  42. * )
  43. * );
  44. * $result = $weObj->createMenu($newmenu);
  45. */
  46. class Wechat
  47. {
  48. const MSGTYPE_TEXT = 'text';
  49. const MSGTYPE_IMAGE = 'image';
  50. const MSGTYPE_LOCATION = 'location';
  51. const MSGTYPE_LINK = 'link';
  52. const MSGTYPE_EVENT = 'event';
  53. const MSGTYPE_MUSIC = 'music';
  54. const MSGTYPE_NEWS = 'news';
  55. const MSGTYPE_VOICE = 'voice';
  56. const MSGTYPE_VIDEO = 'video';
  57. const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
  58. const AUTH_URL = '/token?grant_type=client_credential&';
  59. const MENU_CREATE_URL = '/menu/create?';
  60. const MENU_GET_URL = '/menu/get?';
  61. const MENU_DELETE_URL = '/menu/delete?';
  62. const MEDIA_GET_URL = '/media/get?';
  63. const QRCODE_CREATE_URL='/qrcode/create?';
  64. const QR_SCENE = 0;
  65. const QR_LIMIT_SCENE = 1;
  66. const QRCODE_IMG_URL='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
  67. const SHORT_URL='/shorturl?';
  68. const USER_GET_URL='/user/get?';
  69. const USER_INFO_URL='/user/info?';
  70. const USER_UPDATEREMARK_URL='/user/info/updateremark?';
  71. const GROUP_GET_URL='/groups/get?';
  72. const USER_GROUP_URL='/groups/getid?';
  73. const GROUP_CREATE_URL='/groups/create?';
  74. const GROUP_UPDATE_URL='/groups/update?';
  75. const GROUP_MEMBER_UPDATE_URL='/groups/members/update?';
  76. const CUSTOM_SEND_URL='/message/custom/send?';
  77. const MEDIA_UPLOADNEWS_URL = '/media/uploadnews?';
  78. const MASS_SEND_URL = '/message/mass/send?';
  79. const TEMPLATE_SEND_URL = '/message/template/send?';
  80. const MASS_SEND_GROUP_URL = '/message/mass/sendall?';
  81. const MASS_DELETE_URL = '/message/mass/delete?';
  82. const UPLOAD_MEDIA_URL = 'http://file.api.weixin.qq.com/cgi-bin';
  83. const MEDIA_UPLOAD = '/media/upload?';
  84. const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
  85. const OAUTH_AUTHORIZE_URL = '/authorize?';
  86. const OAUTH_TOKEN_PREFIX = 'https://api.weixin.qq.com/sns/oauth2';
  87. const OAUTH_TOKEN_URL = '/access_token?';
  88. const OAUTH_REFRESH_URL = '/refresh_token?';
  89. const OAUTH_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo?';
  90. const OAUTH_AUTH_URL = 'https://api.weixin.qq.com/sns/auth?';
  91. const PAY_DELIVERNOTIFY = 'https://api.weixin.qq.com/pay/delivernotify?';
  92. const PAY_ORDERQUERY = 'https://api.weixin.qq.com/pay/orderquery?';
  93. const CUSTOM_SERVICE_GET_RECORD = '/customservice/getrecord?';
  94. const CUSTOM_SERVICE_GET_KFLIST = '/customservice/getkflist?';
  95. const CUSTOM_SERVICE_GET_ONLINEKFLIST = '/customservice/getkflist?';
  96. private $token;
  97. private $appid;
  98. private $appsecret;
  99. private $access_token;
  100. private $user_token;
  101. private $partnerid;
  102. private $partnerkey;
  103. private $paysignkey;
  104. private $_msg;
  105. private $_funcflag = false;
  106. private $_receive;
  107. private $_text_filter = true;
  108. public $debug = false;
  109. public $errCode = 40001;
  110. public $errMsg = "no access";
  111. private $_logcallback;
  112. public function __construct($options)
  113. {
  114. $this->token = isset($options['token'])?$options['token']:'';
  115. $this->appid = isset($options['appid'])?$options['appid']:'';
  116. $this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
  117. $this->partnerid = isset($options['partnerid'])?$options['partnerid']:'';
  118. $this->partnerkey = isset($options['partnerkey'])?$options['partnerkey']:'';
  119. $this->paysignkey = isset($options['paysignkey'])?$options['paysignkey']:'';
  120. $this->debug = isset($options['debug'])?$options['debug']:false;
  121. $this->_logcallback = isset($options['logcallback'])?$options['logcallback']:false;
  122. }
  123. /**
  124. * For weixin server validation
  125. */
  126. private function checkSignature()
  127. {
  128. $signature = isset($_GET["signature"])?$_GET["signature"]:'';
  129. $timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:'';
  130. $nonce = isset($_GET["nonce"])?$_GET["nonce"]:'';
  131. $token = $this->token;
  132. $tmpArr = array($token, $timestamp, $nonce);
  133. sort($tmpArr, SORT_STRING);
  134. $tmpStr = implode( $tmpArr );
  135. $tmpStr = sha1( $tmpStr );
  136. if( $tmpStr == $signature ){
  137. return true;
  138. }else{
  139. return false;
  140. }
  141. }
  142. /**
  143. * For weixin server validation
  144. * @param bool $return 是否返回
  145. */
  146. public function valid($return=false)
  147. {
  148. $echoStr = isset($_GET["echostr"]) ? $_GET["echostr"]: '';
  149. if ($return) {
  150. if ($echoStr) {
  151. if ($this->checkSignature())
  152. return $echoStr;
  153. else
  154. return false;
  155. } else
  156. return $this->checkSignature();
  157. } else {
  158. if ($echoStr) {
  159. if ($this->checkSignature())
  160. die($echoStr);
  161. else
  162. die('no access');
  163. } else {
  164. if ($this->checkSignature())
  165. return true;
  166. else
  167. die('no access');
  168. }
  169. }
  170. return false;
  171. }
  172. /**
  173. * 设置发送消息
  174. * @param array $msg 消息数组
  175. * @param bool $append 是否在原消息数组追加
  176. */
  177. public function Message($msg = '',$append = false){
  178. if (is_null($msg)) {
  179. $this->_msg =array();
  180. }elseif (is_array($msg)) {
  181. if ($append)
  182. $this->_msg = array_merge($this->_msg,$msg);
  183. else
  184. $this->_msg = $msg;
  185. return $this->_msg;
  186. } else {
  187. return $this->_msg;
  188. }
  189. }
  190. public function setFuncFlag($flag) {
  191. $this->_funcflag = $flag;
  192. return $this;
  193. }
  194. private function log($log){
  195. if ($this->debug && function_exists($this->_logcallback)) {
  196. if (is_array($log)) $log = print_r($log,true);
  197. return call_user_func($this->_logcallback,$log);
  198. }
  199. }
  200. /**
  201. * 获取微信服务器发来的信息
  202. */
  203. public function getRev()
  204. {
  205. if ($this->_receive) return $this;
  206. $postStr = file_get_contents("php://input");
  207. $this->log($postStr);
  208. if (!empty($postStr)) {
  209. $this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  210. }
  211. return $this;
  212. }
  213. /**
  214. * 获取微信服务器发来的信息
  215. */
  216. public function getRevData()
  217. {
  218. return $this->_receive;
  219. }
  220. /**
  221. * 获取消息发送者
  222. */
  223. public function getRevFrom() {
  224. if (isset($this->_receive['FromUserName']))
  225. return $this->_receive['FromUserName'];
  226. else
  227. return false;
  228. }
  229. /**
  230. * 获取消息接受者
  231. */
  232. public function getRevTo() {
  233. if (isset($this->_receive['ToUserName']))
  234. return $this->_receive['ToUserName'];
  235. else
  236. return false;
  237. }
  238. /**
  239. * 获取接收消息的类型
  240. */
  241. public function getRevType() {
  242. if (isset($this->_receive['MsgType']))
  243. return $this->_receive['MsgType'];
  244. else
  245. return false;
  246. }
  247. /**
  248. * 获取消息ID
  249. */
  250. public function getRevID() {
  251. if (isset($this->_receive['MsgId']))
  252. return $this->_receive['MsgId'];
  253. else
  254. return false;
  255. }
  256. /**
  257. * 获取消息发送时间
  258. */
  259. public function getRevCtime() {
  260. if (isset($this->_receive['CreateTime']))
  261. return $this->_receive['CreateTime'];
  262. else
  263. return false;
  264. }
  265. /**
  266. * 获取接收消息内容正文
  267. */
  268. public function getRevContent(){
  269. if (isset($this->_receive['Content']))
  270. return $this->_receive['Content'];
  271. else if (isset($this->_receive['Recognition'])) //获取语音识别文字内容,需申请开通
  272. return $this->_receive['Recognition'];
  273. else
  274. return false;
  275. }
  276. /**
  277. * 获取接收消息图片
  278. */
  279. public function getRevPic(){
  280. if (isset($this->_receive['PicUrl']))
  281. return array(
  282. 'mediaid'=>$this->_receive['MediaId'],
  283. 'picurl'=>(string)$this->_receive['PicUrl'], //防止picurl为空导致解析出错
  284. );
  285. else
  286. return false;
  287. }
  288. /**
  289. * 获取接收消息链接
  290. */
  291. public function getRevLink(){
  292. if (isset($this->_receive['Url'])){
  293. return array(
  294. 'url'=>$this->_receive['Url'],
  295. 'title'=>$this->_receive['Title'],
  296. 'description'=>$this->_receive['Description']
  297. );
  298. } else
  299. return false;
  300. }
  301. /**
  302. * 获取接收地理位置
  303. */
  304. public function getRevGeo(){
  305. if (isset($this->_receive['Location_X'])){
  306. return array(
  307. 'x'=>$this->_receive['Location_X'],
  308. 'y'=>$this->_receive['Location_Y'],
  309. 'scale'=>$this->_receive['Scale'],
  310. 'label'=>$this->_receive['Label']
  311. );
  312. } else
  313. return false;
  314. }
  315. /**
  316. * 获取上报地理位置事件
  317. */
  318. public function getRevEventGeo(){
  319. if (isset($this->_receive['Latitude'])){
  320. return array(
  321. 'x'=>$this->_receive['Latitude'],
  322. 'y'=>$this->_receive['Longitude'],
  323. 'precision'=>$this->_receive['Precision'],
  324. );
  325. } else
  326. return false;
  327. }
  328. /**
  329. * 获取接收事件推送
  330. */
  331. public function getRevEvent(){
  332. if (isset($this->_receive['Event'])){
  333. $array['event'] = $this->_receive['Event'];
  334. }
  335. if (isset($this->_receive['EventKey'])){
  336. $array['key'] = $this->_receive['EventKey'];
  337. }
  338. if (isset($array) && count($array) > 0) {
  339. return $array;
  340. } else {
  341. return false;
  342. }
  343. }
  344. /**
  345. * 获取自定义菜单的扫码推事件信息
  346. *
  347. * 事件类型为以下两种时则调用此方法有效
  348. * Event 事件类型,scancode_push
  349. * Event 事件类型,scancode_waitmsg
  350. *
  351. * @return: array | false
  352. * array (
  353. * 'ScanType'=>'qrcode',
  354. * 'ScanResult'=>'123123'
  355. * )
  356. */
  357. public function getRevScanInfo(){
  358. if (isset($this->_receive['ScanCodeInfo'])){
  359. if (!is_array($this->_receive['SendPicsInfo'])) {
  360. $array=(array)$this->_receive['ScanCodeInfo'];
  361. $this->_receive['ScanCodeInfo']=$array;
  362. }else {
  363. $array=$this->_receive['ScanCodeInfo'];
  364. }
  365. }
  366. if (isset($array) && count($array) > 0) {
  367. return $array;
  368. } else {
  369. return false;
  370. }
  371. }
  372. /**
  373. * 获取自定义菜单的图片发送事件信息
  374. *
  375. * 事件类型为以下三种时则调用此方法有效
  376. * Event 事件类型,pic_sysphoto 弹出系统拍照发图的事件推送
  377. * Event 事件类型,pic_photo_or_album 弹出拍照或者相册发图的事件推送
  378. * Event 事件类型,pic_weixin 弹出微信相册发图器的事件推送
  379. *
  380. * @return: array | false
  381. * array (
  382. * 'Count' => '2',
  383. * 'PicList' =>
  384. * array (
  385. * 'item' =>
  386. * array (
  387. * 0 =>
  388. * array (
  389. * 'PicMd5Sum' => 'aaae42617cf2a14342d96005af53624c',
  390. * ),
  391. * 1 =>
  392. * array (
  393. * 'PicMd5Sum' => '149bd39e296860a2adc2f1bb81616ff8',
  394. * ),
  395. * ),
  396. * ),
  397. * )
  398. *
  399. */
  400. public function getRevSendPicsInfo(){
  401. if (isset($this->_receive['SendPicsInfo'])){
  402. if (!is_array($this->_receive['SendPicsInfo'])) {
  403. $array=(array)$this->_receive['SendPicsInfo'];
  404. if (isset($array['PicList'])){
  405. $array['PicList']=(array)$array['PicList'];
  406. $item=$array['PicList']['item'];
  407. $array['PicList']['item']=array();
  408. foreach ( $item as $key => $value ){
  409. $array['PicList']['item'][$key]=(array)$value;
  410. }
  411. }
  412. $this->_receive['SendPicsInfo']=$array;
  413. } else {
  414. $array=$this->_receive['SendPicsInfo'];
  415. }
  416. }
  417. if (isset($array) && count($array) > 0) {
  418. return $array;
  419. } else {
  420. return false;
  421. }
  422. }
  423. /**
  424. * 获取自定义菜单的地理位置选择器事件推送
  425. *
  426. * 事件类型为以下时则可以调用此方法有效
  427. * Event 事件类型,location_select 弹出系统拍照发图的事件推送
  428. *
  429. * @return: array | false
  430. * array (
  431. * 'Location_X' => '33.731655000061',
  432. * 'Location_Y' => '113.29955200008047',
  433. * 'Scale' => '16',
  434. * 'Label' => '某某市某某区某某路',
  435. * 'Poiname' => '',
  436. * )
  437. *
  438. */
  439. public function getRevSendGeoInfo(){
  440. if (isset($this->_receive['SendLocationInfo'])){
  441. if (!is_array($this->_receive['SendLocationInfo'])) {
  442. $array=(array)$this->_receive['SendLocationInfo'];
  443. if (empty($array['Poiname'])) {
  444. $array['Poiname']="";
  445. }
  446. if (empty($array['Label'])) {
  447. $array['Label']="";
  448. }
  449. $this->_receive['SendLocationInfo']=$array;
  450. } else {
  451. $array=$this->_receive['SendLocationInfo'];
  452. }
  453. }
  454. if (isset($array) && count($array) > 0) {
  455. return $array;
  456. } else {
  457. return false;
  458. }
  459. }
  460. /**
  461. * 获取接收语音推送
  462. */
  463. public function getRevVoice(){
  464. if (isset($this->_receive['MediaId'])){
  465. return array(
  466. 'mediaid'=>$this->_receive['MediaId'],
  467. 'format'=>$this->_receive['Format'],
  468. );
  469. } else
  470. return false;
  471. }
  472. /**
  473. * 获取接收视频推送
  474. */
  475. public function getRevVideo(){
  476. if (isset($this->_receive['MediaId'])){
  477. return array(
  478. 'mediaid'=>$this->_receive['MediaId'],
  479. 'thumbmediaid'=>$this->_receive['ThumbMediaId']
  480. );
  481. } else
  482. return false;
  483. }
  484. /**
  485. * 获取接收TICKET
  486. */
  487. public function getRevTicket(){
  488. if (isset($this->_receive['Ticket'])){
  489. return $this->_receive['Ticket'];
  490. } else
  491. return false;
  492. }
  493. /**
  494. * 获取二维码的场景值
  495. */
  496. public function getRevSceneId (){
  497. if (isset($this->_receive['EventKey'])){
  498. return str_replace('qrscene_','',$this->_receive['EventKey']);
  499. } else{
  500. return false;
  501. }
  502. }
  503. /**
  504. * 获取模板消息ID
  505. * 经过验证,这个和普通的消息MsgId不一样
  506. */
  507. public function getRevTplMsgID(){
  508. if (isset($this->_receive['MsgID'])){
  509. return $this->_receive['MsgID'];
  510. } else
  511. return false;
  512. }
  513. /**
  514. * 获取模板消息发送状态
  515. */
  516. public function getRevStatus(){
  517. if (isset($this->_receive['Status'])){
  518. return $this->_receive['Status'];
  519. } else
  520. return false;
  521. }
  522. public static function xmlSafeStr($str)
  523. {
  524. return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
  525. }
  526. /**
  527. * 数据XML编码
  528. * @param mixed $data 数据
  529. * @return string
  530. */
  531. public static function data_to_xml($data) {
  532. $xml = '';
  533. foreach ($data as $key => $val) {
  534. is_numeric($key) && $key = "item id=\"$key\"";
  535. $xml .= "<$key>";
  536. $xml .= ( is_array($val) || is_object($val)) ? self::data_to_xml($val) : self::xmlSafeStr($val);
  537. list($key, ) = explode(' ', $key);
  538. $xml .= "</$key>";
  539. }
  540. return $xml;
  541. }
  542. /**
  543. * XML编码
  544. * @param mixed $data 数据
  545. * @param string $root 根节点名
  546. * @param string $item 数字索引的子节点名
  547. * @param string $attr 根节点属性
  548. * @param string $id 数字索引子节点key转换的属性名
  549. * @param string $encoding 数据编码
  550. * @return string
  551. */
  552. public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
  553. if(is_array($attr)){
  554. $_attr = array();
  555. foreach ($attr as $key => $value) {
  556. $_attr[] = "{$key}=\"{$value}\"";
  557. }
  558. $attr = implode(' ', $_attr);
  559. }
  560. $attr = trim($attr);
  561. $attr = empty($attr) ? '' : " {$attr}";
  562. $xml = "<{$root}{$attr}>";
  563. $xml .= self::data_to_xml($data, $item, $id);
  564. $xml .= "</{$root}>";
  565. return $xml;
  566. }
  567. /**
  568. * 过滤文字回复\r\n换行符
  569. * @param string $text
  570. * @return string|mixed
  571. */
  572. private function _auto_text_filter($text) {
  573. if (!$this->_text_filter) return $text;
  574. return str_replace("\r\n", "\n", $text);
  575. }
  576. /**
  577. * 设置回复消息
  578. * Examle: $obj->text('hello')->reply();
  579. * @param string $text
  580. */
  581. public function text($text='')
  582. {
  583. $FuncFlag = $this->_funcflag ? 1 : 0;
  584. $msg = array(
  585. 'ToUserName' => $this->getRevFrom(),
  586. 'FromUserName'=>$this->getRevTo(),
  587. 'MsgType'=>self::MSGTYPE_TEXT,
  588. 'Content'=>$this->_auto_text_filter($text),
  589. 'CreateTime'=>time(),
  590. 'FuncFlag'=>$FuncFlag
  591. );
  592. $this->Message($msg);
  593. return $this;
  594. }
  595. /**
  596. * 设置回复消息
  597. * Examle: $obj->image('media_id')->reply();
  598. * @param string $mediaid
  599. */
  600. public function image($mediaid='')
  601. {
  602. $FuncFlag = $this->_funcflag ? 1 : 0;
  603. $msg = array(
  604. 'ToUserName' => $this->getRevFrom(),
  605. 'FromUserName'=>$this->getRevTo(),
  606. 'MsgType'=>self::MSGTYPE_IMAGE,
  607. 'Image'=>array('MediaId'=>$mediaid),
  608. 'CreateTime'=>time(),
  609. 'FuncFlag'=>$FuncFlag
  610. );
  611. $this->Message($msg);
  612. return $this;
  613. }
  614. /**
  615. * 设置回复消息
  616. * Examle: $obj->voice('media_id')->reply();
  617. * @param string $mediaid
  618. */
  619. public function voice($mediaid='')
  620. {
  621. $FuncFlag = $this->_funcflag ? 1 : 0;
  622. $msg = array(
  623. 'ToUserName' => $this->getRevFrom(),
  624. 'FromUserName'=>$this->getRevTo(),
  625. 'MsgType'=>self::MSGTYPE_IMAGE,
  626. 'Voice'=>array('MediaId'=>$mediaid),
  627. 'CreateTime'=>time(),
  628. 'FuncFlag'=>$FuncFlag
  629. );
  630. $this->Message($msg);
  631. return $this;
  632. }
  633. /**
  634. * 设置回复消息
  635. * Examle: $obj->video('media_id','title','description')->reply();
  636. * @param string $mediaid
  637. */
  638. public function video($mediaid='',$title,$description)
  639. {
  640. $FuncFlag = $this->_funcflag ? 1 : 0;
  641. $msg = array(
  642. 'ToUserName' => $this->getRevFrom(),
  643. 'FromUserName'=>$this->getRevTo(),
  644. 'MsgType'=>self::MSGTYPE_IMAGE,
  645. 'Video'=>array(
  646. 'MediaId'=>$mediaid,
  647. 'Title'=>$mediaid,
  648. 'Description'=>$mediaid,
  649. ),
  650. 'CreateTime'=>time(),
  651. 'FuncFlag'=>$FuncFlag
  652. );
  653. $this->Message($msg);
  654. return $this;
  655. }
  656. /**
  657. * 设置回复音乐
  658. * @param string $title
  659. * @param string $desc
  660. * @param string $musicurl
  661. * @param string $hgmusicurl
  662. */
  663. public function music($title,$desc,$musicurl,$hgmusicurl='') {
  664. $FuncFlag = $this->_funcflag ? 1 : 0;
  665. $msg = array(
  666. 'ToUserName' => $this->getRevFrom(),
  667. 'FromUserName'=>$this->getRevTo(),
  668. 'CreateTime'=>time(),
  669. 'MsgType'=>self::MSGTYPE_MUSIC,
  670. 'Music'=>array(
  671. 'Title'=>$title,
  672. 'Description'=>$desc,
  673. 'MusicUrl'=>$musicurl,
  674. 'HQMusicUrl'=>$hgmusicurl
  675. ),
  676. 'FuncFlag'=>$FuncFlag
  677. );
  678. $this->Message($msg);
  679. return $this;
  680. }
  681. /**
  682. * 设置回复图文
  683. * @param array $newsData
  684. * 数组结构:
  685. * array(
  686. * "0"=>array(
  687. * 'Title'=>'msg title',
  688. * 'Description'=>'summary text',
  689. * 'PicUrl'=>'http://www.domain.com/1.jpg',
  690. * 'Url'=>'http://www.domain.com/1.html'
  691. * ),
  692. * "1"=>....
  693. * )
  694. */
  695. public function news($newsData=array())
  696. {
  697. $FuncFlag = $this->_funcflag ? 1 : 0;
  698. $count = count($newsData);
  699. $msg = array(
  700. 'ToUserName' => $this->getRevFrom(),
  701. 'FromUserName'=>$this->getRevTo(),
  702. 'MsgType'=>self::MSGTYPE_NEWS,
  703. 'CreateTime'=>time(),
  704. 'ArticleCount'=>$count,
  705. 'Articles'=>$newsData,
  706. 'FuncFlag'=>$FuncFlag
  707. );
  708. $this->Message($msg);
  709. return $this;
  710. }
  711. /**
  712. *
  713. * 回复微信服务器, 此函数支持链式操作
  714. * Example: $this->text('msg tips')->reply();
  715. * @param string $msg 要发送的信息, 默认取$this->_msg
  716. * @param bool $return 是否返回信息而不抛出到浏览器 默认:否
  717. */
  718. public function reply($msg=array(),$return = false)
  719. {
  720. if (empty($msg))
  721. $msg = $this->_msg;
  722. $xmldata= $this->xml_encode($msg);
  723. $this->log($xmldata);
  724. if ($return)
  725. return $xmldata;
  726. else
  727. echo $xmldata;
  728. }
  729. /**
  730. * GET 请求
  731. * @param string $url
  732. */
  733. private function http_get($url){
  734. $oCurl = curl_init();
  735. if(stripos($url,"https://")!==FALSE){
  736. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  737. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  738. }
  739. curl_setopt($oCurl, CURLOPT_URL, $url);
  740. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  741. $sContent = curl_exec($oCurl);
  742. $aStatus = curl_getinfo($oCurl);
  743. curl_close($oCurl);
  744. if(intval($aStatus["http_code"])==200){
  745. return $sContent;
  746. }else{
  747. return false;
  748. }
  749. }
  750. /**
  751. * POST 请求
  752. * @param string $url
  753. * @param array $param
  754. * @return string content
  755. */
  756. private function http_post($url,$param){
  757. $oCurl = curl_init();
  758. if(stripos($url,"https://")!==FALSE){
  759. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  760. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
  761. }
  762. if (is_string($param)) {
  763. $strPOST = $param;
  764. } else {
  765. $aPOST = array();
  766. foreach($param as $key=>$val){
  767. $aPOST[] = $key."=".urlencode($val);
  768. }
  769. $strPOST = join("&", $aPOST);
  770. }
  771. curl_setopt($oCurl, CURLOPT_URL, $url);
  772. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  773. curl_setopt($oCurl, CURLOPT_POST,true);
  774. curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
  775. $sContent = curl_exec($oCurl);
  776. $aStatus = curl_getinfo($oCurl);
  777. curl_close($oCurl);
  778. if(intval($aStatus["http_code"])==200){
  779. return $sContent;
  780. }else{
  781. return false;
  782. }
  783. }
  784. /**
  785. * 通用auth验证方法,暂时仅用于菜单更新操作
  786. * @param string $appid
  787. * @param string $appsecret
  788. */
  789. public function checkAuth($appid='',$appsecret=''){
  790. if (!$appid || !$appsecret) {
  791. $appid = $this->appid;
  792. $appsecret = $this->appsecret;
  793. }
  794. //TODO: get the cache access_token
  795. $result = $this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret);
  796. if ($result)
  797. {
  798. $json = json_decode($result,true);
  799. if (!$json || isset($json['errcode'])) {
  800. $this->errCode = $json['errcode'];
  801. $this->errMsg = $json['errmsg'];
  802. return false;
  803. }
  804. $this->access_token = $json['access_token'];
  805. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  806. //TODO: cache access_token
  807. return $this->access_token;
  808. }
  809. return false;
  810. }
  811. /**
  812. * 删除验证数据
  813. * @param string $appid
  814. */
  815. public function resetAuth($appid=''){
  816. if (!$appid) $appid = $this->appid;
  817. $this->access_token = '';
  818. //TODO: remove cache
  819. return true;
  820. }
  821. /**
  822. * 微信api不支持中文转义的json结构
  823. * @param array $arr
  824. */
  825. static function json_encode($arr) {
  826. $parts = array ();
  827. $is_list = false;
  828. //Find out if the given array is a numerical array
  829. $keys = array_keys ( $arr );
  830. $max_length = count ( $arr ) - 1;
  831. if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
  832. $is_list = true;
  833. for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
  834. if ($i != $keys [$i]) { //A key fails at position check.
  835. $is_list = false; //It is an associative array.
  836. break;
  837. }
  838. }
  839. }
  840. foreach ( $arr as $key => $value ) {
  841. if (is_array ( $value )) { //Custom handling for arrays
  842. if ($is_list)
  843. $parts [] = self::json_encode ( $value ); /* :RECURSION: */
  844. else
  845. $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
  846. } else {
  847. $str = '';
  848. if (! $is_list)
  849. $str = '"' . $key . '":';
  850. //Custom handling for multiple data types
  851. if (is_numeric ( $value ) && $value<2000000000)
  852. $str .= $value; //Numbers
  853. elseif ($value === false)
  854. $str .= 'false'; //The booleans
  855. elseif ($value === true)
  856. $str .= 'true';
  857. else
  858. $str .= '"' . addslashes ( $value ) . '"'; //All other things
  859. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  860. $parts [] = $str;
  861. }
  862. }
  863. $json = implode ( ',', $parts );
  864. if ($is_list)
  865. return '[' . $json . ']'; //Return numerical JSON
  866. return '{' . $json . '}'; //Return associative JSON
  867. }
  868. /**
  869. * 创建菜单
  870. * @param array $data 菜单数组数据
  871. * example:
  872. * array (
  873. * 'button' => array (
  874. * 0 => array (
  875. * 'name' => '扫码',
  876. * 'sub_button' => array (
  877. * 0 => array (
  878. * 'type' => 'scancode_waitmsg',
  879. * 'name' => '扫码带提示',
  880. * 'key' => 'rselfmenu_0_0',
  881. * 'sub_button' => ''
  882. * ),
  883. * 1 => array (
  884. * 'type' => 'scancode_push',
  885. * 'name' => '扫码推事件',
  886. * 'key' => 'rselfmenu_0_1',
  887. * 'sub_button' => ''
  888. * ),
  889. * ),
  890. * ),
  891. * 1 => array (
  892. * 'name' => '发图',
  893. * 'sub_button' => array (
  894. * 0 => array (
  895. * 'type' => 'pic_sysphoto',
  896. * 'name' => '系统拍照发图',
  897. * 'key' => 'rselfmenu_1_0',
  898. * 'sub_button' => ''
  899. * ),
  900. * 1 => array (
  901. * 'type' => 'pic_photo_or_album',
  902. * 'name' => '拍照或者相册发图',
  903. * 'key' => 'rselfmenu_1_1',
  904. * 'sub_button' => ''
  905. * )
  906. * ),
  907. * ),
  908. * 2 => array (
  909. * 'type' => 'location_select',
  910. * 'name' => '发送位置',
  911. * 'key' => 'rselfmenu_2_0',
  912. * 'sub_button' => ''
  913. * ),
  914. * ),
  915. * )
  916. * type可以选择为以下几种,其中5-8除了收到菜单事件以外,还会单独收到对应类型的信息。
  917. * 1、click:点击推事件
  918. * 2、view:跳转URL
  919. * 3、scancode_push:扫码推事件
  920. * 4、scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
  921. * 5、pic_sysphoto:弹出系统拍照发图
  922. * 6、pic_photo_or_album:弹出拍照或者相册发图
  923. * 7、pic_weixin:弹出微信相册发图器
  924. * 8、location_select:弹出地理位置选择器
  925. */
  926. public function createMenu($data){
  927. if (!$this->access_token && !$this->checkAuth()) return false;
  928. $result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  929. if ($result)
  930. {
  931. $json = json_decode($result,true);
  932. if (!$json || !empty($json['errcode'])) {
  933. $this->errCode = $json['errcode'];
  934. $this->errMsg = $json['errmsg'];
  935. return false;
  936. }
  937. return true;
  938. }
  939. return false;
  940. }
  941. /**
  942. * 获取菜单
  943. * @return array('menu'=>array(....s))
  944. */
  945. public function getMenu(){
  946. if (!$this->access_token && !$this->checkAuth()) return false;
  947. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
  948. if ($result)
  949. {
  950. $json = json_decode($result,true);
  951. if (!$json || isset($json['errcode'])) {
  952. $this->errCode = $json['errcode'];
  953. $this->errMsg = $json['errmsg'];
  954. return false;
  955. }
  956. return $json;
  957. }
  958. return false;
  959. }
  960. /**
  961. * 删除菜单
  962. * @return boolean
  963. */
  964. public function deleteMenu(){
  965. if (!$this->access_token && !$this->checkAuth()) return false;
  966. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
  967. if ($result)
  968. {
  969. $json = json_decode($result,true);
  970. if (!$json || !empty($json['errcode'])) {
  971. $this->errCode = $json['errcode'];
  972. $this->errMsg = $json['errmsg'];
  973. return false;
  974. }
  975. return true;
  976. }
  977. return false;
  978. }
  979. /**
  980. * 上传多媒体文件
  981. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  982. * @param array $data {"media":'@Path\filename.jpg'}
  983. * @param type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
  984. * @return boolean|array
  985. */
  986. public function uploadMedia($data, $type){
  987. if (!$this->access_token && !$this->checkAuth()) return false;
  988. $result = $this->http_post(self::UPLOAD_MEDIA_URL.self::MEDIA_UPLOAD.'access_token='.$this->access_token.'&type='.$type,$data);
  989. if ($result)
  990. {
  991. $json = json_decode($result,true);
  992. if (!$json || !empty($json['errcode'])) {
  993. $this->errCode = $json['errcode'];
  994. $this->errMsg = $json['errmsg'];
  995. return false;
  996. }
  997. return $json;
  998. }
  999. return false;
  1000. }
  1001. /**
  1002. * 根据媒体文件ID获取媒体文件
  1003. * @param string $media_id 媒体文件id
  1004. * @return raw data
  1005. */
  1006. public function getMedia($media_id){
  1007. if (!$this->access_token && !$this->checkAuth()) return false;
  1008. $result = $this->http_get(self::UPLOAD_MEDIA_URL.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
  1009. if ($result)
  1010. {
  1011. $json = json_decode($result,true);
  1012. if (isset($json['errcode'])) {
  1013. $this->errCode = $json['errcode'];
  1014. $this->errMsg = $json['errmsg'];
  1015. return false;
  1016. }
  1017. return $json;
  1018. }
  1019. return false;
  1020. }
  1021. /**
  1022. * 上传图文消息素材
  1023. * @param array $data 消息结构{"articles":[{...}]}
  1024. * @return boolean|array
  1025. */
  1026. public function uploadArticles($data){
  1027. if (!$this->access_token && !$this->checkAuth()) return false;
  1028. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADNEWS_URL.'access_token='.$this->access_token,self::json_encode($data));
  1029. if ($result)
  1030. {
  1031. $json = json_decode($result,true);
  1032. if (!$json || !empty($json['errcode'])) {
  1033. $this->errCode = $json['errcode'];
  1034. $this->errMsg = $json['errmsg'];
  1035. return false;
  1036. }
  1037. return $json;
  1038. }
  1039. return false;
  1040. }
  1041. /**
  1042. * 高级群发消息, 根据OpenID列表群发图文消息
  1043. * @param array $data 消息结构{ "touser":[ "OPENID1", "OPENID2" ], "mpnews":{ "media_id":"123dsdajkasd231jhksad" }, "msgtype":"mpnews" }
  1044. * @return boolean|array
  1045. */
  1046. public function sendMassMessage($data){
  1047. if (!$this->access_token && !$this->checkAuth()) return false;
  1048. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1049. if ($result)
  1050. {
  1051. $json = json_decode($result,true);
  1052. if (!$json || !empty($json['errcode'])) {
  1053. $this->errCode = $json['errcode'];
  1054. $this->errMsg = $json['errmsg'];
  1055. return false;
  1056. }
  1057. return $json;
  1058. }
  1059. return false;
  1060. }
  1061. /**
  1062. * 高级群发消息, 根据群组id群发图文消息
  1063. * @param array $data 消息结构{ "filter":[ "group_id": "2" ], "mpnews":{ "media_id":"123dsdajkasd231jhksad" }, "msgtype":"mpnews" }
  1064. * @return boolean|array
  1065. */
  1066. public function sendGroupMassMessage($data){
  1067. if (!$this->access_token && !$this->checkAuth()) return false;
  1068. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1069. if ($result)
  1070. {
  1071. $json = json_decode($result,true);
  1072. if (!$json || !empty($json['errcode'])) {
  1073. $this->errCode = $json['errcode'];
  1074. $this->errMsg = $json['errmsg'];
  1075. return false;
  1076. }
  1077. return $json;
  1078. }
  1079. return false;
  1080. }
  1081. /**
  1082. * 高级群发消息, 删除群发图文消息
  1083. * @param int $msg_id 消息id
  1084. * @return boolean|array
  1085. */
  1086. public function deleteMassMessage($msg_id){
  1087. if (!$this->access_token && !$this->checkAuth()) return false;
  1088. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_DELETE_URL.'access_token='.$this->access_token,self::json_encode(array('msg_id'=>$msg_id)));
  1089. if ($result)
  1090. {
  1091. $json = json_decode($result,true);
  1092. if (!$json || !empty($json['errcode'])) {
  1093. $this->errCode = $json['errcode'];
  1094. $this->errMsg = $json['errmsg'];
  1095. return false;
  1096. }
  1097. return true;
  1098. }
  1099. return false;
  1100. }
  1101. /**
  1102. * 创建二维码ticket
  1103. * @param int $scene_id 自定义追踪id
  1104. * @param int $type 0:临时二维码;1:永久二维码(此时expire参数无效)
  1105. * @param int $expire 临时二维码有效期,最大为1800秒
  1106. * @return array('ticket'=>'qrcode字串','expire_seconds'=>1800,'url'=>'二维码图片解析后的地址')
  1107. */
  1108. public function getQRCode($scene_id,$type=0,$expire=1800){
  1109. if (!$this->access_token && !$this->checkAuth()) return false;
  1110. $data = array(
  1111. 'action_name'=>$type?"QR_LIMIT_SCENE":"QR_SCENE",
  1112. 'expire_seconds'=>$expire,
  1113. 'action_info'=>array('scene'=>array('scene_id'=>$scene_id))
  1114. );
  1115. if ($type == 1) {
  1116. unset($data['expire_seconds']);
  1117. }
  1118. $result = $this->http_post(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1119. if ($result)
  1120. {
  1121. $json = json_decode($result,true);
  1122. if (!$json || !empty($json['errcode'])) {
  1123. $this->errCode = $json['errcode'];
  1124. $this->errMsg = $json['errmsg'];
  1125. return false;
  1126. }
  1127. return $json;
  1128. }
  1129. return false;
  1130. }
  1131. /**
  1132. * 获取二维码图片
  1133. * @param string $ticket 传入由getQRCode方法生成的ticket参数
  1134. * @return string url 返回http地址
  1135. */
  1136. public function getQRUrl($ticket) {
  1137. return self::QRCODE_IMG_URL.$ticket;
  1138. }
  1139. /**
  1140. * 长链接转短链接接口
  1141. * @param string $long_url 传入要转换的长url
  1142. * @return boolean|string url 成功则返回转换后的短url
  1143. */
  1144. public function getShortUrl($long_url){
  1145. if (!$this->access_token && !$this->checkAuth()) return false;
  1146. $data = array(
  1147. 'action'=>'long2short',
  1148. 'long_url'=>$long_url
  1149. );
  1150. $result = $this->http_post(self::API_URL_PREFIX.self::SHORT_URL.'access_token='.$this->access_token,self::json_encode($data));
  1151. if ($result)
  1152. {
  1153. $json = json_decode($result,true);
  1154. if (!$json || !empty($json['errcode'])) {
  1155. $this->errCode = $json['errcode'];
  1156. $this->errMsg = $json['errmsg'];
  1157. return false;
  1158. }
  1159. return $json['short_url'];
  1160. }
  1161. return false;
  1162. }
  1163. /**
  1164. * 批量获取关注用户列表
  1165. * @param unknown $next_openid
  1166. */
  1167. public function getUserList($next_openid=''){
  1168. if (!$this->access_token && !$this->checkAuth()) return false;
  1169. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
  1170. if ($result)
  1171. {
  1172. $json = json_decode($result,true);
  1173. if (isset($json['errcode'])) {
  1174. $this->errCode = $json['errcode'];
  1175. $this->errMsg = $json['errmsg'];
  1176. return false;
  1177. }
  1178. return $json;
  1179. }
  1180. return false;
  1181. }
  1182. /**
  1183. * 获取关注者详细信息
  1184. * @param string $openid
  1185. * @return array {subscribe,openid,nickname,sex,city,province,country,language,headimgurl,subscribe_time,[unionid]}
  1186. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  1187. */
  1188. public function getUserInfo($openid){
  1189. if (!$this->access_token && !$this->checkAuth()) return false;
  1190. $result = $this->http_get(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
  1191. if ($result)
  1192. {
  1193. $json = json_decode($result,true);
  1194. if (isset($json['errcode'])) {
  1195. $this->errCode = $json['errcode'];
  1196. $this->errMsg = $json['errmsg'];
  1197. return false;
  1198. }
  1199. return $json;
  1200. }
  1201. return false;
  1202. }
  1203. /**
  1204. * 设置用户备注名
  1205. * @param string $openid
  1206. * @param string $remark 备注名
  1207. * @return boolean|array
  1208. */
  1209. public function updateUserRemark($openid,$remark){
  1210. if (!$this->access_token && !$this->checkAuth()) return false;
  1211. $data = array(
  1212. 'openid'=>$openid,
  1213. 'remark'=>$remark
  1214. );
  1215. $result = $this->http_post(self::API_URL_PREFIX.self::USER_UPDATEREMARK_URL.'access_token='.$this->access_token,$data);
  1216. if ($result)
  1217. {
  1218. $json = json_decode($result,true);
  1219. if (!$json || !empty($json['errcode'])) {
  1220. $this->errCode = $json['errcode'];
  1221. $this->errMsg = $json['errmsg'];
  1222. return false;
  1223. }
  1224. return $json;
  1225. }
  1226. return false;
  1227. }
  1228. /**
  1229. * 获取用户分组列表
  1230. * @return boolean|array
  1231. */
  1232. public function getGroup(){
  1233. if (!$this->access_token && !$this->checkAuth()) return false;
  1234. $result = $this->http_get(self::API_URL_PREFIX.self::GROUP_GET_URL.'access_token='.$this->access_token);
  1235. if ($result)
  1236. {
  1237. $json = json_decode($result,true);
  1238. if (isset($json['errcode'])) {
  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 string $openid
  1250. * @return boolean|int 成功则返回用户分组id
  1251. */
  1252. public function getUserGroup($openid){
  1253. if (!$this->access_token && !$this->checkAuth()) return false;
  1254. $data = array(
  1255. 'openid'=>$openid
  1256. );
  1257. $result = $this->http_post(self::API_URL_PREFIX.self::USER_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1258. if ($result)
  1259. {
  1260. $json = json_decode($result,true);
  1261. if (!$json || !empty($json['errcode'])) {
  1262. $this->errCode = $json['errcode'];
  1263. $this->errMsg = $json['errmsg'];
  1264. return false;
  1265. } else
  1266. if (isset($json['groupid'])) return $json['groupid'];
  1267. }
  1268. return false;
  1269. }
  1270. /**
  1271. * 新增自定分组
  1272. * @param string $name 分组名称
  1273. * @return boolean|array
  1274. */
  1275. public function createGroup($name){
  1276. if (!$this->access_token && !$this->checkAuth()) return false;
  1277. $data = array(
  1278. 'group'=>array('name'=>$name)
  1279. );
  1280. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1281. if ($result)
  1282. {
  1283. $json = json_decode($result,true);
  1284. if (!$json || !empty($json['errcode'])) {
  1285. $this->errCode = $json['errcode'];
  1286. $this->errMsg = $json['errmsg'];
  1287. return false;
  1288. }
  1289. return $json;
  1290. }
  1291. return false;
  1292. }
  1293. /**
  1294. * 更改分组名称
  1295. * @param int $groupid 分组id
  1296. * @param string $name 分组名称
  1297. * @return boolean|array
  1298. */
  1299. public function updateGroup($groupid,$name){
  1300. if (!$this->access_token && !$this->checkAuth()) return false;
  1301. $data = array(
  1302. 'group'=>array('id'=>$groupid,'name'=>$name)
  1303. );
  1304. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1305. if ($result)
  1306. {
  1307. $json = json_decode($result,true);
  1308. if (!$json || !empty($json['errcode'])) {
  1309. $this->errCode = $json['errcode'];
  1310. $this->errMsg = $json['errmsg'];
  1311. return false;
  1312. }
  1313. return $json;
  1314. }
  1315. return false;
  1316. }
  1317. /**
  1318. * 移动用户分组
  1319. * @param int $groupid 分组id
  1320. * @param string $openid 用户openid
  1321. * @return boolean|array
  1322. */
  1323. public function updateGroupMembers($groupid,$openid){
  1324. if (!$this->access_token && !$this->checkAuth()) return false;
  1325. $data = array(
  1326. 'openid'=>$openid,
  1327. 'to_groupid'=>$groupid
  1328. );
  1329. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_UPDATE_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'])) {
  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 消息结构{"touser":"OPENID","msgtype":"news","news":{...}}
  1345. * @return boolean|array
  1346. */
  1347. public function sendCustomMessage($data){
  1348. if (!$this->access_token && !$this->checkAuth()) return false;
  1349. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1350. if ($result)
  1351. {
  1352. $json = json_decode($result,true);
  1353. if (!$json || !empty($json['errcode'])) {
  1354. $this->errCode = $json['errcode'];
  1355. $this->errMsg = $json['errmsg'];
  1356. return false;
  1357. }
  1358. return $json;
  1359. }
  1360. return false;
  1361. }
  1362. /**
  1363. * oauth 授权跳转接口
  1364. * @param string $callback 回调URI
  1365. * @return string
  1366. */
  1367. public function getOauthRedirect($callback,$state='',$scope='snsapi_userinfo'){
  1368. return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  1369. }
  1370. /**
  1371. * 通过code获取Access Token
  1372. * @return array {access_token,expires_in,refresh_token,openid,scope}
  1373. */
  1374. public function getOauthAccessToken(){
  1375. $code = isset($_GET['code'])?$_GET['code']:'';
  1376. if (!$code) return false;
  1377. $result = $this->http_get(self::OAUTH_TOKEN_PREFIX.self::OAUTH_TOKEN_URL.'appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code');
  1378. if ($result)
  1379. {
  1380. $json = json_decode($result,true);
  1381. if (!$json || !empty($json['errcode'])) {
  1382. $this->errCode = $json['errcode'];
  1383. $this->errMsg = $json['errmsg'];
  1384. return false;
  1385. }
  1386. $this->user_token = $json['access_token'];
  1387. return $json;
  1388. }
  1389. return false;
  1390. }
  1391. /**
  1392. * 刷新access token并续期
  1393. * @param string $refresh_token
  1394. * @return boolean|mixed
  1395. */
  1396. public function getOauthRefreshToken($refresh_token){
  1397. $result = $this->http_get(self::OAUTH_TOKEN_PREFIX.self::OAUTH_REFRESH_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
  1398. if ($result)
  1399. {
  1400. $json = json_decode($result,true);
  1401. if (!$json || !empty($json['errcode'])) {
  1402. $this->errCode = $json['errcode'];
  1403. $this->errMsg = $json['errmsg'];
  1404. return false;
  1405. }
  1406. $this->user_token = $json['access_token'];
  1407. return $json;
  1408. }
  1409. return false;
  1410. }
  1411. /**
  1412. * 获取授权后的用户资料
  1413. * @param string $access_token
  1414. * @param string $openid
  1415. * @return array {openid,nickname,sex,province,city,country,headimgurl,privilege,[unionid]}
  1416. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  1417. */
  1418. public function getOauthUserinfo($access_token,$openid){
  1419. $result = $this->http_get(self::OAUTH_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
  1420. if ($result)
  1421. {
  1422. $json = json_decode($result,true);
  1423. if (!$json || !empty($json['errcode'])) {
  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 string $access_token
  1435. * @param string $openid
  1436. * @return boolean 是否有效
  1437. */
  1438. public function getOauthAuth($access_token,$openid){
  1439. $result = $this->http_get(self::OAUTH_AUTH_URL.'access_token='.$access_token.'&openid='.$openid);
  1440. if ($result)
  1441. {
  1442. $json = json_decode($result,true);
  1443. if (!$json || !empty($json['errcode'])) {
  1444. $this->errCode = $json['errcode'];
  1445. $this->errMsg = $json['errmsg'];
  1446. return false;
  1447. } else
  1448. if ($json['errcode']==0) return true;
  1449. }
  1450. return false;
  1451. }
  1452. /**
  1453. * 获取签名
  1454. * @param array $arrdata 签名数组
  1455. * @param string $method 签名方法
  1456. * @return boolean|string 签名值
  1457. */
  1458. public function getSignature($arrdata,$method="sha1") {
  1459. if (!function_exists($method)) return false;
  1460. ksort($arrdata);
  1461. $paramstring = "";
  1462. foreach($arrdata as $key => $value)
  1463. {
  1464. if(strlen($paramstring) == 0)
  1465. $paramstring .= $key . "=" . $value;
  1466. else
  1467. $paramstring .= "&" . $key . "=" . $value;
  1468. }
  1469. $paySign = $method($paramstring);
  1470. return $paySign;
  1471. }
  1472. /**
  1473. * 生成随机字串
  1474. * @param number $length 长度,默认为16,最长为32字节
  1475. * @return string
  1476. */
  1477. public function generateNonceStr($length=16){
  1478. // 密码字符集,可任意添加你需要的字符
  1479. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1480. $str = "";
  1481. for($i = 0; $i < $length; $i++)
  1482. {
  1483. $str .= $chars[mt_rand(0, strlen($chars) - 1)];
  1484. }
  1485. return $str;
  1486. }
  1487. /**
  1488. * 生成原生支付url
  1489. * @param number $productid 商品编号,最长为32字节
  1490. * @return string
  1491. */
  1492. public function createNativeUrl($productid){
  1493. $nativeObj["appid"] = $this->appid;
  1494. $nativeObj["appkey"] = $this->paysignkey;
  1495. $nativeObj["productid"] = urlencode($productid);
  1496. $nativeObj["timestamp"] = time();
  1497. $nativeObj["noncestr"] = $this->generateNonceStr();
  1498. $nativeObj["sign"] = $this->getSignature($nativeObj);
  1499. unset($nativeObj["appkey"]);
  1500. $bizString = "";
  1501. foreach($nativeObj as $key => $value)
  1502. {
  1503. if(strlen($bizString) == 0)
  1504. $bizString .= $key . "=" . $value;
  1505. else
  1506. $bizString .= "&" . $key . "=" . $value;
  1507. }
  1508. return "weixin://wxpay/bizpayurl?".$bizString;
  1509. //weixin://wxpay/bizpayurl?sign=XXXXX&appid=XXXXXX&productid=XXXXXX&timestamp=XXXXXX&noncestr=XXXXXX
  1510. }
  1511. /**
  1512. * 生成订单package字符串
  1513. * @param string $out_trade_no 必填,商户系统内部的订单号,32个字符内,确保在商户系统唯一
  1514. * @param string $body 必填,商品描述,128 字节以下
  1515. * @param int $total_fee 必填,订单总金额,单位为分
  1516. * @param string $notify_url 必填,支付完成通知回调接口,255 字节以内
  1517. * @param string $spbill_create_ip 必填,用户终端IP,IPV4字串,15字节内
  1518. * @param int $fee_type 必填,现金支付币种,默认1:人民币
  1519. * @param string $bank_type 必填,银行通道类型,默认WX
  1520. * @param string $input_charset 必填,传入参数字符编码,默认UTF-8,取值有UTF-8和GBK
  1521. * @param string $time_start 交易起始时间,订单生成时间,格式yyyyMMddHHmmss
  1522. * @param string $time_expire 交易结束时间,也是订单失效时间
  1523. * @param int $transport_fee 物流费用,单位为分
  1524. * @param int $product_fee 商品费用,单位为分,必须保证 transport_fee + product_fee=total_fee
  1525. * @param string $goods_tag 商品标记,优惠券时可能用到
  1526. * @param string $attach 附加数据,notify接口原样返回
  1527. * @return string
  1528. */
  1529. public function createPackage($out_trade_no,$body,$total_fee,$notify_url,$spbill_create_ip,$fee_type=1,$bank_type="WX",$input_charset="UTF-8",$time_start="",$time_expire="",$transport_fee="",$product_fee="",$goods_tag="",$attach=""){
  1530. $arrdata = array("bank_type" => $bank_type, "body" => $body, "partner" => $this->partnerid, "out_trade_no" => $out_trade_no, "total_fee" => $total_fee, "fee_type" => $fee_type, "notify_url" => $notify_url, "spbill_create_ip" => $spbill_create_ip, "input_charset" => $input_charset);
  1531. if ($time_start) $arrdata['time_start'] = $time_start;
  1532. if ($time_expire) $arrdata['time_expire'] = $time_expire;
  1533. if ($transport_fee) $arrdata['transport_fee'] = $transport_fee;
  1534. if ($product_fee) $arrdata['product_fee'] = $product_fee;
  1535. if ($goods_tag) $arrdata['goods_tag'] = $goods_tag;
  1536. if ($attach) $arrdata['attach'] = $attach;
  1537. ksort($arrdata);
  1538. $paramstring = "";
  1539. foreach($arrdata as $key => $value)
  1540. {
  1541. if(strlen($paramstring) == 0)
  1542. $paramstring .= $key . "=" . $value;
  1543. else
  1544. $paramstring .= "&" . $key . "=" . $value;
  1545. }
  1546. $stringSignTemp = $paramstring . "&key=" . $this->partnerkey;
  1547. $signValue = strtoupper(md5($stringSignTemp));
  1548. $package = http_build_query($arrdata) . "&sign=" . $signValue;
  1549. return $package;
  1550. }
  1551. /**
  1552. * 支付签名(paySign)生成方法
  1553. * @param string $package 订单详情字串
  1554. * @param string $timeStamp 当前时间戳(需与JS输出的一致)
  1555. * @param string $nonceStr 随机串(需与JS输出的一致)
  1556. * @return string 返回签名字串
  1557. */
  1558. public function getPaySign($package, $timeStamp, $nonceStr){
  1559. $arrdata = array("appid" => $this->appid, "timestamp" => $timeStamp, "noncestr" => $nonceStr, "package" => $package, "appkey" => $this->paysignkey);
  1560. $paySign = $this->getSignature($arrdata);
  1561. return $paySign;
  1562. }
  1563. /**
  1564. * 回调通知签名验证
  1565. * @param array $orderxml 返回的orderXml的数组表示,留空则自动从post数据获取
  1566. * @return boolean
  1567. */
  1568. public function checkOrderSignature($orderxml=''){
  1569. if (!$orderxml) {
  1570. $postStr = file_get_contents("php://input");
  1571. if (!empty($postStr)) {
  1572. $orderxml = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  1573. } else return false;
  1574. }
  1575. $arrdata = array('appid'=>$orderxml['AppId'],'appkey'=>$this->paysignkey,'timestamp'=>$orderxml['TimeStamp'],'noncestr'=>$orderxml['NonceStr'],'openid'=>$orderxml['OpenId'],'issubscribe'=>$orderxml['IsSubscribe']);
  1576. $paySign = $this->getSignature($arrdata);
  1577. if ($paySign!=$orderxml['AppSignature']) return false;
  1578. return true;
  1579. }
  1580. /**
  1581. * 发货通知
  1582. * @param string $openid 用户open_id
  1583. * @param string $transid 交易单号
  1584. * @param string $out_trade_no 第三方订单号
  1585. * @param int $status 0:发货失败;1:已发货
  1586. * @param string $msg 失败原因
  1587. * @return boolean|array
  1588. */
  1589. public function sendPayDeliverNotify($openid,$transid,$out_trade_no,$status=1,$msg='ok'){
  1590. if (!$this->access_token && !$this->checkAuth()) return false;
  1591. $postdata = array(
  1592. "appid"=>$this->appid,
  1593. "appkey"=>$this->paysignkey,
  1594. "openid"=>$openid,
  1595. "transid"=>strval($transid),
  1596. "out_trade_no"=>strval($out_trade_no),
  1597. "deliver_timestamp"=>strval(time()),
  1598. "deliver_status"=>strval($status),
  1599. "deliver_msg"=>$msg,
  1600. );
  1601. $postdata['app_signature'] = $this->getSignature($postdata);
  1602. $postdata['sign_method'] = 'sha1';
  1603. unset($postdata['appkey']);
  1604. $result = $this->http_post(self::PAY_DELIVERNOTIFY.'access_token='.$this->access_token,self::json_encode($postdata));
  1605. if ($result)
  1606. {
  1607. $json = json_decode($result,true);
  1608. if (!$json || !empty($json['errcode'])) {
  1609. $this->errCode = $json['errcode'];
  1610. $this->errMsg = $json['errmsg'];
  1611. return false;
  1612. }
  1613. return $json;
  1614. }
  1615. return false;
  1616. }
  1617. /**
  1618. * 查询订单信息
  1619. * @param string $out_trade_no 订单号
  1620. * @return boolean|array
  1621. */
  1622. public function getPayOrder($out_trade_no) {
  1623. if (!$this->access_token && !$this->checkAuth()) return false;
  1624. $sign = strtoupper(md5("out_trade_no=$out_trade_no&partner={$this->partnerid}&key={$this->partnerkey}"));
  1625. $postdata = array(
  1626. "appid"=>$this->appid,
  1627. "appkey"=>$this->paysignkey,
  1628. "package"=>"out_trade_no=$out_trade_no&partner={$this->partnerid}&sign=$sign",
  1629. "timestamp"=>strval(time()),
  1630. );
  1631. $postdata['app_signature'] = $this->getSignature($postdata);
  1632. $postdata['sign_method'] = 'sha1';
  1633. unset($postdata['appkey']);
  1634. $result = $this->http_post(self::PAY_ORDERQUERY.'access_token='.$this->access_token,self::json_encode($postdata));
  1635. if ($result)
  1636. {
  1637. $json = json_decode($result,true);
  1638. if (!$json || !empty($json['errcode'])) {
  1639. $this->errCode = $json['errcode'];
  1640. $this->errMsg = $json['errmsg'].json_encode($postdata);
  1641. return false;
  1642. }
  1643. return $json["order_info"];
  1644. }
  1645. return false;
  1646. }
  1647. /**
  1648. * 获取收货地址JS的签名
  1649. * @tutorial 参考weixin.js脚本的WeixinJS.editAddress方法调用
  1650. * @param string $appId
  1651. * @param string $url
  1652. * @param int $timeStamp
  1653. * @param string $nonceStr
  1654. * @param string $user_token
  1655. * @return Ambigous <boolean, string>
  1656. */
  1657. public function getAddrSign($url, $timeStamp, $nonceStr, $user_token=''){
  1658. if (!$user_token) $user_token = $this->user_token;
  1659. if (!$user_token) {
  1660. $this->errMsg = 'no user access token found!';
  1661. return false;
  1662. }
  1663. $url = htmlspecialchars_decode($url);
  1664. $arrdata = array(
  1665. 'appid'=>$this->appid,
  1666. 'url'=>$url,
  1667. 'timestamp'=>strval($timeStamp),
  1668. 'noncestr'=>$nonceStr,
  1669. 'accesstoken'=>$user_token
  1670. );
  1671. return $this->getSignature($arrdata);
  1672. }
  1673. /**
  1674. * 发送模板消息
  1675. * @param array $data 消息结构
  1676. * {
  1677. "touser":"OPENID",
  1678. "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
  1679. "url":"http://weixin.qq.com/download",
  1680. "topcolor":"#FF0000",
  1681. "data":{
  1682. "参数名1": {
  1683. "value":"参数",
  1684. "color":"#173177" //参数颜色
  1685. },
  1686. "Date":{
  1687. "value":"06月07日 19时24分",
  1688. "color":"#173177"
  1689. },
  1690. "CardNumber":{
  1691. "value":"0426",
  1692. "color":"#173177"
  1693. },
  1694. "Type":{
  1695. "value":"消费",
  1696. "color":"#173177"
  1697. }
  1698. }
  1699. }
  1700. * @return boolean|array
  1701. */
  1702. public function sendTemplateMessage($data){
  1703. if (!$this->access_token && !$this->checkAuth()) return false;
  1704. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1705. if($result){
  1706. $json = json_decode($result,true);
  1707. if (!$json || !empty($json['errcode'])) {
  1708. $this->errCode = $json['errcode'];
  1709. $this->errMsg = $json['errmsg'];
  1710. return false;
  1711. }
  1712. return $json;
  1713. }
  1714. return false;
  1715. }
  1716. /**
  1717. * 获取多客服会话记录
  1718. * @param array $data 数据结构{"starttime":123456789,"endtime":987654321,"openid":"OPENID","pagesize":10,"pageindex":1,}
  1719. * @return boolean|array
  1720. */
  1721. public function getCustomServiceMessage($data){
  1722. if (!$this->access_token && !$this->checkAuth()) return false;
  1723. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_RECORD.'access_token='.$this->access_token,self::json_encode($data));
  1724. if ($result)
  1725. {
  1726. $json = json_decode($result,true);
  1727. if (!$json || !empty($json['errcode'])) {
  1728. $this->errCode = $json['errcode'];
  1729. $this->errMsg = $json['errmsg'];
  1730. return false;
  1731. }
  1732. return $json;
  1733. }
  1734. return false;
  1735. }
  1736. /**
  1737. * 转发多客服消息
  1738. * Examle: $obj->transfer_customer_service($customer_account)->reply();
  1739. * @param string $customer_account 转发到指定客服帐号:test1@test
  1740. */
  1741. public function transfer_customer_service($customer_account = '')
  1742. {
  1743. $msg = array(
  1744. 'ToUserName' => $this->getRevFrom(),
  1745. 'FromUserName'=>$this->getRevTo(),
  1746. 'CreateTime'=>time(),
  1747. 'MsgType'=>'transfer_customer_service',
  1748. );
  1749. if (!$customer_account) {
  1750. $msg['TransInfo'] = array('KfAccount'=>$customer_account);
  1751. }
  1752. $this->Message($msg);
  1753. return $this;
  1754. }
  1755. /**
  1756. * 获取多客服客服基本信息
  1757. *
  1758. * @return boolean|array
  1759. */
  1760. public function getCustomServiceKFlist(){
  1761. if (!$this->access_token && !$this->checkAuth()) return false;
  1762. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_KFLIST.'access_token='.$this->access_token);
  1763. if ($result)
  1764. {
  1765. $json = json_decode($result,true);
  1766. if (!$json || !empty($json['errcode'])) {
  1767. $this->errCode = $json['errcode'];
  1768. $this->errMsg = $json['errmsg'];
  1769. return false;
  1770. }
  1771. return $json;
  1772. }
  1773. return false;
  1774. }
  1775. /**
  1776. * 获取多客服在线客服接待信息
  1777. *
  1778. * @return boolean|array {
  1779. "kf_online_list": [
  1780. {
  1781. "kf_account": "test1@test", //客服账号@微信别名
  1782. "status": 1, //客服在线状态 1:pc在线,2:手机在线,若pc和手机同时在线则为 1+2=3
  1783. "kf_id": "1001", //客服工号
  1784. "auto_accept": 0, //客服设置的最大自动接入数
  1785. "accepted_case": 1 //客服当前正在接待的会话数
  1786. }
  1787. ]
  1788. }
  1789. */
  1790. public function getCustomServiceOnlineKFlist(){
  1791. if (!$this->access_token && !$this->checkAuth()) return false;
  1792. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_ONLINEKFLIST.'access_token='.$this->access_token);
  1793. if ($result)
  1794. {
  1795. $json = json_decode($result,true);
  1796. if (!$json || !empty($json['errcode'])) {
  1797. $this->errCode = $json['errcode'];
  1798. $this->errMsg = $json['errmsg'];
  1799. return false;
  1800. }
  1801. return $json;
  1802. }
  1803. return false;
  1804. }
  1805. }