教程目錄
一 流程圖
二 微信測試號申請
三 新建Egret項目
四 微信網頁授權流程
五 微信Web開發者工具
六 Demo下載
一、流程圖
二、微信測試號申請
測試號申請參考之前教程:http://bbs.egret.com/thread-26429-1-1.html
申請微信測試號后,要測試網頁授權,需要設置授權回調頁面域名。
現在我們有了一個可以測試微信授權的賬號。
三、新建Egret項目
新建一個egret項目,里面啥也沒有,只有一個label顯示將要獲取的微信用戶信息。
nickname需要顯示中文,要用到decodeURI。
四、微信網頁授權流程
微信官方文檔:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
我們的demo,php文件主要有以下幾個:
access_token.php 保存獲取到access_token(這里我測試是一直重新獲取access_token,所以沒用到)
HttpUtils.php https請求
index.php 主頁
wechat.php 網頁授權獲取用戶信息
1. index.php (獲取code)
appid:測試微信號的appid
redirect_uri:回調頁面。獲取code后,會跳轉到頁面。
response_type:返回類型
scope:授權類型,靜默授權或用戶授權
state:重定向帶上的State參數,直接填STATE
wechat_redirect:重定向必須帶上
2. wechat.php (code換access_token,拉取用戶信息,重定向到egret)
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
<?php
require_once
"HttpUtils.php"
;
//1.獲取code
$httpUtils =
new
HttpUtils();
$code = $_GET[
"code"
];
if
($code !=
null
){
echo(
"code is have"
);
//2. 通過code換取網頁授權access_token
$url =
"https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx4a14bf95e973b059&secret=af99ce68694f39e2712e7cf7c22fe224&code=$code&grant_type=authorization_code"
;
$res = json_decode($httpUtils->httpGet($url));
$access_token = $res->access_token;
$openid = $res->openid;
$expires_in = $res->expires_in;
$refresh_token = $res->refresh_token;
$scope = $res->scope;
//3. 拉取用戶信息(需scope為 snsapi_userinfo)
$url =
"https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN"
;
$userInfoResult = json_decode($httpUtils->httpGet($url));
echo(
"</br>"
);
echo(
"openid:"
.$userInfoResult->openid.
"</br>"
);
echo(
"nickname:"
.$userInfoResult->nickname.
"</br>"
);
echo(
"sex:"
.$userInfoResult->sex.
"</br>"
);
echo(
"province:"
.$userInfoResult->province.
"</br>"
);
echo(
"city:"
.$userInfoResult->city.
"</br>"
);
echo(
"country:"
.$userInfoResult->country.
"</br>"
);
echo(
"headimgurl:"
.$userInfoResult->headimgurl.
"</br>"
);
echo(
"privilege:"
.$userInfoResult->privilege.
"</br>"
);
echo(
"unionid:"
.$userInfoResult->unionid.
"</br>"
);
//4.重定向
$openid = $userInfoResult->openid;
$nickname = $userInfoResult->nickname;
header(
'Location:[url]http://120.24.188.118/Example/weixin_php_scope/egret/index.html'
.[/url]
"?openid="
.$openid.
"&nickname="
.$nickname);
}
else
{
echo(
"code is null"
);
}
?>
|
拉取用戶信息成功
五、微信Web開發者工具
在pc端測試時,可以用這個工具,具體用法不再贅述。
官方下載地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1455784140
六、Demo下載(含php和egret)
https://files-cdn.cnblogs.com/files/gamedaybyday/Egret4.1.0_WxShouQuanDemo.7z