wechat.class.php 56 KB

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