백엔드 개발 PHP 튜토리얼 EaglePHP 프레임워크 v2.7을 기반으로 개발된 WeChat 5.0의 가장 포괄적인 최신 API 인터페이스입니다.

EaglePHP 프레임워크 v2.7을 기반으로 개발된 WeChat 5.0의 가장 포괄적인 최신 API 인터페이스입니다.

Jul 25, 2016 am 08:49 AM

코드 소스: http://www.eaglephp.com
적용 플랫폼: window/Linux
종속 프로젝트: EaglePHP 프레임워크

WeChat 5.0 API 기본 인터페이스, 사용자 정의 메뉴 및 고급 인터페이스가 포함되어 있습니다.
1. 사용자 메시지를 받습니다.
2. 사용자에게 답장을 보냅니다.
3. 이벤트 푸시를 수락합니다.
4. 대화 인터페이스 맞춤 메뉴.
5. 음성인식.
6. 고객 서비스 인터페이스.
7. OAuth2.0 웹페이지 인증.
8. 매개변수를 사용하여 QR 코드를 생성합니다.
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. {
  11. private $token > private $appid;
  12. private $appsecret;
  13. private $access_token;
  14. // 接收的資料
  15. private $_ceive = array();
  16. private $_reply = '';
  17. // 介面錯誤碼
  18. private $errCode = '';
  19. // 介面錯誤訊息
  20. private $errMerrMsg = ' ';
  21. // 微信oauth登陸取得code
  22. const CONNECT_OAUTH_AUTHORIZE_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
  23. 微信oauth登陸透過code換取網頁授權access_token
  24. const SNS_OAUTH_ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token?'; const SNS_OAUTH_REFRESH_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?';
  25. // 透過ticket換取二維碼
  26. constdUR_L🎜> 'https://mp.weixin.qq.com/cgi-bin/showqrcode?';
  27. // 微信oauth登陸拉取用戶資訊(需scope為snsapi_userinfo)
  28. const SNS_USERINFO_URL = 'https ://api.weixin.qq.com/sns/userinfo?';
  29. // 請求api前綴
  30. const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin ';
  31. // 自訂選單建立
  32. const MENU_CREATE_URL = '/menu/create?';
  33. // 自訂選單查詢
  34. const MENU_GET_URL = '/menu/ get?';
  35. // 自訂選單刪除
  36. const MENU_DELETE_URL = '/menu/delete?';
  37. // 取得access_token
  38. const AUTH_URL = '/token? grant_type=client_credential&';
  39. // 取得使用者基本資訊
  40. const USER_INFO_URL = '/user/info?';
  41. // 取得追蹤者清單
  42. const USERGET_URL = ' /user/get?';
  43. // 查詢分組
  44. const GROUPS_GET_URL = '/groups/get?';
  45. // 建立分組
  46. const GROUPS_CREATE_URL = '/groupATE_URL = '/group /create?';
  47. // 修改分組名稱
  48. const GROUPS_UPDATE_URL = '/groups/update?';
  49. // 行動用戶分組
  50. congroupst GRPS_MEMBERS_UP/ATE_ /members/update?';
  51. // 傳送客服訊息
  52. const MESSAGE_CUSTOM_SEND_URL = '/message/custom/send?';
  53. // 建立二維碼ticket
  54. const QRCODE_CREATE_URL = '/qrcode/create?';
  55. /**
  56. * 初始化設定資料
  57. * @param array $options
  58. */
  59. public function __construct($options)
  60. this
  61. this
  62. $ ->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 函數> return isset($this->_receive['FromUserName']) ? $this->_receive['FromUserName'] : false;
  98. }
  99. /**
  100. * 取得接收訊息建立時間 (整型)
  101. */
  102. public function getRevCTime()
  103. {
  104. return isset($this->_receive['CreateTime']) ? $this->_receive['CreateTime'] : false;
  105. }
  106. }
  107. /**
  108. * 取得接收訊息類型(text、image、voice、video、location、link、event)
  109. */
  110. public function getRevType()
  111. {
  112. return isset($this->_receive['MsgType']) ? $this->_receive[' MsgType'] : false;
  113. }
  114. /**
  115. * 取得接收訊息編號
  116. */
  117. public function getRevId()
  118. {
  119. return isset($this->_reive
  120. {
  121. return isset($this->_reive
  122. {
  123. return isset($this->_rece. ['MsgId']) ? $this->_receive['MsgId'] : false;
  124. }
  125. /** * 取得接收訊息文字 * 透過語音辨識接口,使用者發送的語音,將會同時給予語音辨識出的文字內容。(서비스 계정의 고급 인터페이스 권한을 신청해야 합니다.)
  126. */
  127. public function getRevText()
  128. {
  129. if(isset($this->_receive['Content'] )) return Trim( $this->_receive['Content']);
  130. elseif(isset($this->_receive['Recognition'])) return Trim($this->_receive['인식' ']);
  131. else return false;
  132. }
  133. /**
  134. * 사진 메시지 받기 및 받기
  135. */
  136. 공개 함수 getRevImage()
  137. {
  138. if(isset ($this-> ;_receive['PicUrl'])){
  139. return array(
  140. 'picUrl' => $this->_receive['PicUrl'], //사진 링크
  141. ' mediaId' => $this->_receive['MediaId'] //사진 메시지 미디어 ID, 멀티미디어 파일 다운로드 인터페이스를 호출하여 데이터를 가져올 수 있습니다
  142. );
  143. }
  144. return false;
  145. }
  146. /**
  147. * 음성 메시지 받기 및 받기
  148. */
  149. 공개 함수 getRevVoice()
  150. {
  151. if(isset($this->_receive['MediaId'] )){
  152. return array(
  153. 'mediaId' => $this->_receive['MediaId'], //음성 메시지 미디어 ID, 멀티미디어 파일 다운로드 인터페이스를 호출하여 데이터를 가져올 수 있습니다.
  154. 'format' => $this->_receive['Format'] //amr, speex 등의 음성 형식
  155. );
  156. }
  157. return false;
  158. }
  159. / **
  160. * 영상 메시지 받기 및 받기
  161. */
  162. 공개 함수 getRevVideo()
  163. {
  164. if(isset($this->_receive['MediaId']) ){
  165. return array(
  166. ' mediaId' => $this->_receive['MediaId'], //비디오 메시지 미디어 ID, 멀티미디어 파일 다운로드 인터페이스를 호출하여 데이터를 가져올 수 있습니다.
  167. 'thumbMediaId' => $this->_receive['ThumbMediaId'] //동영상 메시지 썸네일의 미디어 ID, 멀티미디어 파일 다운로드 인터페이스를 호출하여 데이터를 가져올 수 있습니다.
  168. );
  169. }
  170. false 반환;
  171. }
  172. /**
  173. * 사용자의 지리적 위치 가져오기
  174. */
  175. 공용 함수 getRevLocation()
  176. {
  177. if(isset($this->_receive['Location_X'])){
  178. return array(
  179. 'locationX' => $this->_receive['Location_X'], //위치 위치 차원
  180. 'locationY' => $this->_receive['Location_Y'], //위치 위치 경도
  181. 'scale' => $this->_receive['Scale'], // 지도 확대/축소 크기
  182. 'label' => $this->_receive['Label'] //지리적 위치 정보
  183. );
  184. }
  185. //보고용 API를 공개한 공개 지리적 위치 계정은 사용자가 팔로우 후 공식 계정 세션에 진입하면 공식 계정의 지리적 위치 사용이 허용되는지 확인하는 팝업 상자가 사용자에게 표시됩니다.
  186. //팝업창은 팔로우 후 한 번만 나타납니다. 향후 공식 계정 상세 페이지에서 작업하실 수 있습니다.
  187. elseif(isset($this->_receive['Latitude']))
  188. {
  189. return array(
  190. 'latitude' => $this->_receive['Latitude'] , //지리적 위치 위도
  191. '경도' => $this->_receive['경도'], //지리적 위치 경도
  192. '정밀도' => $this->_receive['정밀도' '] // 위치정보 정확도
  193. );
  194. }
  195. return false;
  196. }
  197. /**
  198. * 링크 메시지 수신
  199. */
  200. 공개 함수 getRevLink( )
  201. {
  202. if(isset($this->_receive['Title'])){
  203. return array(
  204. 'title' => $this->_receive['Title ' ], //메시지 제목
  205. '설명' => $this->_receive['Description'], //메시지 설명
  206. 'url' => $this->_receive['Url' ] //메시지 링크
  207. );
  208. }
  209. return false;
  210. }
  211. /**
  212. * 수신 이벤트 유형 가져오기
  213. * 이벤트 유형: 구독, 구독 취소, 클릭
  214. */
  215. 공용 함수 getRevEvent()
  216. {
  217. if(isset($this->_receive['Event']))
  218. {
  219. return array(
  220. 'event' => strtolower($this-> _receive ['이벤트']),
  221. 'key'=> isset($this->_receive['EventKey']) ? $this->_receive['EventKey'] : ''
  222. ) ;
  223. }
  224. false 반환;
  225. }
  226. /**
  227. * 답장 문자 메시지 설정
  228. * @param string $content
  229. * @param string $openid
  230. */
  231. 공개 함수 텍스트($content='')
  232. {
  233. $textTpl = "
  234. %s
  235. Content> ;
  236. ";
  237. $this->_reply = sprintf($textTpl,
  238. $ this->getRevFrom(),
  239. $this->getRevTo(),
  240. Date::getTimeStamp(),
  241. 'text',
  242. $content
  243. );
  244. return $this;
  245. }
  246. /**
  247. * 답글 음악 정보 설정
  248. * @param string $title
  249. * @param string $desc
  250. * @param string $musicurl
  251. * @param string $hgmusicurl
  252. */
  253. 공개 기능 음악($title, $desc, $musicurl, $hgmusicurl='')
  254. {
  255. $textTpl = '
  256. %s
  257. <음악>
  258. <제목>
  259. <설명>< 설명>
  260. ';
  261. //
  262. $this->_reply = sprintf($textTpl,
  263. $this->getRevFrom(),
  264. $this->getRevTo(),
  265. Date::getTimeStamp(),
  266. ' music',
  267. $title,
  268. $desc,
  269. $musicurl,
  270. $hgmusicurl
  271. );
  272. return $this;
  273. }
  274. /**
  275. * 그래픽 메시지에 응답
  276. * @param array
  277. */
  278. 공개 함수 뉴스($data)
  279. {
  280. $count = count($data);
  281. $subText = '';
  282. if( $ 개수 > 0)
  283. {
  284. foreach($data as $v)
  285. {
  286. $tmpText = '
  287. <제목>
  288. <설명>
  289. <[CDATA[%s] ] >
  290. ';
  291. $subText . = sprintf(
  292. $tmpText, $v['title'],
  293. isset($v['description']) ? $v['description'] : '',
  294. isset($v [ 'picUrl']) ? $v['picUrl'] : '',
  295. isset($v['url']) ? $v['url'] : ''
  296. );
  297. }
  298. }
  299. $textTpl = '
  300. %s文章>
  301. ';
  302. $this->_reply = sprintf(
  303. $textTpl,
  304. $this->getRevFrom(),
  305. $this->getRevTo() ,
  306. Date::getTimeStamp(),
  307. $count,
  308. $subText
  309. );
  310. return $this;
  311. }
  312. /**
  313. * 回覆訊息
  314. * @param array $msg
  315. * @param bool $return
  316. */
  317. public function reply()
  318. {
  319. header('Contentd. -Type:text/xml');
  320. echo $this->_reply;
  321. exit;
  322. }
  323. /**
  324. * 自訂選單建立
  325. * @param array 選單資料
  326. */
  327. 公用函數createMenu($data)
  328. {
  329. if(!$this->access_token && !$this ->checkAuth()) return false;
  330. $result = curlRequest(self::API_URL_PREFIX.URL_PREFIX. ::MENU_CREATE_URL.'access_token='.$this->access_token, $this->jsonEncode( $data), 'post');
  331. if($result)
  332. {
  333. $jsonArr = json_decode( $result, true);
  334. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  335. else return true;
  336. }
  337. return false;
  338. }
  339. /**
  340. * 自訂選單查詢
  341. */
  342. public function getMe( > {
  343. if(!$this->access_token && !$this->checkAuth()) return false;
  344. $result = curlRequest(self::API_URL_PREFIX.self::MENU_GET_URLken. '.$this->access_token);
  345. if($result)
  346. {
  347. $jsonArr = json_decode($result, true);
  348. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  349. 否則回傳 $jsonArr;
  350. }
  351. 回傳false;
  352. }
  353. /**
  354. * 自訂選單刪除
  355. */
  356. public function deleteMenu()
  357. {
  358. if(!$this->access_token & acc $this->checkAuth()) return false;
  359. $result = curlRequest(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
  360. if($this->access_token); {
  361. $jsonArr = json_decode($result, true);
  362. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  363. 否則回傳true;
  364. }
  365. 回傳false;
  366. }
  367. /**
  368. * 取得使用者基本資訊
  369. * @param string $openid 一般使用者的標識,對目前公眾號唯一
  370. */
  371. public function getUserInfo($openid)
  372. {
  373. if(!$this->access_token && !$this->checkAuth()) return false;
  374. $resultAuth()) return false;
  375. $result =curlRequest(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
  376. if($result)
  377. {
  378. $jsonArrsonArr = json_decode($result, true);
  379. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr );
  380. else return $jsonArr;
  381. }
  382. return false;
  383. }
  384. /**
  385. * 取得追蹤者清單
  386. * @param string $next_openid 第一個拉取的OPENID,不填預設從頭開始拉取
  387. */ ($next_openid='')
  388. {
  389. if(!$this->access_token && !$this->checkAuth()) return false;
  390. $ result =curlRequest(self::IX_URL_PREF21 .self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
  391. if($result)
  392. {
  393. $jsonArr = json_decode($resr );
  394. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  395. 否則回傳 $jsonArr;
  396. }
  397. return false;
  398. }
  399. /* *
  400. * 查詢分組
  401. */
  402. public function getGroup()
  403. {
  404. if(!$this->access_token & access! $this->checkAuth()) return false;
  405. $result = curlRequest(self::API_URL_PREFIX.self::GROUPS_GET_URL.'access_token='.$this->access_tokenPS_GET_URL.'access_token='.$this->access_token);
  406. if($ result)
  407. {
  408. $jsonArr = json_decode($result , true);
  409. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  410. 否則回傳$jsonArr;
  411. }
  412. 回傳false; }
  413. /**
  414. * 그룹 생성
  415. * @param string $name 그룹명(30자 이내)
  416. */
  417. 공개 함수 createGroup($name)
  418. {
  419. if(!$this->access_token && !$this-> checkAuth())는 false를 반환합니다.
  420. $data = array('group' => array('name' => $name));
  421. $result =curlRequest(self::API_URL_PREFIX.self:: GROUPS_CREATE_URL.'access_token='.$this->access_token, $this->jsonEncode($data), 'post');
  422. if($result)
  423. {
  424. $jsonArr = json_decode( $result, true);
  425. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr) ;
  426. else 반환 true;
  427. }
  428. false 반환;
  429. }
  430. /**
  431. * 그룹명 수정
  432. * @param int $id 위챗에서 할당한 그룹 아이디
  433. * @param string $name 그룹명(30자 이내)
  434. */
  435. 공용 함수 updateGroup($ id, $name)
  436. {
  437. if(!$this->access_token && !$this->checkAuth()) return false;
  438. $data = array('group' = > array('id' => $id, 'name' => $name));
  439. $result =curlRequest(self::API_URL_PREFIX.self::GROUPS_UPDATE_URL.'access_token='.$this- >access_token, $this->jsonEncode($data), 'post');
  440. if($result)
  441. {
  442. $jsonArr = json_decode($result, true);
  443. if (!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  444. else return true;
  445. }
  446. false 반환;
  447. }
  448. /**
  449. * 모바일 사용자 그룹
  450. *
  451. * @param string $openid 사용자 고유 식별자
  452. * @param int $to_groupid 그룹 ID
  453. */
  454. 공개 함수 updateGroupMembers($openid, $to_groupid)
  455. {
  456. if(!$ this->access_token && !$this->checkAuth()) return false;
  457. $data = array('openid' => $openid, 'to_groupid' => $to_groupid);
  458. $result = curRequest(self::API_URL_PREFIX.self::GROUPS_MEMBERS_UPDATE_URL.'access_token='.$this->access_token, $this->jsonEncode($data), 'post');
  459. if( $result)
  460. {
  461. $jsonArr = json_decode($result, true);
  462. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  463. else return true;
  464. }
  465. return false;
  466. }
  467. / **
  468. * 发送客服消息
  469. * 当用户主动发消息给公众号的时候(包括发送信息、点击自定义菜单clike事件、订阅事件、扫描二维码事件、支付成功事件、用户维权),
  470. * 微信将会把消息数据推送给开发者,开发者在一段时间内(目前为24小时)可以调用客服消息接口,통过POST一个JSON数据包来发送消息给普일반적인사용户,24小时内不限发送次数。
  471. * 정말 좋아요.
  472. *
  473. * @param string $touser 일반 사용자 openid
  474. */
  475. 공개 함수 sendCustomMessage($touser, $data, $msgType = 'text')
  476. {
  477. $arr = array();
  478. $arr['touser'] = $touser;
  479. $arr['msgtype'] = $msgType;
  480. 스위치($msgType)
  481. {
  482. 케이스 ' text': // 문자 메시지 보내기
  483. $arr['text']['content'] = $data
  484. break;
  485. case 'image': // 이미지 메시지 보내기
  486. $arr['image']['media_id'] = $data;
  487. break;
  488. case 'voice': // 음성 메시지 보내기
  489. $arr['voice'][' media_id'] = $data;
  490. break;
  491. case 'video': // 영상 메시지 보내기
  492. $arr['video']['media_id'] = $data['media_id' ]; // 전송된 동영상의 미디어 ID
  493. $arr['video']['thumb_media_id'] = $data['thumb_media_id'] // 동영상 썸네일의 미디어 ID
  494. break;
  495. 케이스 'music': //음악 메시지 보내기
  496. $arr['music']['title'] = $data['title'];//음악 제목
  497. $arr['music' ]['description'] = $data['description'];//음악 설명
  498. $arr['music']['musicurl'] = $data['musicurl'];//음악 링크
  499. $arr['music']['hqmusicurl'] = $data['hqmusicurl'];// 고품질 음악 링크, Wi-Fi 환경에서는 이 링크를 사용하여 음악을 재생하는 것을 선호합니다
  500. $arr['music'] ['thumb_media_id' ] = $data['title'];//썸네일의 미디어 ID
  501. break;
  502. case 'news': //그래픽 메시지 보내기
  503. $arr['news' ][ 'articles'] = $data; // 제목, 설명, URL, picurl
  504. break;
  505. }
  506. if(!$this->access_token && !$this-> checkAuth( )) return false;
  507. $result =curlRequest(self::API_URL_PREFIX.self::MESSAGE_CUSTOM_SEND_URL.'access_token='.$this->access_token, $this->jsonEncode($arr) , ' post');
  508. if($result)
  509. {
  510. $jsonArr = json_decode($result, true);
  511. if(!$jsonArr || (isset($jsonArr['errcode) '] ) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  512. else return true;
  513. }
  514. return false;
  515. }
  516. /**
  517. * access_token 받기
  518. */
  519. 공개 함수 checkAuth()
  520. {
  521. // 캐시에서 access_token 가져오기
  522. $cache_flag = 'weixin_access_token';
  523. $access_token = 캐시($cache_flag);
  524. if($access_token)
  525. {
  526. $this->access_token = $access_token;
  527. return true;
  528. }
  529. // access_token을 얻기 위해 WeChat 서버에 요청
  530. $result = curRequest(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$this->appid.'&secret= '.$ this->appsecret);
  531. if($result)
  532. {
  533. $jsonArr = json_decode($result, true);
  534. if(!$jsonArr || (isset($ jsonArr[' errcode']) && $jsonArr['errcode'] > 0))
  535. {
  536. $this->error($jsonArr);
  537. }
  538. else
  539. {
  540. $this->access_token = $jsonArr['access_token'];
  541. $expire = isset($jsonArr['expires_in']) ? intval($jsonArr['expires_in'])-100 : 3600;
  542. // access_token을 캐시에 저장
  543. 캐시($cache_flag, $this->access_token, $expire, Cache::FILE)
  544. return true;
  545. }
  546. }
  547. return false;
  548. }
  549. /**
  550. * WeChat oauth 로그인-> 1단계: 사용자가 승인에 동의하고 코드를 얻습니다
  551. * 애플리케이션 승인 범위, snsapi_base (인증 페이지가 뜨지 않고 바로 점프하여 사용자의 openid만 알 수 있습니다),
  552. * snsapi_userinfo (인증 페이지가 뜨면 openid를 통해 닉네임, 성별, 위치를 알 수 있습니다. 또한, 해당 사용자를 팔로우하지 않더라도 해당 사용자가 승인하는 한 해당 정보를 계속 얻을 수 있습니다.)
  553. * 위챗에서 직접 링크를 열면 이 매개변수를 입력할 필요가 없습니다.302 페이지 리다이렉션을 할 때 이 파라미터를 가져와야 합니다
  554. *
  555. * @param string $redirect_uri 인증 후 리다이렉션을 위한 콜백 링크 주소
  556. * @param string $scope 애플리케이션 인증 범위 0은 snsapi_base, 1 For snsapi_userinfo
  557. * @param string $state, 상태 매개변수는 리디렉션 후에 포함됩니다. 개발자는 모든 매개변수 값을 입력할 수 있습니다
  558. */
  559. 공개 함수 리디렉션GetOauthCode($redirect_uri, $scope=0, $state= '')
  560. {
  561. $scope = ($scope == 0) ? 'snsapi_base' : 'snsapi_userinfo';
  562. $url = self::CONNECT_OAUTH_AUTHORIZE_URL.'appid='.$this-> appid.'&redirect_uri='.urlencode($redirect_uri).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
  563. 리디렉션($url);
  564. }
  565. /**
  566. * WeChat oauth 로그인-> 2단계: 웹페이지 인증 access_token 코드 교환
  567. *
  568. * @param string $code
  569. */
  570. 공개 함수 getSnsAccessToken($code)
  571. {
  572. $result =curlRequest(self::SNS_OAUTH_ACCESS_TOKEN_URL.'appid='.$this ->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code');
  573. if($result)
  574. {
  575. $jsonArr = json_decode($result, true);
  576. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($ jsonArr);
  577. else return $jsonArr;
  578. }
  579. return false;
  580. }
  581. /**
  582. * WeChat oauth 로그인-> 3단계: access_token 새로 고침(필요한 경우)
  583. * access_token은 유효 기간이 짧기 때문에 access_token 시간이 초과되면 새로 고침을 위해 Refresh_token을 사용할 수 있습니다.
  584. * Refresh_token에는 긴 유효 기간 긴 유효 기간(7일, 30일, 60일, 90일), Refresh_token이 만료되면 사용자는 다시 인증해야 합니다.
  585. *
  586. * @param string $refresh_token access_token을 통해 얻은 Refresh_token 매개변수를 입력하세요
  587. */
  588. 공개 함수 ReferhToken($refresh_token)
  589. {
  590. $result =curlRequest(self::SNS_OAUTH_REFRESH_TOKEN_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
  591. if( $result)
  592. {
  593. $jsonArr = json_decode($result, true);
  594. if(!$jsonArr || (isset($jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  595. else return $jsonArr;
  596. }
  597. return false;
  598. }
  599. /**
  600. * WeChat oauth login-> 4단계: 사용자 정보 가져오기(범위는 snsapi_userinfo여야 함)
  601. * 웹페이지 인증 범위가 snsapi_userinfo인 경우 개발자는 이때 access_token 및 openid를 통해 사용자 정보를 가져올 수 있습니다. .
  602. *
  603. * @param string $access_token 웹 페이지 인증 인터페이스 호출 인증서, 참고: 이 access_token은 기본적으로 지원되는 access_token과 다릅니다.
  604. * @param string $openid 사용자의 고유 식별자
  605. */
  606. 공개 함수 getSnsUserInfo($access_token, $openid)
  607. {
  608. $result =curlRequest(self::SNS_USERINFO_URL.'access_token='.$access_token.'&openid=' .$openid);
  609. if($result)
  610. {
  611. $jsonArr = json_decode($result, true);
  612. if(!$jsonArr || (isset($jsonArr['errcode') ]) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  613. else return $jsonArr;
  614. }
  615. return false;
  616. }
  617. /**
  618. * QR코드 티켓 생성
  619. * QR코드 티켓을 생성할 때마다 개발자가 설정한 매개변수(scene_id)를 제공해야 하며, 임시 QR코드와 영구 QR코드 생성 방법을 각각 소개하겠습니다. . 티켓 프로세스.
  620. *
  621. * @param int $scene_id 장면 값 ID, 임시 QR 코드의 32비트 정수, 영구 QR 코드의 최대값은 1000
  622. * @param int $type QR 코드 유형, 0 임시, 1은 영구
  623. * @param int $expire QR 코드의 유효 시간(초)입니다. 최대 수는 1800을 초과하지 않습니다.
  624. */
  625. 공개 함수 createQrcode($scene_id, $type=0, $expire=1800)
  626. {
  627. if(!$this ->access_token && !$this->checkAuth()) return false;
  628. $data = array();
  629. $data['action_info'] = array('scene' => array('scene_id' => $scene_id));
  630. $data['action_name'] = ($type == 0 ? 'QR_SCENE' : 'QR_LIMIT_SCENE');
  631. if($type == 0 ) $data['expire_seconds'] = $expire;
  632. $result =curlRequest(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token, $this-> jsonEncode($data), 'post');
  633. if($result)
  634. {
  635. $jsonArr = json_decode($result, true);
  636. if(!$jsonArr || (isset( $jsonArr['errcode']) && $jsonArr['errcode'] > 0)) $this->error($jsonArr);
  637. else return $jsonArr;
  638. }
  639. return false;
  640. }
  641. /**
  642. * 티켓을 QR 코드로 교환
  643. * QR 코드 티켓을 획득한 후 개발자는 티켓을 QR 코드로 교환할 수 있습니다. 영상. 이 인터페이스는 로그인하지 않고도 호출할 수 있습니다.
  644. * 알림: UrlEncode TICKET을 기억하세요
  645. * 티켓이 올바른 경우 http 반환 코드는 200이며, 이는 사진이며 직접 표시하거나 다운로드할 수 있습니다.
  646. * 오류 상황(예: 불법 티켓)에서는 HTTP 오류 코드 404를 반환합니다.
  647. *
  648. * @param string $ticket
  649. */
  650. 공개 함수 getQrcodeUrl($ticket)
  651. {
  652. return self::SHOW_QRCODE_URL.'ticket='.urlencode($ticket );
  653. }
  654. /**
  655. * 인터페이스에서 생성된 오류 로그를 기록합니다
  656. */
  657. 공용 함수 오류($data)
  658. {
  659. $this->errCode = $data[ 'errcode'];
  660. $this->errMsg = $data['errmsg'];
  661. Log::info('WEIXIN API errcode:['.$this->errCode.'] errmsg: ['.$this->errMsg.']');
  662. }
  663. /**
  664. * 배열의 중국어를 json 데이터로 변환
  665. * @param array $arr
  666. */
  667. 공개 함수 jsonEncode($arr) {
  668. $parts = array ();
  669. $is_list = false;
  670. //주어진 배열이 숫자 배열인지 확인
  671. $keys = array_keys ( $arr );
  672. $max_length = count ( $arr ) - 1;
  673. if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //첫 번째 키가 0이고 마지막 키인지 확인 길이 - 1
  674. $is_list = true;
  675. for($i = 0; $i < count ( $keys ); $i ) { //각 키가 해당 위치에 해당하는지 확인
  676. if ($i != $keys [$i]) { //위치 확인 시 키가 실패합니다.
  677. $is_list = false; //연관배열입니다.
  678. break;
  679. }
  680. }
  681. }
  682. foreach ( $arr as $key => $value ) {
  683. if (is_array ( $ value )) { //배열에 대한 사용자 정의 처리
  684. if ($is_list)
  685. $parts [] = $this->jsonEncode ( $value ); /* :재귀: */
  686. else
  687. $parts [] = '"' . $key . '":' . $this->jsonEncode ( $value ); /* :RECURSION: */
  688. } else {
  689. $str = '';
  690. if (! $is_list)
  691. $str = '"' . $key . '":';
  692. //여러 데이터 유형에 대한 사용자 정의 처리
  693. if (is_numeric ( $value ) && $value<2000000000)
  694. $str .= $value; //숫자
  695. elseif ($value === false)
  696. $str .= 'false'; //부울
  697. elseif ($value === true)
  698. $str .= 'true';
  699. else
  700. $str .= '"' .addlashes( $value ) . '" '; //기타 모든 것
  701. // :TODO: 주의해야 할 데이터 유형이 더 있나요? (객체?)
  702. $parts [] = $str;
  703. }
  704. }
  705. $json = implode ( ',', $parts );
  706. if ($is_list)
  707. 반품 '[' . $json . ']'; //숫자 JSON 반환
  708. '{' 반환. $json . '}'; //연관 JSON 반환
  709. }
  710. /**
  711. * 서명 확인
  712. */
  713. 공개 함수 checkSignature()
  714. {
  715. $signature = HttpRequest::getGet(' 서명');
  716. $timestamp = HttpRequest::getGet('timestamp');
  717. $nonce = HttpRequest::getGet('nonce');
  718. $token = $this-> 토큰;
  719. $tmpArr = 배열($token, $timestamp, $nonce);
  720. sort($tmpArr);
  721. $tmpStr = implode($tmpArr);
  722. $tmpStr = sha1($ tmpStr);
  723. return ($tmpStr == $signature ? true : false);
  724. }
  725. /**
  726. * 토큰이 유효한지 확인
  727. */
  728. 공개 함수 유효 ()
  729. {
  730. if($this->checkSignature())exit(HttpRequest::getGet('echostr'));
  731. }
  732. }
제제대码


본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Laravel의 플래시 세션 데이터로 작업합니다 Laravel의 플래시 세션 데이터로 작업합니다 Mar 12, 2025 pm 05:08 PM

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 Mar 14, 2025 am 11:42 AM

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Mar 12, 2025 pm 05:09 PM

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> ​​'Hello World', 'github.com'=> ​​[ 'foo'=> 'bar'], 'forge.laravel.com'=>

Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Mar 13, 2025 pm 12:08 PM

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

PHP에서 늦은 정적 결합의 개념을 설명하십시오. PHP에서 늦은 정적 결합의 개념을 설명하십시오. Mar 21, 2025 pm 01:33 PM

기사는 PHP 5.3에 도입 된 PHP의 LSB (Late STATIC BING)에 대해 논의하여 정적 방법의 런타임 해상도가보다 유연한 상속을 요구할 수있게한다. LSB의 실제 응용 프로그램 및 잠재적 성능

프레임 워크 사용자 정의/확장 : 사용자 정의 기능을 추가하는 방법. 프레임 워크 사용자 정의/확장 : 사용자 정의 기능을 추가하는 방법. Mar 28, 2025 pm 05:12 PM

이 기사에서는 프레임 워크에 사용자 정의 기능 추가, 아키텍처 이해, 확장 지점 식별 및 통합 및 디버깅을위한 모범 사례에 중점을 둡니다.

프레임 워크 보안 기능 : 취약점 보호. 프레임 워크 보안 기능 : 취약점 보호. Mar 28, 2025 pm 05:11 PM

기사는 입력 유효성 검사, 인증 및 정기 업데이트를 포함한 취약점을 방지하기 위해 프레임 워크의 필수 보안 기능을 논의합니다.

See all articles