根据文档说明,网页授权流程分为四步。这里主要说下其中的三步,
第一步:用户同意授权,获取code。
首先是要有一个认证的微信公众号,进入 公众号设置/功能设置/网页授权域名,填
入授权回调接口域名。
前端页面js代码,
var appID = “xxx”; // 公众号AppID
var redirectUri = “http://xxx/oauth2.php”; // 授权接口地址
var state = “xxx”; // 状态标识(用于项目拓展)
if(openid == null || openid == undefined || openid == ‘’){ // 通过判断地址参数是否有
openid来确定是否要跳转授权
var strUrl = “https://open.weixin.qq.com/connect/oauth2/authorize?appid=” +
appID + “&redirect_uri=” + redirectUri +
“&response_type=code&scope=snsapi_userinfo&state=” + state +
“#wechat_redirect”;
window.location.href = strUrl;
}
会弹出微信授权页面(如果只是获取用户openid,把scope设为snsapi_base,就会静默授
权)。
如果出现10003错误代码,要检查公众号回调域名配置。
第二步:通过code换取网页授权access_token。
接口代码,
$appId = ‘xxx’; // 公众号AppId
$appSecret = ‘xxx’; // 公众号AppSecret
c
o
d
e
=
code =
code = _GET[‘code’];
u
r
l
=
"
h
t
t
p
s
:
/
/
a
p
i
.
w
e
i
x
i
n
.
q
q
.
c
o
m
/
s
n
s
/
o
a
u
t
h
2
/
a
c
c
e
s
s
t
o
k
e
n
?
a
p
p
i
d
=
url = "https://api.weixin.qq.com/sns/oauth2/access_token? appid=
url = "https://api.weixin.qq.com/sns/oauth2/accesstoken?appid=appId&secret=KaTeX parse error: Expected 'EOF', got '&' at position 10: appSecret&̲code= {code}&grant_type=authorization_code";
这一步取到网页授权access_token的同时,也获取到了openid。
第三步:刷新access_token。
第四步:拉取用户信息(需scope为 snsapi_userinfo)。
通过第二步的access_token和openid拉取用户信息,接口代码,
a
=
f
i
l
e
g
e
t
c
o
n
t
e
n
t
s
(
a = file_get_contents(
a = filegetcontents(url);
j
s
o
n
=
(
a
r
r
a
y
)
j
s
o
n
d
e
c
o
d
e
(
json=(array)json_decode(
json=(array)jsondecode(a);
if(!isset(KaTeX parse error: Expected '}', got 'EOF' at end of input: …rcode'])){ openid =
j
s
o
n
[
′
o
p
e
n
i
d
′
]
;
json['openid'];
json[′openid′]; url =“https://api.weixin.qq.com/sns/userinfo?
access_token=”.KaTeX parse error: Expected 'EOF', got '&' at position 23: …ccess_token']."&̲openid=".json[‘openid’];
a
=
f
i
l
e
g
e
t
c
o
n
t
e
n
t
s
(
a = file_get_contents(
a = filegetcontents(url);
j
s
o
n
=
(
a
r
r
a
y
)
j
s
o
n
d
e
c
o
d
e
(
json = (array)json_decode(
json = (array)jsondecode(a);
n
i
c
k
n
a
m
e
=
nickname =
nickname = json[‘nickname’];
h
e
a
d
i
m
g
u
r
l
=
headimgurl =
headimgurl = json[‘headimgurl’];
// 追加用户信息(如:openid、昵称、头像等)地址参数跳回前端页面
header(“Location:http://html5.rockstudio.cn/Demo/weixin/oauthDemo/index.html?
openid=KaTeX parse error: Expected 'EOF', got '&' at position 7: openid&̲nickname=nickname&headimgurl=$headimgurl”);
}
当然如果项目有安全考虑,可以自行加入token加密参数(如md5等)。
BTW
1、为了方便接口拓展,使用state参数作为项目的标示,这样就可以多个项目调用同一
个接口,
s
t
a
t
e
=
state =
state = _GET[‘state’];
// …
switch($state){
case ‘project1’:
// …
break;
case ‘project2’:
// …
break;
case ‘project3’:
// …
break;
default:
echo “ERROR”;
}
2、通过用cookie记录openid等信息,可以避免用户二次授权的情况。这里前端以轻为
主,不使用cookie功能。如有这个需求看下这篇文章《用cookie解决新版微信中H5页面底
部白条问题》。
3、由于用户昵称是通过地址参数传递到前端,如果昵称里有emoji表情,会出现乱码
的情况。可以通过php的json_decode和json_encode函数给参数编码。
作者:高飞家的猫
来源:CSDN
原文:https://blog.csdn.net/gaofei880219/article/details/80309222?
utm_source=copy
版权声明:本文为博主原创文章,转载请附上博文链接!
2325

被折叠的 条评论
为什么被折叠?



