Wechat.class.php 55 KB

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