wechat.class.php 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899
  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. * @param string $token 手动指定access_token,非必要情况不建议用
  789. */
  790. public function checkAuth($appid='',$appsecret='',$token=''){
  791. if (!$appid || !$appsecret) {
  792. $appid = $this->appid;
  793. $appsecret = $this->appsecret;
  794. }
  795. if ($token) { //手动指定token,优先使用
  796. $this->access_token=$token;
  797. return $this->access_token;
  798. }
  799. //TODO: get the cache access_token
  800. $result = $this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret);
  801. if ($result)
  802. {
  803. $json = json_decode($result,true);
  804. if (!$json || isset($json['errcode'])) {
  805. $this->errCode = $json['errcode'];
  806. $this->errMsg = $json['errmsg'];
  807. return false;
  808. }
  809. $this->access_token = $json['access_token'];
  810. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  811. //TODO: cache access_token
  812. return $this->access_token;
  813. }
  814. return false;
  815. }
  816. /**
  817. * 删除验证数据
  818. * @param string $appid
  819. */
  820. public function resetAuth($appid=''){
  821. if (!$appid) $appid = $this->appid;
  822. $this->access_token = '';
  823. //TODO: remove cache
  824. return true;
  825. }
  826. /**
  827. * 微信api不支持中文转义的json结构
  828. * @param array $arr
  829. */
  830. static function json_encode($arr) {
  831. $parts = array ();
  832. $is_list = false;
  833. //Find out if the given array is a numerical array
  834. $keys = array_keys ( $arr );
  835. $max_length = count ( $arr ) - 1;
  836. if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
  837. $is_list = true;
  838. for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
  839. if ($i != $keys [$i]) { //A key fails at position check.
  840. $is_list = false; //It is an associative array.
  841. break;
  842. }
  843. }
  844. }
  845. foreach ( $arr as $key => $value ) {
  846. if (is_array ( $value )) { //Custom handling for arrays
  847. if ($is_list)
  848. $parts [] = self::json_encode ( $value ); /* :RECURSION: */
  849. else
  850. $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
  851. } else {
  852. $str = '';
  853. if (! $is_list)
  854. $str = '"' . $key . '":';
  855. //Custom handling for multiple data types
  856. if (is_numeric ( $value ) && $value<2000000000)
  857. $str .= $value; //Numbers
  858. elseif ($value === false)
  859. $str .= 'false'; //The booleans
  860. elseif ($value === true)
  861. $str .= 'true';
  862. else
  863. $str .= '"' . addslashes ( $value ) . '"'; //All other things
  864. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  865. $parts [] = $str;
  866. }
  867. }
  868. $json = implode ( ',', $parts );
  869. if ($is_list)
  870. return '[' . $json . ']'; //Return numerical JSON
  871. return '{' . $json . '}'; //Return associative JSON
  872. }
  873. /**
  874. * 创建菜单
  875. * @param array $data 菜单数组数据
  876. * example:
  877. * array (
  878. * 'button' => array (
  879. * 0 => array (
  880. * 'name' => '扫码',
  881. * 'sub_button' => array (
  882. * 0 => array (
  883. * 'type' => 'scancode_waitmsg',
  884. * 'name' => '扫码带提示',
  885. * 'key' => 'rselfmenu_0_0',
  886. * 'sub_button' => ''
  887. * ),
  888. * 1 => array (
  889. * 'type' => 'scancode_push',
  890. * 'name' => '扫码推事件',
  891. * 'key' => 'rselfmenu_0_1',
  892. * 'sub_button' => ''
  893. * ),
  894. * ),
  895. * ),
  896. * 1 => array (
  897. * 'name' => '发图',
  898. * 'sub_button' => array (
  899. * 0 => array (
  900. * 'type' => 'pic_sysphoto',
  901. * 'name' => '系统拍照发图',
  902. * 'key' => 'rselfmenu_1_0',
  903. * 'sub_button' => ''
  904. * ),
  905. * 1 => array (
  906. * 'type' => 'pic_photo_or_album',
  907. * 'name' => '拍照或者相册发图',
  908. * 'key' => 'rselfmenu_1_1',
  909. * 'sub_button' => ''
  910. * )
  911. * ),
  912. * ),
  913. * 2 => array (
  914. * 'type' => 'location_select',
  915. * 'name' => '发送位置',
  916. * 'key' => 'rselfmenu_2_0',
  917. * 'sub_button' => ''
  918. * ),
  919. * ),
  920. * )
  921. * type可以选择为以下几种,其中5-8除了收到菜单事件以外,还会单独收到对应类型的信息。
  922. * 1、click:点击推事件
  923. * 2、view:跳转URL
  924. * 3、scancode_push:扫码推事件
  925. * 4、scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
  926. * 5、pic_sysphoto:弹出系统拍照发图
  927. * 6、pic_photo_or_album:弹出拍照或者相册发图
  928. * 7、pic_weixin:弹出微信相册发图器
  929. * 8、location_select:弹出地理位置选择器
  930. */
  931. public function createMenu($data){
  932. if (!$this->access_token && !$this->checkAuth()) return false;
  933. $result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  934. if ($result)
  935. {
  936. $json = json_decode($result,true);
  937. if (!$json || !empty($json['errcode'])) {
  938. $this->errCode = $json['errcode'];
  939. $this->errMsg = $json['errmsg'];
  940. return false;
  941. }
  942. return true;
  943. }
  944. return false;
  945. }
  946. /**
  947. * 获取菜单
  948. * @return array('menu'=>array(....s))
  949. */
  950. public function getMenu(){
  951. if (!$this->access_token && !$this->checkAuth()) return false;
  952. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
  953. if ($result)
  954. {
  955. $json = json_decode($result,true);
  956. if (!$json || isset($json['errcode'])) {
  957. $this->errCode = $json['errcode'];
  958. $this->errMsg = $json['errmsg'];
  959. return false;
  960. }
  961. return $json;
  962. }
  963. return false;
  964. }
  965. /**
  966. * 删除菜单
  967. * @return boolean
  968. */
  969. public function deleteMenu(){
  970. if (!$this->access_token && !$this->checkAuth()) return false;
  971. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
  972. if ($result)
  973. {
  974. $json = json_decode($result,true);
  975. if (!$json || !empty($json['errcode'])) {
  976. $this->errCode = $json['errcode'];
  977. $this->errMsg = $json['errmsg'];
  978. return false;
  979. }
  980. return true;
  981. }
  982. return false;
  983. }
  984. /**
  985. * 上传多媒体文件
  986. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  987. * @param array $data {"media":'@Path\filename.jpg'}
  988. * @param type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
  989. * @return boolean|array
  990. */
  991. public function uploadMedia($data, $type){
  992. if (!$this->access_token && !$this->checkAuth()) return false;
  993. $result = $this->http_post(self::UPLOAD_MEDIA_URL.self::MEDIA_UPLOAD.'access_token='.$this->access_token.'&type='.$type,$data);
  994. if ($result)
  995. {
  996. $json = json_decode($result,true);
  997. if (!$json || !empty($json['errcode'])) {
  998. $this->errCode = $json['errcode'];
  999. $this->errMsg = $json['errmsg'];
  1000. return false;
  1001. }
  1002. return $json;
  1003. }
  1004. return false;
  1005. }
  1006. /**
  1007. * 根据媒体文件ID获取媒体文件
  1008. * @param string $media_id 媒体文件id
  1009. * @return raw data
  1010. */
  1011. public function getMedia($media_id){
  1012. if (!$this->access_token && !$this->checkAuth()) return false;
  1013. $result = $this->http_get(self::UPLOAD_MEDIA_URL.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
  1014. if ($result)
  1015. {
  1016. $json = json_decode($result,true);
  1017. if (isset($json['errcode'])) {
  1018. $this->errCode = $json['errcode'];
  1019. $this->errMsg = $json['errmsg'];
  1020. return false;
  1021. }
  1022. return $json;
  1023. }
  1024. return false;
  1025. }
  1026. /**
  1027. * 上传图文消息素材
  1028. * @param array $data 消息结构{"articles":[{...}]}
  1029. * @return boolean|array
  1030. */
  1031. public function uploadArticles($data){
  1032. if (!$this->access_token && !$this->checkAuth()) return false;
  1033. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADNEWS_URL.'access_token='.$this->access_token,self::json_encode($data));
  1034. if ($result)
  1035. {
  1036. $json = json_decode($result,true);
  1037. if (!$json || !empty($json['errcode'])) {
  1038. $this->errCode = $json['errcode'];
  1039. $this->errMsg = $json['errmsg'];
  1040. return false;
  1041. }
  1042. return $json;
  1043. }
  1044. return false;
  1045. }
  1046. /**
  1047. * 高级群发消息, 根据OpenID列表群发图文消息
  1048. * @param array $data 消息结构{ "touser":[ "OPENID1", "OPENID2" ], "mpnews":{ "media_id":"123dsdajkasd231jhksad" }, "msgtype":"mpnews" }
  1049. * @return boolean|array
  1050. */
  1051. public function sendMassMessage($data){
  1052. if (!$this->access_token && !$this->checkAuth()) return false;
  1053. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1054. if ($result)
  1055. {
  1056. $json = json_decode($result,true);
  1057. if (!$json || !empty($json['errcode'])) {
  1058. $this->errCode = $json['errcode'];
  1059. $this->errMsg = $json['errmsg'];
  1060. return false;
  1061. }
  1062. return $json;
  1063. }
  1064. return false;
  1065. }
  1066. /**
  1067. * 高级群发消息, 根据群组id群发图文消息
  1068. * @param array $data 消息结构{ "filter":[ "group_id": "2" ], "mpnews":{ "media_id":"123dsdajkasd231jhksad" }, "msgtype":"mpnews" }
  1069. * @return boolean|array
  1070. */
  1071. public function sendGroupMassMessage($data){
  1072. if (!$this->access_token && !$this->checkAuth()) return false;
  1073. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1074. if ($result)
  1075. {
  1076. $json = json_decode($result,true);
  1077. if (!$json || !empty($json['errcode'])) {
  1078. $this->errCode = $json['errcode'];
  1079. $this->errMsg = $json['errmsg'];
  1080. return false;
  1081. }
  1082. return $json;
  1083. }
  1084. return false;
  1085. }
  1086. /**
  1087. * 高级群发消息, 删除群发图文消息
  1088. * @param int $msg_id 消息id
  1089. * @return boolean|array
  1090. */
  1091. public function deleteMassMessage($msg_id){
  1092. if (!$this->access_token && !$this->checkAuth()) return false;
  1093. $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)));
  1094. if ($result)
  1095. {
  1096. $json = json_decode($result,true);
  1097. if (!$json || !empty($json['errcode'])) {
  1098. $this->errCode = $json['errcode'];
  1099. $this->errMsg = $json['errmsg'];
  1100. return false;
  1101. }
  1102. return true;
  1103. }
  1104. return false;
  1105. }
  1106. /**
  1107. * 创建二维码ticket
  1108. * @param int $scene_id 自定义追踪id
  1109. * @param int $type 0:临时二维码;1:永久二维码(此时expire参数无效)
  1110. * @param int $expire 临时二维码有效期,最大为1800秒
  1111. * @return array('ticket'=>'qrcode字串','expire_seconds'=>1800,'url'=>'二维码图片解析后的地址')
  1112. */
  1113. public function getQRCode($scene_id,$type=0,$expire=1800){
  1114. if (!$this->access_token && !$this->checkAuth()) return false;
  1115. $data = array(
  1116. 'action_name'=>$type?"QR_LIMIT_SCENE":"QR_SCENE",
  1117. 'expire_seconds'=>$expire,
  1118. 'action_info'=>array('scene'=>array('scene_id'=>$scene_id))
  1119. );
  1120. if ($type == 1) {
  1121. unset($data['expire_seconds']);
  1122. }
  1123. $result = $this->http_post(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1124. if ($result)
  1125. {
  1126. $json = json_decode($result,true);
  1127. if (!$json || !empty($json['errcode'])) {
  1128. $this->errCode = $json['errcode'];
  1129. $this->errMsg = $json['errmsg'];
  1130. return false;
  1131. }
  1132. return $json;
  1133. }
  1134. return false;
  1135. }
  1136. /**
  1137. * 获取二维码图片
  1138. * @param string $ticket 传入由getQRCode方法生成的ticket参数
  1139. * @return string url 返回http地址
  1140. */
  1141. public function getQRUrl($ticket) {
  1142. return self::QRCODE_IMG_URL.$ticket;
  1143. }
  1144. /**
  1145. * 长链接转短链接接口
  1146. * @param string $long_url 传入要转换的长url
  1147. * @return boolean|string url 成功则返回转换后的短url
  1148. */
  1149. public function getShortUrl($long_url){
  1150. if (!$this->access_token && !$this->checkAuth()) return false;
  1151. $data = array(
  1152. 'action'=>'long2short',
  1153. 'long_url'=>$long_url
  1154. );
  1155. $result = $this->http_post(self::API_URL_PREFIX.self::SHORT_URL.'access_token='.$this->access_token,self::json_encode($data));
  1156. if ($result)
  1157. {
  1158. $json = json_decode($result,true);
  1159. if (!$json || !empty($json['errcode'])) {
  1160. $this->errCode = $json['errcode'];
  1161. $this->errMsg = $json['errmsg'];
  1162. return false;
  1163. }
  1164. return $json['short_url'];
  1165. }
  1166. return false;
  1167. }
  1168. /**
  1169. * 批量获取关注用户列表
  1170. * @param unknown $next_openid
  1171. */
  1172. public function getUserList($next_openid=''){
  1173. if (!$this->access_token && !$this->checkAuth()) return false;
  1174. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
  1175. if ($result)
  1176. {
  1177. $json = json_decode($result,true);
  1178. if (isset($json['errcode'])) {
  1179. $this->errCode = $json['errcode'];
  1180. $this->errMsg = $json['errmsg'];
  1181. return false;
  1182. }
  1183. return $json;
  1184. }
  1185. return false;
  1186. }
  1187. /**
  1188. * 获取关注者详细信息
  1189. * @param string $openid
  1190. * @return array {subscribe,openid,nickname,sex,city,province,country,language,headimgurl,subscribe_time,[unionid]}
  1191. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  1192. */
  1193. public function getUserInfo($openid){
  1194. if (!$this->access_token && !$this->checkAuth()) return false;
  1195. $result = $this->http_get(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
  1196. if ($result)
  1197. {
  1198. $json = json_decode($result,true);
  1199. if (isset($json['errcode'])) {
  1200. $this->errCode = $json['errcode'];
  1201. $this->errMsg = $json['errmsg'];
  1202. return false;
  1203. }
  1204. return $json;
  1205. }
  1206. return false;
  1207. }
  1208. /**
  1209. * 设置用户备注名
  1210. * @param string $openid
  1211. * @param string $remark 备注名
  1212. * @return boolean|array
  1213. */
  1214. public function updateUserRemark($openid,$remark){
  1215. if (!$this->access_token && !$this->checkAuth()) return false;
  1216. $data = array(
  1217. 'openid'=>$openid,
  1218. 'remark'=>$remark
  1219. );
  1220. $result = $this->http_post(self::API_URL_PREFIX.self::USER_UPDATEREMARK_URL.'access_token='.$this->access_token,$data);
  1221. if ($result)
  1222. {
  1223. $json = json_decode($result,true);
  1224. if (!$json || !empty($json['errcode'])) {
  1225. $this->errCode = $json['errcode'];
  1226. $this->errMsg = $json['errmsg'];
  1227. return false;
  1228. }
  1229. return $json;
  1230. }
  1231. return false;
  1232. }
  1233. /**
  1234. * 获取用户分组列表
  1235. * @return boolean|array
  1236. */
  1237. public function getGroup(){
  1238. if (!$this->access_token && !$this->checkAuth()) return false;
  1239. $result = $this->http_get(self::API_URL_PREFIX.self::GROUP_GET_URL.'access_token='.$this->access_token);
  1240. if ($result)
  1241. {
  1242. $json = json_decode($result,true);
  1243. if (isset($json['errcode'])) {
  1244. $this->errCode = $json['errcode'];
  1245. $this->errMsg = $json['errmsg'];
  1246. return false;
  1247. }
  1248. return $json;
  1249. }
  1250. return false;
  1251. }
  1252. /**
  1253. * 获取用户所在分组
  1254. * @param string $openid
  1255. * @return boolean|int 成功则返回用户分组id
  1256. */
  1257. public function getUserGroup($openid){
  1258. if (!$this->access_token && !$this->checkAuth()) return false;
  1259. $data = array(
  1260. 'openid'=>$openid
  1261. );
  1262. $result = $this->http_post(self::API_URL_PREFIX.self::USER_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1263. if ($result)
  1264. {
  1265. $json = json_decode($result,true);
  1266. if (!$json || !empty($json['errcode'])) {
  1267. $this->errCode = $json['errcode'];
  1268. $this->errMsg = $json['errmsg'];
  1269. return false;
  1270. } else
  1271. if (isset($json['groupid'])) return $json['groupid'];
  1272. }
  1273. return false;
  1274. }
  1275. /**
  1276. * 新增自定分组
  1277. * @param string $name 分组名称
  1278. * @return boolean|array
  1279. */
  1280. public function createGroup($name){
  1281. if (!$this->access_token && !$this->checkAuth()) return false;
  1282. $data = array(
  1283. 'group'=>array('name'=>$name)
  1284. );
  1285. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1286. if ($result)
  1287. {
  1288. $json = json_decode($result,true);
  1289. if (!$json || !empty($json['errcode'])) {
  1290. $this->errCode = $json['errcode'];
  1291. $this->errMsg = $json['errmsg'];
  1292. return false;
  1293. }
  1294. return $json;
  1295. }
  1296. return false;
  1297. }
  1298. /**
  1299. * 更改分组名称
  1300. * @param int $groupid 分组id
  1301. * @param string $name 分组名称
  1302. * @return boolean|array
  1303. */
  1304. public function updateGroup($groupid,$name){
  1305. if (!$this->access_token && !$this->checkAuth()) return false;
  1306. $data = array(
  1307. 'group'=>array('id'=>$groupid,'name'=>$name)
  1308. );
  1309. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1310. if ($result)
  1311. {
  1312. $json = json_decode($result,true);
  1313. if (!$json || !empty($json['errcode'])) {
  1314. $this->errCode = $json['errcode'];
  1315. $this->errMsg = $json['errmsg'];
  1316. return false;
  1317. }
  1318. return $json;
  1319. }
  1320. return false;
  1321. }
  1322. /**
  1323. * 移动用户分组
  1324. * @param int $groupid 分组id
  1325. * @param string $openid 用户openid
  1326. * @return boolean|array
  1327. */
  1328. public function updateGroupMembers($groupid,$openid){
  1329. if (!$this->access_token && !$this->checkAuth()) return false;
  1330. $data = array(
  1331. 'openid'=>$openid,
  1332. 'to_groupid'=>$groupid
  1333. );
  1334. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1335. if ($result)
  1336. {
  1337. $json = json_decode($result,true);
  1338. if (!$json || !empty($json['errcode'])) {
  1339. $this->errCode = $json['errcode'];
  1340. $this->errMsg = $json['errmsg'];
  1341. return false;
  1342. }
  1343. return $json;
  1344. }
  1345. return false;
  1346. }
  1347. /**
  1348. * 发送客服消息
  1349. * @param array $data 消息结构{"touser":"OPENID","msgtype":"news","news":{...}}
  1350. * @return boolean|array
  1351. */
  1352. public function sendCustomMessage($data){
  1353. if (!$this->access_token && !$this->checkAuth()) return false;
  1354. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1355. if ($result)
  1356. {
  1357. $json = json_decode($result,true);
  1358. if (!$json || !empty($json['errcode'])) {
  1359. $this->errCode = $json['errcode'];
  1360. $this->errMsg = $json['errmsg'];
  1361. return false;
  1362. }
  1363. return $json;
  1364. }
  1365. return false;
  1366. }
  1367. /**
  1368. * oauth 授权跳转接口
  1369. * @param string $callback 回调URI
  1370. * @return string
  1371. */
  1372. public function getOauthRedirect($callback,$state='',$scope='snsapi_userinfo'){
  1373. return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  1374. }
  1375. /**
  1376. * 通过code获取Access Token
  1377. * @return array {access_token,expires_in,refresh_token,openid,scope}
  1378. */
  1379. public function getOauthAccessToken(){
  1380. $code = isset($_GET['code'])?$_GET['code']:'';
  1381. if (!$code) return false;
  1382. $result = $this->http_get(self::OAUTH_TOKEN_PREFIX.self::OAUTH_TOKEN_URL.'appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code');
  1383. if ($result)
  1384. {
  1385. $json = json_decode($result,true);
  1386. if (!$json || !empty($json['errcode'])) {
  1387. $this->errCode = $json['errcode'];
  1388. $this->errMsg = $json['errmsg'];
  1389. return false;
  1390. }
  1391. $this->user_token = $json['access_token'];
  1392. return $json;
  1393. }
  1394. return false;
  1395. }
  1396. /**
  1397. * 刷新access token并续期
  1398. * @param string $refresh_token
  1399. * @return boolean|mixed
  1400. */
  1401. public function getOauthRefreshToken($refresh_token){
  1402. $result = $this->http_get(self::OAUTH_TOKEN_PREFIX.self::OAUTH_REFRESH_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
  1403. if ($result)
  1404. {
  1405. $json = json_decode($result,true);
  1406. if (!$json || !empty($json['errcode'])) {
  1407. $this->errCode = $json['errcode'];
  1408. $this->errMsg = $json['errmsg'];
  1409. return false;
  1410. }
  1411. $this->user_token = $json['access_token'];
  1412. return $json;
  1413. }
  1414. return false;
  1415. }
  1416. /**
  1417. * 获取授权后的用户资料
  1418. * @param string $access_token
  1419. * @param string $openid
  1420. * @return array {openid,nickname,sex,province,city,country,headimgurl,privilege,[unionid]}
  1421. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  1422. */
  1423. public function getOauthUserinfo($access_token,$openid){
  1424. $result = $this->http_get(self::OAUTH_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
  1425. if ($result)
  1426. {
  1427. $json = json_decode($result,true);
  1428. if (!$json || !empty($json['errcode'])) {
  1429. $this->errCode = $json['errcode'];
  1430. $this->errMsg = $json['errmsg'];
  1431. return false;
  1432. }
  1433. return $json;
  1434. }
  1435. return false;
  1436. }
  1437. /**
  1438. * 检验授权凭证是否有效
  1439. * @param string $access_token
  1440. * @param string $openid
  1441. * @return boolean 是否有效
  1442. */
  1443. public function getOauthAuth($access_token,$openid){
  1444. $result = $this->http_get(self::OAUTH_AUTH_URL.'access_token='.$access_token.'&openid='.$openid);
  1445. if ($result)
  1446. {
  1447. $json = json_decode($result,true);
  1448. if (!$json || !empty($json['errcode'])) {
  1449. $this->errCode = $json['errcode'];
  1450. $this->errMsg = $json['errmsg'];
  1451. return false;
  1452. } else
  1453. if ($json['errcode']==0) return true;
  1454. }
  1455. return false;
  1456. }
  1457. /**
  1458. * 获取签名
  1459. * @param array $arrdata 签名数组
  1460. * @param string $method 签名方法
  1461. * @return boolean|string 签名值
  1462. */
  1463. public function getSignature($arrdata,$method="sha1") {
  1464. if (!function_exists($method)) return false;
  1465. ksort($arrdata);
  1466. $paramstring = "";
  1467. foreach($arrdata as $key => $value)
  1468. {
  1469. if(strlen($paramstring) == 0)
  1470. $paramstring .= $key . "=" . $value;
  1471. else
  1472. $paramstring .= "&" . $key . "=" . $value;
  1473. }
  1474. $paySign = $method($paramstring);
  1475. return $paySign;
  1476. }
  1477. /**
  1478. * 生成随机字串
  1479. * @param number $length 长度,默认为16,最长为32字节
  1480. * @return string
  1481. */
  1482. public function generateNonceStr($length=16){
  1483. // 密码字符集,可任意添加你需要的字符
  1484. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1485. $str = "";
  1486. for($i = 0; $i < $length; $i++)
  1487. {
  1488. $str .= $chars[mt_rand(0, strlen($chars) - 1)];
  1489. }
  1490. return $str;
  1491. }
  1492. /**
  1493. * 生成原生支付url
  1494. * @param number $productid 商品编号,最长为32字节
  1495. * @return string
  1496. */
  1497. public function createNativeUrl($productid){
  1498. $nativeObj["appid"] = $this->appid;
  1499. $nativeObj["appkey"] = $this->paysignkey;
  1500. $nativeObj["productid"] = urlencode($productid);
  1501. $nativeObj["timestamp"] = time();
  1502. $nativeObj["noncestr"] = $this->generateNonceStr();
  1503. $nativeObj["sign"] = $this->getSignature($nativeObj);
  1504. unset($nativeObj["appkey"]);
  1505. $bizString = "";
  1506. foreach($nativeObj as $key => $value)
  1507. {
  1508. if(strlen($bizString) == 0)
  1509. $bizString .= $key . "=" . $value;
  1510. else
  1511. $bizString .= "&" . $key . "=" . $value;
  1512. }
  1513. return "weixin://wxpay/bizpayurl?".$bizString;
  1514. //weixin://wxpay/bizpayurl?sign=XXXXX&appid=XXXXXX&productid=XXXXXX&timestamp=XXXXXX&noncestr=XXXXXX
  1515. }
  1516. /**
  1517. * 生成订单package字符串
  1518. * @param string $out_trade_no 必填,商户系统内部的订单号,32个字符内,确保在商户系统唯一
  1519. * @param string $body 必填,商品描述,128 字节以下
  1520. * @param int $total_fee 必填,订单总金额,单位为分
  1521. * @param string $notify_url 必填,支付完成通知回调接口,255 字节以内
  1522. * @param string $spbill_create_ip 必填,用户终端IP,IPV4字串,15字节内
  1523. * @param int $fee_type 必填,现金支付币种,默认1:人民币
  1524. * @param string $bank_type 必填,银行通道类型,默认WX
  1525. * @param string $input_charset 必填,传入参数字符编码,默认UTF-8,取值有UTF-8和GBK
  1526. * @param string $time_start 交易起始时间,订单生成时间,格式yyyyMMddHHmmss
  1527. * @param string $time_expire 交易结束时间,也是订单失效时间
  1528. * @param int $transport_fee 物流费用,单位为分
  1529. * @param int $product_fee 商品费用,单位为分,必须保证 transport_fee + product_fee=total_fee
  1530. * @param string $goods_tag 商品标记,优惠券时可能用到
  1531. * @param string $attach 附加数据,notify接口原样返回
  1532. * @return string
  1533. */
  1534. 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=""){
  1535. $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);
  1536. if ($time_start) $arrdata['time_start'] = $time_start;
  1537. if ($time_expire) $arrdata['time_expire'] = $time_expire;
  1538. if ($transport_fee) $arrdata['transport_fee'] = $transport_fee;
  1539. if ($product_fee) $arrdata['product_fee'] = $product_fee;
  1540. if ($goods_tag) $arrdata['goods_tag'] = $goods_tag;
  1541. if ($attach) $arrdata['attach'] = $attach;
  1542. ksort($arrdata);
  1543. $paramstring = "";
  1544. foreach($arrdata as $key => $value)
  1545. {
  1546. if(strlen($paramstring) == 0)
  1547. $paramstring .= $key . "=" . $value;
  1548. else
  1549. $paramstring .= "&" . $key . "=" . $value;
  1550. }
  1551. $stringSignTemp = $paramstring . "&key=" . $this->partnerkey;
  1552. $signValue = strtoupper(md5($stringSignTemp));
  1553. $package = http_build_query($arrdata) . "&sign=" . $signValue;
  1554. return $package;
  1555. }
  1556. /**
  1557. * 支付签名(paySign)生成方法
  1558. * @param string $package 订单详情字串
  1559. * @param string $timeStamp 当前时间戳(需与JS输出的一致)
  1560. * @param string $nonceStr 随机串(需与JS输出的一致)
  1561. * @return string 返回签名字串
  1562. */
  1563. public function getPaySign($package, $timeStamp, $nonceStr){
  1564. $arrdata = array("appid" => $this->appid, "timestamp" => $timeStamp, "noncestr" => $nonceStr, "package" => $package, "appkey" => $this->paysignkey);
  1565. $paySign = $this->getSignature($arrdata);
  1566. return $paySign;
  1567. }
  1568. /**
  1569. * 回调通知签名验证
  1570. * @param array $orderxml 返回的orderXml的数组表示,留空则自动从post数据获取
  1571. * @return boolean
  1572. */
  1573. public function checkOrderSignature($orderxml=''){
  1574. if (!$orderxml) {
  1575. $postStr = file_get_contents("php://input");
  1576. if (!empty($postStr)) {
  1577. $orderxml = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  1578. } else return false;
  1579. }
  1580. $arrdata = array('appid'=>$orderxml['AppId'],'appkey'=>$this->paysignkey,'timestamp'=>$orderxml['TimeStamp'],'noncestr'=>$orderxml['NonceStr'],'openid'=>$orderxml['OpenId'],'issubscribe'=>$orderxml['IsSubscribe']);
  1581. $paySign = $this->getSignature($arrdata);
  1582. if ($paySign!=$orderxml['AppSignature']) return false;
  1583. return true;
  1584. }
  1585. /**
  1586. * 发货通知
  1587. * @param string $openid 用户open_id
  1588. * @param string $transid 交易单号
  1589. * @param string $out_trade_no 第三方订单号
  1590. * @param int $status 0:发货失败;1:已发货
  1591. * @param string $msg 失败原因
  1592. * @return boolean|array
  1593. */
  1594. public function sendPayDeliverNotify($openid,$transid,$out_trade_no,$status=1,$msg='ok'){
  1595. if (!$this->access_token && !$this->checkAuth()) return false;
  1596. $postdata = array(
  1597. "appid"=>$this->appid,
  1598. "appkey"=>$this->paysignkey,
  1599. "openid"=>$openid,
  1600. "transid"=>strval($transid),
  1601. "out_trade_no"=>strval($out_trade_no),
  1602. "deliver_timestamp"=>strval(time()),
  1603. "deliver_status"=>strval($status),
  1604. "deliver_msg"=>$msg,
  1605. );
  1606. $postdata['app_signature'] = $this->getSignature($postdata);
  1607. $postdata['sign_method'] = 'sha1';
  1608. unset($postdata['appkey']);
  1609. $result = $this->http_post(self::PAY_DELIVERNOTIFY.'access_token='.$this->access_token,self::json_encode($postdata));
  1610. if ($result)
  1611. {
  1612. $json = json_decode($result,true);
  1613. if (!$json || !empty($json['errcode'])) {
  1614. $this->errCode = $json['errcode'];
  1615. $this->errMsg = $json['errmsg'];
  1616. return false;
  1617. }
  1618. return $json;
  1619. }
  1620. return false;
  1621. }
  1622. /**
  1623. * 查询订单信息
  1624. * @param string $out_trade_no 订单号
  1625. * @return boolean|array
  1626. */
  1627. public function getPayOrder($out_trade_no) {
  1628. if (!$this->access_token && !$this->checkAuth()) return false;
  1629. $sign = strtoupper(md5("out_trade_no=$out_trade_no&partner={$this->partnerid}&key={$this->partnerkey}"));
  1630. $postdata = array(
  1631. "appid"=>$this->appid,
  1632. "appkey"=>$this->paysignkey,
  1633. "package"=>"out_trade_no=$out_trade_no&partner={$this->partnerid}&sign=$sign",
  1634. "timestamp"=>strval(time()),
  1635. );
  1636. $postdata['app_signature'] = $this->getSignature($postdata);
  1637. $postdata['sign_method'] = 'sha1';
  1638. unset($postdata['appkey']);
  1639. $result = $this->http_post(self::PAY_ORDERQUERY.'access_token='.$this->access_token,self::json_encode($postdata));
  1640. if ($result)
  1641. {
  1642. $json = json_decode($result,true);
  1643. if (!$json || !empty($json['errcode'])) {
  1644. $this->errCode = $json['errcode'];
  1645. $this->errMsg = $json['errmsg'].json_encode($postdata);
  1646. return false;
  1647. }
  1648. return $json["order_info"];
  1649. }
  1650. return false;
  1651. }
  1652. /**
  1653. * 获取收货地址JS的签名
  1654. * @tutorial 参考weixin.js脚本的WeixinJS.editAddress方法调用
  1655. * @param string $appId
  1656. * @param string $url
  1657. * @param int $timeStamp
  1658. * @param string $nonceStr
  1659. * @param string $user_token
  1660. * @return Ambigous <boolean, string>
  1661. */
  1662. public function getAddrSign($url, $timeStamp, $nonceStr, $user_token=''){
  1663. if (!$user_token) $user_token = $this->user_token;
  1664. if (!$user_token) {
  1665. $this->errMsg = 'no user access token found!';
  1666. return false;
  1667. }
  1668. $url = htmlspecialchars_decode($url);
  1669. $arrdata = array(
  1670. 'appid'=>$this->appid,
  1671. 'url'=>$url,
  1672. 'timestamp'=>strval($timeStamp),
  1673. 'noncestr'=>$nonceStr,
  1674. 'accesstoken'=>$user_token
  1675. );
  1676. return $this->getSignature($arrdata);
  1677. }
  1678. /**
  1679. * 发送模板消息
  1680. * @param array $data 消息结构
  1681. * {
  1682. "touser":"OPENID",
  1683. "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
  1684. "url":"http://weixin.qq.com/download",
  1685. "topcolor":"#FF0000",
  1686. "data":{
  1687. "参数名1": {
  1688. "value":"参数",
  1689. "color":"#173177" //参数颜色
  1690. },
  1691. "Date":{
  1692. "value":"06月07日 19时24分",
  1693. "color":"#173177"
  1694. },
  1695. "CardNumber":{
  1696. "value":"0426",
  1697. "color":"#173177"
  1698. },
  1699. "Type":{
  1700. "value":"消费",
  1701. "color":"#173177"
  1702. }
  1703. }
  1704. }
  1705. * @return boolean|array
  1706. */
  1707. public function sendTemplateMessage($data){
  1708. if (!$this->access_token && !$this->checkAuth()) return false;
  1709. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1710. if($result){
  1711. $json = json_decode($result,true);
  1712. if (!$json || !empty($json['errcode'])) {
  1713. $this->errCode = $json['errcode'];
  1714. $this->errMsg = $json['errmsg'];
  1715. return false;
  1716. }
  1717. return $json;
  1718. }
  1719. return false;
  1720. }
  1721. /**
  1722. * 获取多客服会话记录
  1723. * @param array $data 数据结构{"starttime":123456789,"endtime":987654321,"openid":"OPENID","pagesize":10,"pageindex":1,}
  1724. * @return boolean|array
  1725. */
  1726. public function getCustomServiceMessage($data){
  1727. if (!$this->access_token && !$this->checkAuth()) return false;
  1728. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_RECORD.'access_token='.$this->access_token,self::json_encode($data));
  1729. if ($result)
  1730. {
  1731. $json = json_decode($result,true);
  1732. if (!$json || !empty($json['errcode'])) {
  1733. $this->errCode = $json['errcode'];
  1734. $this->errMsg = $json['errmsg'];
  1735. return false;
  1736. }
  1737. return $json;
  1738. }
  1739. return false;
  1740. }
  1741. /**
  1742. * 转发多客服消息
  1743. * Examle: $obj->transfer_customer_service($customer_account)->reply();
  1744. * @param string $customer_account 转发到指定客服帐号:test1@test
  1745. */
  1746. public function transfer_customer_service($customer_account = '')
  1747. {
  1748. $msg = array(
  1749. 'ToUserName' => $this->getRevFrom(),
  1750. 'FromUserName'=>$this->getRevTo(),
  1751. 'CreateTime'=>time(),
  1752. 'MsgType'=>'transfer_customer_service',
  1753. );
  1754. if (!$customer_account) {
  1755. $msg['TransInfo'] = array('KfAccount'=>$customer_account);
  1756. }
  1757. $this->Message($msg);
  1758. return $this;
  1759. }
  1760. /**
  1761. * 获取多客服客服基本信息
  1762. *
  1763. * @return boolean|array
  1764. */
  1765. public function getCustomServiceKFlist(){
  1766. if (!$this->access_token && !$this->checkAuth()) return false;
  1767. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_KFLIST.'access_token='.$this->access_token);
  1768. if ($result)
  1769. {
  1770. $json = json_decode($result,true);
  1771. if (!$json || !empty($json['errcode'])) {
  1772. $this->errCode = $json['errcode'];
  1773. $this->errMsg = $json['errmsg'];
  1774. return false;
  1775. }
  1776. return $json;
  1777. }
  1778. return false;
  1779. }
  1780. /**
  1781. * 获取多客服在线客服接待信息
  1782. *
  1783. * @return boolean|array {
  1784. "kf_online_list": [
  1785. {
  1786. "kf_account": "test1@test", //客服账号@微信别名
  1787. "status": 1, //客服在线状态 1:pc在线,2:手机在线,若pc和手机同时在线则为 1+2=3
  1788. "kf_id": "1001", //客服工号
  1789. "auto_accept": 0, //客服设置的最大自动接入数
  1790. "accepted_case": 1 //客服当前正在接待的会话数
  1791. }
  1792. ]
  1793. }
  1794. */
  1795. public function getCustomServiceOnlineKFlist(){
  1796. if (!$this->access_token && !$this->checkAuth()) return false;
  1797. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_ONLINEKFLIST.'access_token='.$this->access_token);
  1798. if ($result)
  1799. {
  1800. $json = json_decode($result,true);
  1801. if (!$json || !empty($json['errcode'])) {
  1802. $this->errCode = $json['errcode'];
  1803. $this->errMsg = $json['errmsg'];
  1804. return false;
  1805. }
  1806. return $json;
  1807. }
  1808. return false;
  1809. }
  1810. }