代碼下載鏈接https://download.csdn.net/download/longgeaisisi/10903652
一、準備:
1、登錄微信公衆帳號點擊接口權限查看網頁授權是否獲得
2、點擊修改設置網頁授權域名
3、拿到appid和AppSecret,下面會用到
二、代碼步驟:
- 首先引導用戶進入授權頁面同意授權,使用appId獲取code
- 通過code獲取網頁授權access_token,然後通過網頁授權access_token和openId即可獲取到用戶基本信息
(scope參數這裏官方有一個說明)
以snsapi_base爲scope發起的網頁授權,是用來獲取進入頁面的用戶的openid的,並且是靜默授權並自動跳轉到回調頁的。用戶感知的就是直接進入了回調頁(往往是業務頁面)
以snsapi_userinfo爲scope發起的網頁授權,是用來獲取用戶的基本信息的。但這種授權需要用戶手動同意,並且由於用戶同意過,所以無須關注,就可在授權後獲取該用戶的基本信息。
用戶管理類接口中的“獲取用戶基本信息接口”,是在用戶和公衆號產生消息交互或關注後事件推送後,才能根據用戶OpenID來獲取用戶基本信息。這個接口,包括其他微信接口,都是需要該用戶(即openid)關注了公衆號後,才能調用成功的。
public function wxLogin(){
//appId
$appId = 'yuor appid';
// 回調的url
$redirect_uri = urlencode('http://www.xxx.com/index.php/Home/Index/getUserInfo');
//跳轉微信回調到redirect_uri獲取code
$url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appId&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
echo "<script>location.href='$url';</script>";
}
public function getUserInfo(){
//獲取code
$code = $_GET["code"];
// appId與appSecret
$appId = 'your appid';
$appSecret = 'your appSecret';
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";
$res = $this->sendRequest($url);
var_dump($res);
$access_token = $res["access_token"];
$openId = $res['openid'];
$getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openId&lang=zh_CN";
//得到用戶信息
$user_info = $this->sendRequest($getUserInfo);
dump($user_info);
//接下來的邏輯...
}
//發送請求
public function sendRequest($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}
三、傳到服務器上去
這裏我用的是xftp5上傳快哈哈哈,絕對沒有打廣告的意思
四、效果
手機打開微信,訪問http://www.xxx.com/index.php/Home/index/wxLogin