//***方法一
獲取code
https://open.weixin.qq.com/connect/oauth2/authorize?appid=這里是你的公眾號的APPID&redirect_uri=http://www.xx.com/getcode&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect
用戶點擊確認登錄,自動跳轉下面地址得到code
http://www.xx.com/getcode 這個是你自己的跳轉地址
http://www.xx.com/getcode?code=0064f7afef7af7b395147bfe8b51f7bf&state=123
后面的這個 ?code=……123 是微信自動跳轉添加的,不是你自己加的
下面是PHP語言,寫在getcode這個頁面里
1
2
3
4
5
|
$code
=
$_GET
[
'code'
];
//獲取code
$weixin
=
file_get_contents
(
"https://api.weixin.qq.com/sns/oauth2/access_token?appid=這里是你的APPID&secret=這里是你的SECRET&code="
.
$code
.
"&grant_type=authorization_code"
);//通過code換取網頁授權access_token
$jsondecode
= json_decode(
$weixin
);
//對JSON格式的字符串進行編碼
$array
= get_object_vars(
$jsondecode
);
//轉換成數組
$openid
=
$array
[
'openid'
];
//輸出openid
|
//***方法二
$appid
=
"公眾號在微信的appid"
;
$secret
=
"公眾號在微信的app secret"
;
$code
=
$_GET
[
"code"
];
$get_token_url
=
'https://api.weixin.qq.com/sns/oauth2/access_token?appid='
.
$appid
.
'&secret='
.
$secret
.
'&code='
.
$code
.
'&grant_type=authorization_code'
;
$ch
= curl_init();
curl_setopt(
$ch
,CURLOPT_URL,
$get_token_url
);
curl_setopt(
$ch
,CURLOPT_HEADER,0);
curl_setopt(
$ch
, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt(
$ch
, CURLOPT_CONNECTTIMEOUT, 10);
$res
= curl_exec(
$ch
);
curl_close(
$ch
);
$json_obj
= json_decode(
$res
,true);
//根據openid和access_token查詢用戶信息
$access_token
=
$json_obj
[
'access_token'
];
$openid
=
$json_obj
[
'openid'
];
$get_user_info_url
=
'https://api.weixin.qq.com/sns/userinfo?access_token='
.
$access_token
.
'&openid='
.
$openid
.
'&lang=zh_CN'
;
$ch
= curl_init();
curl_setopt(
$ch
,CURLOPT_URL,
$get_user_info_url
);
curl_setopt(
$ch
,CURLOPT_HEADER,0);
curl_setopt(
$ch
, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt(
$ch
, CURLOPT_CONNECTTIMEOUT, 10);
$res
= curl_exec(
$ch
);
curl_close(
$ch
);
//解析json
$user_obj
= json_decode(
$res
,true);
$_SESSION
[
'user'
] =
$user_obj
;
print_r(
$user_obj
);