php 微信開發獲取用戶信息
獲取用戶信息的大致算法是
用戶授權登錄第三方網站,
重點:scope參數:
snsapi_basic 靜默登錄,不需要用戶授權,只能獲取到openid;
snsapi_userinfo ,需要用戶點擊授權,能獲取到openid和所有用戶信息;
第一步:先獲取用戶的code值;
第二步:根據code值去獲取access_token,每次請求的值都不一樣,如果沒有使用,每五分鍾更新一次;
第三步:根據access_token獲取用戶信息;
1.獲取code代碼實現:
getcode.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
if
(isset(
$_SESSION
[
'user'
])){
print_r(
$_SESSION
[
'user'
]);
exit
;
}
$appid
=
'wx1d7c6fcd6131143b3'
;
$scope
=
'snsapi_userinfo'
;
//獲取的方式;
$url
=
'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
.
$appid
.
'&redirect_uri='
.urlencode(
$redirect_url
).
'&response_type=code&scope='
.
$scope
.
'&state=123#wechat_redirect'
;
header(
"Location:"
.
$url
);
|
2、根據code獲取access_token和openid
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
getOpenid.php
<?php
//獲取用戶openid
$appid
=
"your appid"
;
$appsecret
=
"your appsecret"
;
$code
=
$_GET
[
'code'
];
function
getOpenID(
$appid
,
$appsecret
,
$code
){
$appsecret
.
"&code="
.
$code
.
"&grant_type=authorization_code"
;
$weixin
=
file_get_contents
(
$url
);
//通過code換取網頁授權access_token
$jsondecode
=json_decode(
$weixin
);
//對JSON格式的字符串進行編碼
$array
= get_object_vars(
$jsondecode
);
//轉換成數組
$openid
=
$array
[
'openid'
];
//輸出openid
return
$openid
;
}
echo
getOpenID(
$appid
,
$appsecret
,
$code
);
|