新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
PHP實(shí)現(xiàn)微信開放平臺掃碼登錄
為了優(yōu)化登錄,減少用戶操作,決定使用微信掃碼登錄,開發(fā)步驟如下

一、登錄微信開放平臺(https://open.weixin.qq.com/),創(chuàng)建應(yīng)用申請AppID和AppSecret
二、拿到AppID和AppSecret 后 便可以開始開發(fā)了,創(chuàng)建一個(gè)喚起微信登錄的頁面,并跳轉(zhuǎn)到微信掃碼頁面
/*微信喚起登錄*/
public function index()
{
$type = input('type');
$this->wxopenConfig = config('wxopen');
if ($type == 'weixin') {
$redirect_url = urlencode('http://' . $_SERVER['HTTP_HOST'] . '/snslogin/wx_login');
$url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $this->wxopenConfig['appid'] . "&redirect_uri=" . $redirect_url . "&response_type=code&scope=" . $this->wxopenConfig['scope'] . "&state=STATE&connect_redirect=1#wechat_redirect";
header('Location:' . $url);
} else {
echo 'hello word';
}
}
//Config.php配置文件
return [
'wxopen'=>[
'appid'=>'',
'appsecret'=>'',
'scope'=>'snsapi_login'//固定參數(shù),保留即可
],
];
用戶掃碼完成后,微信會(huì)有一個(gè)同步回調(diào),回調(diào)到你剛才設(shè)置的地址$redirect_url
/*微信回調(diào)*/
public function wx_login(){
$this->wxopenConfig = config('wxopen');
$code = $_GET['code'];
//判斷是否授權(quán)
if (empty($code)){
$this->error('授權(quán)失敗');
}
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->wxopenConfig['appid'] . '&secret=' . $this->wxopenConfig['appsecret'] . '&code=' . $code . '&grant_type=authorization_code';
//獲取token,為了獲取access_token 如果沒有就彈出錯(cuò)誤
$token = json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
echo '錯(cuò)誤:
' . $token->errcode;
echo '
錯(cuò)誤信息:
' . $token->errmsg;
exit;
}
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $this->wxopenConfig['appid'] . '&grant_type=refresh_token&refresh_token=' . $token->refresh_token;
//獲取access_token ,為了獲取微信的個(gè)人信息,如果沒有就彈出錯(cuò)誤
$access_token = json_decode(file_get_contents($access_token_url));
if (isset($access_token->errcode)) {
echo '錯(cuò)誤:
' . $access_token->errcode;
echo '
錯(cuò)誤信息:
' . $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 = json_decode(file_get_contents($user_info_url));
if (isset($user_info->errcode)) {
echo '錯(cuò)誤:
' . $user_info->errcode;
echo '
錯(cuò)誤信息:
' . $user_info->errmsg;
exit;
}
//這里轉(zhuǎn)換為數(shù)組
$rs = (array)$user_info;
die($rs);
}
到此已經(jīng)獲取到了微信用戶信息,后續(xù)再加上自己的業(yè)務(wù)邏輯即可
網(wǎng)站題目:PHP實(shí)現(xiàn)微信開放平臺掃碼登錄
URL網(wǎng)址:http://www.dlmjj.cn/article/djhispj.html


咨詢
建站咨詢
