登录  /  注册

基于EaglePHP框架v2.7开发的微信5.0最新最全的API接口

php中文网
发布: 2016-07-25 08:49:07
原创
755人浏览过
代码出处:http://www.eaglephp.com
适用平台:window/Linux
依赖项目:EaglePHP框架

包含微信5.0 API基础接口、自定义菜单、高级接口,具体如下:
1、接收用户消息。
2、向用户回复消息。
3、接受事件推送。
4、会话界面自定义菜单。
5、语音识别。
6、客服接口。
7、OAuth2.0网页授权。
8、生成带参数二维码。
9、获取用户地理位置。
10、获取用户基本信息。
11、获取关注者列表。
12、用户分组。
  1. /**
  2. * 微信公众平台API
  3. *
  4. * @author maojianlw@139.com
  5. * [url=home.php?mod=space&uid=17823]@LINK[/url] http://www.eaglephp.com
  6. */
  7. class WeixinChat
  8. {
  9. private $token;
  10. private $appid;
  11. private $appsecret;
  12. private $access_token;
  13. // 接收的数据
  14. private $_receive = array();
  15. private $_reply = '';
  16. // 接口错误码
  17. private $errCode = '';
  18. // 接口错误信息
  19. private $errMsg = '';
  20. // 微信oauth登陆获取code
  21. const CONNECT_OAUTH_AUTHORIZE_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
  22. // 微信oauth登陆通过code换取网页授权access_token
  23. const SNS_OAUTH_ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
  24. // 微信oauth登陆刷新access_token(如果需要)
  25. const SNS_OAUTH_REFRESH_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?';
  26. // 通过ticket换取二维码
  27. const SHOW_QRCODE_URL = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?';
  28. // 微信oauth登陆拉取用户信息(需scope为 snsapi_userinfo)
  29. const SNS_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo?';
  30. // 请求api前缀
  31. const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
  32. // 自定义菜单创建
  33. const MENU_CREATE_URL = '/menu/create?';
  34. // 自定义菜单查询
  35. const MENU_GET_URL = '/menu/get?';
  36. // 自定义菜单删除
  37. const MENU_DELETE_URL = '/menu/delete?';
  38. // 获取 access_token
  39. const AUTH_URL = '/token?grant_type=client_credential&';
  40. // 获取用户基本信息
  41. const USER_INFO_URL = '/user/info?';
  42. // 获取关注者列表
  43. const USER_GET_URL = '/user/get?';
  44. // 查询分组
  45. const GROUPS_GET_URL = '/groups/get?';
  46. // 创建分组
  47. const GROUPS_CREATE_URL = '/groups/create?';
  48. // 修改分组名
  49. const GROUPS_UPDATE_URL = '/groups/update?';
  50. // 移动用户分组
  51. const GROUPS_MEMBERS_UPDATE_URL = '/groups/members/update?';
  52. // 发送客服消息
  53. const MESSAGE_CUSTOM_SEND_URL = '/message/custom/send?';
  54. // 创建二维码ticket
  55. const QRCODE_CREATE_URL = '/qrcode/create?';
  56. /**
  57. * 初始化配置数据
  58. * @param array $options
  59. */
  60. public function __construct($options)
  61. {
  62. $this->token = isset($options['token']) ? $options['token'] : '';
  63. $this->appid = isset($options['appid']) ? $options['appid'] : '';
  64. $this->appsecret = isset($options['appsecret']) ? $options['appsecret'] : '';
  65. }
  66. /**
  67. * 获取发来的消息
  68. * 当普通微信用户向公众账号发消息时,微信服务器将POST消息的XML数据包到开发者填写的URL上。
  69. */
  70. public function getRev()
  71. {
  72. $postStr = file_get_contents('php://input');
  73. if($postStr)
  74. {
  75. $this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  76. //Log::info(var_export($this->_receive, true));
  77. }
  78. return $this;
  79. }
  80. /**
  81. * 获取微信服务器发来的消息
  82. */
  83. public function getRevData()
  84. {
  85. return $this->_receive;
  86. }
  87. /**
  88. * 获取接收者
  89. */
  90. public function getRevTo()
  91. {
  92. return isset($this->_receive['ToUserName']) ? $this->_receive['ToUserName'] : false;
  93. }
  94. /**
  95. * 获取消息发送者(一个OpenID)
  96. */
  97. public function getRevFrom()
  98. {
  99. return isset($this->_receive['FromUserName']) ? $this->_receive['FromUserName'] : false;
  100. }
  101. /**
  102. * 获取接收消息创建时间 (整型)
  103. */
  104. public function getRevCTime()
  105. {
  106. return isset($this->_receive['CreateTime']) ? $this->_receive['CreateTime'] : false;
  107. }
  108. /**
  109. * 获取接收消息类型(text、image、voice、video、location、link、event)
  110. */
  111. public function getRevType()
  112. {
  113. return isset($this->_receive['MsgType']) ? $this->_receive['MsgType'] : false;
  114. }
  115. /**
  116. * 获取接收消息编号
  117. */
  118. public function getRevId()
  119. {
  120. return isset($this->_receive['MsgId']) ? $this->_receive['MsgId'] : false;
  121. }
  122. /**
  123. * 获取接收消息文本
  124. * 通过语音识别接口,用户发送的语音,将会同时给出语音识别出的文本内容。(需申请服务号的高级接口权限)
  125. */
  126. public function getRevText()
  127. {
  128. if(isset($this->_receive['Content'])) return trim($this->_receive['Content']);
  129. elseif(isset($this->_receive['Recognition'])) return trim($this->_receive['Recognition']);
  130. else return false;
  131. }
  132. /**
  133. * 获取接收图片消息
  134. */
  135. public function getRevImage()
  136. {
  137. if(isset($this->_receive['PicUrl'])){
  138. return array(
  139. 'picUrl' => $this->_receive['PicUrl'], //图片链接
  140. 'mediaId' => $this->_receive['MediaId'] //图片消息媒体id,可以调用多媒体文件下载接口拉取数据。
  141. );
  142. }
  143. return false;
  144. }
  145. /**
  146. * 获取接收语音消息
  147. */
  148. public function getRevVoice()
  149. {
  150. if(isset($this->_receive['MediaId'])){
  151. return array(
  152. 'mediaId' => $this->_receive['MediaId'], //语音消息媒体id,可以调用多媒体文件下载接口拉取数据。
  153. 'format' => $this->_receive['Format'] //语音格式,如amr,speex等
  154. );
  155. }
  156. return false;
  157. }
  158. /**
  159. * 获取接收视频消息
  160. */
  161. public function getRevVideo()
  162. {
  163. if(isset($this->_receive['MediaId'])){
  164. return array(
  165. 'mediaId' => $this->_receive['MediaId'], //视频消息媒体id,可以调用多媒体文件下载接口拉取数据。
  166. 'thumbMediaId' => $this->_receive['ThumbMediaId'] //视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
  167. );
  168. }
  169. return false;
  170. }
  171. /**
  172. * 获取用户地理位置
  173. */
  174. public function getRevLocation()
  175. {
  176. if(isset($this->_receive['Location_X'])){
  177. return array(
  178. 'locationX' => $this->_receive['Location_X'], //地理位置维度
  179. 'locationY' => $this->_receive['Location_Y'], //地理位置经度
  180. 'scale' => $this->_receive['Scale'], //地图缩放大小
  181. 'label' => $this->_receive['Label'] //地理位置信息
  182. );
  183. }
  184. //开通了上报地理位置接口的公众号,用户在关注后进入公众号会话时,会弹框让用户确认是否允许公众号使用其地理位置。
  185. //弹框只在关注后出现一次,用户以后可以在公众号详情页面进行操作。
  186. elseif(isset($this->_receive['Latitude']))
  187. {
  188. return array(
  189. 'latitude' => $this->_receive['Latitude'], //地理位置纬度
  190. 'longitude' => $this->_receive['Longitude'], //地理位置经度
  191. 'precision' => $this->_receive['Precision'] // 地理位置精度
  192. );
  193. }
  194. return false;
  195. }
  196. /**
  197. * 获取接收链接消息
  198. */
  199. public function getRevLink()
  200. {
  201. if(isset($this->_receive['Title'])){
  202. return array(
  203. 'title' => $this->_receive['Title'], //消息标题
  204. 'description' => $this->_receive['Description'], //消息描述
  205. 'url' => $this->_receive['Url'] //消息链接
  206. );
  207. }
  208. return false;
  209. }
  210. /**
  211. * 获取接收事件类型
  212. * 事件类型如:subscribe(订阅)、unsubscribe(取消订阅)、click
  213. */
  214. public function getRevEvent()
  215. {
  216. if(isset($this->_receive['Event']))
  217. {
  218. return array(
  219. 'event' => strtolower($this->_receive['Event']),
  220. 'key'=> isset($this->_receive['EventKey']) ? $this->_receive['EventKey'] : ''
  221. );
  222. }
  223. return false;
  224. }
  225. /**
  226. * 设置回复文本消息
  227. * @param string $content
  228. * @param string $openid
  229. */
  230. public function text($content='')
  231. {
  232. $textTpl = "
  233. %s
  234. ";
  235. $this->_reply = sprintf($textTpl,
  236. $this->getRevFrom(),
  237. $this->getRevTo(),
  238. Date::getTimeStamp(),
  239. 'text',
  240. $content
  241. );
  242. return $this;
  243. }
  244. /**
  245. * 设置回复音乐信息
  246. * @param string $title
  247. * @param string $desc
  248. * @param string $musicurl
  249. * @param string $hgmusicurl
  250. */
  251. public function music($title, $desc, $musicurl, $hgmusicurl='')
  252. {
  253. $textTpl = '
  254. %s
  255. ';
  256. //
  257. $this->_reply = sprintf($textTpl,
  258. $this->getRevFrom(),
  259. $this->getRevTo(),
  260. Date::getTimeStamp(),
  261. 'music',
  262. $title,
  263. $desc,
  264. $musicurl,
  265. $hgmusicurl
  266. );
  267. return $this;
  268. }
  269. /**
  270. * 回复图文消息
  271. * @param array
  272. */
  273. public function news($data)
  274. {
  275. $count = count($data);
  276. $subText = '';
  277. if($count > 0)
  278. {
  279. foreach($data as $v)
  280. {
  281. $tmpText = '
  282. ';
  283. $subText .= sprintf(
  284. $tmpText, $v['title'],
  285. isset($v['description']) ? $v['description'] : '',
  286. isset($v['picUrl']) ? $v['picUrl'] : '',
  287. isset($v['url']) ? $v['url'] : ''
  288. );
  289. }
  290. }
  291. $textTpl = '
  292. %s
  293. ';
  294. $this->_reply = sprintf(
  295. $textTpl,
  296. $this->getRevFrom(),
  297. $this->getRevTo(),
  298. Date::getTimeStamp(),
  299. $count,
  300. $subText
  301. );
  302. return $this;
  303. }
  304. /**
  305. * 回复消息
  306. * @param array $msg
  307. * @param bool $return
  308. */
  309. public function reply()
  310. {
  311. header('Content-Type:text/xml');
  312. echo $this->_reply;
  313. exit;
  314. }
  315. /**
  316. * 自定义菜单创建
  317. * @param array 菜单数据
  318. */
  319. public function createMenu($data)
  320. {
  321. if(!$this->access_token && !$this->checkAuth()) return false;
  322. $result = curlRequest(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token, $this->jsonEncode($data), 'post');
  323. if($result)
  324. {
  325. $jsonArr = json_decode($result, true);
  326. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  327. else return true;
  328. }
  329. return false;
  330. }
  331. /**
  332. * 自定义菜单查询
  333. */
  334. public function getMenu()
  335. {
  336. if(!$this->access_token && !$this->checkAuth()) return false;
  337. $result = curlRequest(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
  338. if($result)
  339. {
  340. $jsonArr = json_decode($result, true);
  341. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  342. else return $jsonArr;
  343. }
  344. return false;
  345. }
  346. /**
  347. * 自定义菜单删除
  348. */
  349. public function deleteMenu()
  350. {
  351. if(!$this->access_token && !$this->checkAuth()) return false;
  352. $result = curlRequest(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
  353. if($result)
  354. {
  355. $jsonArr = json_decode($result, true);
  356. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  357. else return true;
  358. }
  359. return false;
  360. }
  361. /**
  362. * 获取用户基本信息
  363. * @param string $openid 普通用户的标识,对当前公众号唯一
  364. */
  365. public function getUserInfo($openid)
  366. {
  367. if(!$this->access_token && !$this->checkAuth()) return false;
  368. $result = curlRequest(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
  369. if($result)
  370. {
  371. $jsonArr = json_decode($result, true);
  372. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  373. else return $jsonArr;
  374. }
  375. return false;
  376. }
  377. /**
  378. * 获取关注者列表
  379. * @param string $next_openid 第一个拉取的OPENID,不填默认从头开始拉取
  380. */
  381. public function getUserList($next_openid='')
  382. {
  383. if(!$this->access_token && !$this->checkAuth()) return false;
  384. $result = curlRequest(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
  385. if($result)
  386. {
  387. $jsonArr = json_decode($result, true);
  388. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  389. else return $jsonArr;
  390. }
  391. return false;
  392. }
  393. /**
  394. * 查询分组
  395. */
  396. public function getGroup()
  397. {
  398. if(!$this->access_token && !$this->checkAuth()) return false;
  399. $result = curlRequest(self::API_URL_PREFIX.self::GROUPS_GET_URL.'access_token='.$this->access_token);
  400. if($result)
  401. {
  402. $jsonArr = json_decode($result, true);
  403. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  404. else return $jsonArr;
  405. }
  406. return false;
  407. }
  408. /**
  409. * 创建分组
  410. * @param string $name 分组名字(30个字符以内)
  411. */
  412. public function createGroup($name)
  413. {
  414. if(!$this->access_token && !$this->checkAuth()) return false;
  415. $data = array('group' => array('name' => $name));
  416. $result = curlRequest(self::API_URL_PREFIX.self::GROUPS_CREATE_URL.'access_token='.$this->access_token, $this->jsonEncode($data), 'post');
  417. if($result)
  418. {
  419. $jsonArr = json_decode($result, true);
  420. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  421. else return true;
  422. }
  423. return false;
  424. }
  425. /**
  426. * 修改分组名
  427. * @param int $id 分组id,由微信分配
  428. * @param string $name 分组名字(30个字符以内)
  429. */
  430. public function updateGroup($id, $name)
  431. {
  432. if(!$this->access_token && !$this->checkAuth()) return false;
  433. $data = array('group' => array('id' => $id, 'name' => $name));
  434. $result = curlRequest(self::API_URL_PREFIX.self::GROUPS_UPDATE_URL.'access_token='.$this->access_token, $this->jsonEncode($data), 'post');
  435. if($result)
  436. {
  437. $jsonArr = json_decode($result, true);
  438. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  439. else return true;
  440. }
  441. return false;
  442. }
  443. /**
  444. * 移动用户分组
  445. *
  446. * @param string $openid 用户唯一标识符
  447. * @param int $to_groupid 分组id
  448. */
  449. public function updateGroupMembers($openid, $to_groupid)
  450. {
  451. if(!$this->access_token && !$this->checkAuth()) return false;
  452. $data = array('openid' => $openid, 'to_groupid' => $to_groupid);
  453. $result = curlRequest(self::API_URL_PREFIX.self::GROUPS_MEMBERS_UPDATE_URL.'access_token='.$this->access_token, $this->jsonEncode($data), 'post');
  454. if($result)
  455. {
  456. $jsonArr = json_decode($result, true);
  457. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  458. else return true;
  459. }
  460. return false;
  461. }
  462. /**
  463. * 发送客服消息
  464. * 当用户主动发消息给公众号的时候(包括发送信息、点击自定义菜单clike事件、订阅事件、扫描二维码事件、支付成功事件、用户维权),
  465. * 微信将会把消息数据推送给开发者,开发者在一段时间内(目前为24小时)可以调用客服消息接口,通过POST一个JSON数据包来发送消息给普通用户,在24小时内不限制发送次数。
  466. * 此接口主要用于客服等有人工消息处理环节的功能,方便开发者为用户提供更加优质的服务。
  467. *
  468. * @param string $touser 普通用户openid
  469. */
  470. public function sendCustomMessage($touser, $data, $msgType = 'text')
  471. {
  472. $arr = array();
  473. $arr['touser'] = $touser;
  474. $arr['msgtype'] = $msgType;
  475. switch ($msgType)
  476. {
  477. case 'text': // 发送文本消息
  478. $arr['text']['content'] = $data;
  479. break;
  480. case 'image': // 发送图片消息
  481. $arr['image']['media_id'] = $data;
  482. break;
  483. case 'voice': // 发送语音消息
  484. $arr['voice']['media_id'] = $data;
  485. break;
  486. case 'video': // 发送视频消息
  487. $arr['video']['media_id'] = $data['media_id']; // 发送的视频的媒体ID
  488. $arr['video']['thumb_media_id'] = $data['thumb_media_id']; // 视频缩略图的媒体ID
  489. break;
  490. case 'music': // 发送音乐消息
  491. $arr['music']['title'] = $data['title'];// 音乐标题
  492. $arr['music']['description'] = $data['description'];// 音乐描述
  493. $arr['music']['musicurl'] = $data['musicurl'];// 音乐链接
  494. $arr['music']['hqmusicurl'] = $data['hqmusicurl'];// 高品质音乐链接,wifi环境优先使用该链接播放音乐
  495. $arr['music']['thumb_media_id'] = $data['title'];// 缩略图的媒体ID
  496. break;
  497. case 'news': // 发送图文消息
  498. $arr['news']['articles'] = $data; // title、description、url、picurl
  499. break;
  500. }
  501. if(!$this->access_token && !$this->checkAuth()) return false;
  502. $result = curlRequest(self::API_URL_PREFIX.self::MESSAGE_CUSTOM_SEND_URL.'access_token='.$this->access_token, $this->jsonEncode($arr), 'post');
  503. if($result)
  504. {
  505. $jsonArr = json_decode($result, true);
  506. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  507. else return true;
  508. }
  509. return false;
  510. }
  511. /**
  512. * 获取access_token
  513. */
  514. public function checkAuth()
  515. {
  516. // 从缓存中获取access_token
  517. $cache_flag = 'weixin_access_token';
  518. $access_token = cache($cache_flag);
  519. if($access_token)
  520. {
  521. $this->access_token = $access_token;
  522. return true;
  523. }
  524. // 请求微信服务器获取access_token
  525. $result = curlRequest(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$this->appid.'&secret='.$this->appsecret);
  526. if($result)
  527. {
  528. $jsonArr = json_decode($result, true);
  529. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0))
  530. {
  531. $this->error($jsonArr);
  532. }
  533. else
  534. {
  535. $this->access_token = $jsonArr['access_token'];
  536. $expire = isset($jsonArr['expires_in']) ? intval($jsonArr['expires_in'])-100 : 3600;
  537. // 将access_token保存到缓存中
  538. cache($cache_flag, $this->access_token, $expire, Cache::FILE);
  539. return true;
  540. }
  541. }
  542. return false;
  543. }
  544. /**
  545. * 微信oauth登陆->第一步:用户同意授权,获取code
  546. * 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),
  547. * snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
  548. * 直接在微信打开链接,可以不填此参数。做页面302重定向时候,必须带此参数
  549. *
  550. * @param string $redirect_uri 授权后重定向的回调链接地址
  551. * @param string $scope 应用授权作用域 0为snsapi_base,1为snsapi_userinfo
  552. * @param string $state 重定向后会带上state参数,开发者可以填写任意参数值
  553. */
  554. public function redirectGetOauthCode($redirect_uri, $scope=0, $state='')
  555. {
  556. $scope = ($scope == 0) ? 'snsapi_base' : 'snsapi_userinfo';
  557. $url = self::CONNECT_OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($redirect_uri).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  558. redirect($url);
  559. }
  560. /**
  561. * 微信oauth登陆->第二步:通过code换取网页授权access_token
  562. *
  563. * @param string $code
  564. */
  565. public function getSnsAccessToken($code)
  566. {
  567. $result = curlRequest(self::SNS_OAUTH_ACCESS_TOKEN_URL.'appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code');
  568. if($result)
  569. {
  570. $jsonArr = json_decode($result, true);
  571. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  572. else return $jsonArr;
  573. }
  574. return false;
  575. }
  576. /**
  577. * 微信oauth登陆->第三步:刷新access_token(如果需要)
  578. * 由于access_token拥有较短的有效期,当access_token超时后,可以使用refresh_token进行刷新,
  579. * refresh_token拥有较长的有效期(7天、30天、60天、90天),当refresh_token失效的后,需要用户重新授权。
  580. *
  581. * @param string $refresh_token 填写通过access_token获取到的refresh_token参数
  582. */
  583. public function refershToken($refresh_token)
  584. {
  585. $result = curlRequest(self::SNS_OAUTH_REFRESH_TOKEN_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
  586. if($result)
  587. {
  588. $jsonArr = json_decode($result, true);
  589. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  590. else return $jsonArr;
  591. }
  592. return false;
  593. }
  594. /**
  595. * 微信oauth登陆->第四步:拉取用户信息(需scope为 snsapi_userinfo)
  596. * 如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。
  597. *
  598. * @param string $access_token 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
  599. * @param string $openid 用户的唯一标识
  600. */
  601. public function getSnsUserInfo($access_token, $openid)
  602. {
  603. $result = curlRequest(self::SNS_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
  604. if($result)
  605. {
  606. $jsonArr = json_decode($result, true);
  607. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  608. else return $jsonArr;
  609. }
  610. return false;
  611. }
  612. /**
  613. * 创建二维码ticket
  614. * 每次创建二维码ticket需要提供一个开发者自行设定的参数(scene_id),分别介绍临时二维码和永久二维码的创建二维码ticket过程。
  615. *
  616. * @param int $scene_id 场景值ID,临时二维码时为32位整型,永久二维码时最大值为1000
  617. * @param int $type 二维码类型,0为临时,1为永久
  618. * @param int $expire 该二维码有效时间,以秒为单位。 最大不超过1800。
  619. */
  620. public function createQrcode($scene_id, $type=0, $expire=1800)
  621. {
  622. if(!$this->access_token && !$this->checkAuth()) return false;
  623. $data = array();
  624. $data['action_info'] = array('scene' => array('scene_id' => $scene_id));
  625. $data['action_name'] = ($type == 0 ? 'QR_SCENE' : 'QR_LIMIT_SCENE');
  626. if($type == 0) $data['expire_seconds'] = $expire;
  627. $result = curlRequest(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token, $this->jsonEncode($data), 'post');
  628. if($result)
  629. {
  630. $jsonArr = json_decode($result, true);
  631. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  632. else return $jsonArr;
  633. }
  634. return false;
  635. }
  636. /**
  637. * 通过ticket换取二维码
  638. * 获取二维码ticket后,开发者可用ticket换取二维码图片。请注意,本接口无须登录态即可调用。
  639. * 提醒:TICKET记得进行UrlEncode
  640. * ticket正确情况下,http 返回码是200,是一张图片,可以直接展示或者下载。
  641. * 错误情况下(如ticket非法)返回HTTP错误码404。
  642. *
  643. * @param string $ticket
  644. */
  645. public function getQrcodeUrl($ticket)
  646. {
  647. return self::SHOW_QRCODE_URL.'ticket='.urlencode($ticket);
  648. }
  649. /**
  650. * 记录接口产生的错误日志
  651. */
  652. public function error($data)
  653. {
  654. $this->errCode = $data['errcode'];
  655. $this->errMsg = $data['errmsg'];
  656. Log::info('WEIXIN API errcode:['.$this->errCode.'] errmsg:['.$this->errMsg.']');
  657. }
  658. /**
  659. * 将数组中的中文转换成json数据
  660. * @param array $arr
  661. */
  662. public function jsonEncode($arr) {
  663. $parts = array ();
  664. $is_list = false;
  665. //Find out if the given array is a numerical array
  666. $keys = array_keys ( $arr );
  667. $max_length = count ( $arr ) - 1;
  668. if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
  669. $is_list = true;
  670. for($i = 0; $i if ($i != $keys [$i]) { //A key fails at position check.
  671. $is_list = false; //It is an associative array.
  672. break;
  673. }
  674. }
  675. }
  676. foreach ( $arr as $key => $value ) {
  677. if (is_array ( $value )) { //Custom handling for arrays
  678. if ($is_list)
  679. $parts [] = $this->jsonEncode ( $value ); /* :RECURSION: */
  680. else
  681. $parts [] = '"' . $key . '":' . $this->jsonEncode ( $value ); /* :RECURSION: */
  682. } else {
  683. $str = '';
  684. if (! $is_list)
  685. $str = '"' . $key . '":';
  686. //Custom handling for multiple data types
  687. if (is_numeric ( $value ) && $value $str .= $value; //Numbers
  688. elseif ($value === false)
  689. $str .= 'false'; //The booleans
  690. elseif ($value === true)
  691. $str .= 'true';
  692. else
  693. $str .= '"' . addslashes ( $value ) . '"'; //All other things
  694. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  695. $parts [] = $str;
  696. }
  697. }
  698. $json = implode ( ',', $parts );
  699. if ($is_list)
  700. return '[' . $json . ']'; //Return numerical JSON
  701. return '{' . $json . '}'; //Return associative JSON
  702. }
  703. /**
  704. * 检验签名
  705. */
  706. public function checkSignature()
  707. {
  708. $signature = HttpRequest::getGet('signature');
  709. $timestamp = HttpRequest::getGet('timestamp');
  710. $nonce = HttpRequest::getGet('nonce');
  711. $token = $this->token;
  712. $tmpArr = array($token, $timestamp, $nonce);
  713. sort($tmpArr);
  714. $tmpStr = implode($tmpArr);
  715. $tmpStr = sha1($tmpStr);
  716. return ($tmpStr == $signature ? true : false);
  717. }
  718. /**
  719. * 验证token是否有效
  720. */
  721. public function valid()
  722. {
  723. if($this->checkSignature()) exit(HttpRequest::getGet('echostr'));
  724. }
  725. }
复制代码


智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号