文檔參考:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
3個文件
(假設)服務器域名:http://www.mytest.com/
index.php、oauth2.php、test.php
1、用戶同意授權,獲取code
index.php內(nèi)容
connect_redirect=1 是騰訊(微信)服務器配置的動態(tài)參數(shù), 意為只觸發(fā)一次請求, 超時也不重發(fā)。
<?php
$appid = '你的APPID';
header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'
&redirect_uri=http://www.mytest.com/oauth2.php
&response_type=code
&scope=snsapi_userinfo
&state=state
&connect_redirect=1
#wechat_redirect');
?>
2、oauth2.php內(nèi)容
<?php
error_reporting(0);
session_start();
$appid = '你的APPID';
$appsecret = '你的APPSECRET ';
$code = $_GET['code'];//獲取微信服務器轉(zhuǎn)發(fā)過來的code
//code換取網(wǎng)頁授權access_token
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
echo '<h1>錯誤1:</h1>'.$token->errcode;
echo '<br/><h2>錯誤信息1:</h2>'.$token->errmsg;
exit;
}
//刷新access_token
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
$access_token = json_decode(file_get_contents($access_token_url));
if (isset($access_token->errcode)) {
echo '<h1>錯誤2:</h1>'.$access_token->errcode;
echo '<br/><h2>錯誤信息2:</h2>'.$access_token->errmsg;
exit;
}
//拉取用戶信息
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//$user_info用戶信息對象
$user_info = json_decode(file_get_contents($user_info_url));
if (isset($user_info->errcode)) {
echo '<h1>錯誤4:</h1>'.$user_info->errcode;
echo '<br/><h2>錯誤信息4:</h2>'.$user_info->errmsg;
exit;
}
//用戶信息存到session 全局可調(diào)用
$_SESSION['openid'] = $user_info->{'openid'};
$_SESSION['nickname'] = $user_info->{'nickname'};
$_SESSION['head'] = $user_info->{'headimgurl'};
//最后跳轉(zhuǎn)到測試頁面 test.php
header('location:http://www.mytest.com/test.php');
?>
3、test.php 內(nèi)容
<?php
session_start();
var_dump($_SESSION);
//接下來想怎么玩兒就看你自己咯。
?>