溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

微信開(kāi)發(fā)中如何實(shí)現(xiàn)網(wǎng)頁(yè)授權(quán)獲取用戶信息

發(fā)布時(shí)間:2021-09-16 15:34:41 來(lái)源:億速云 閱讀:257 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)微信開(kāi)發(fā)中如何實(shí)現(xiàn)網(wǎng)頁(yè)授權(quán)獲取用戶信息的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。

1、設(shè)置授權(quán)回調(diào)域名:開(kāi)發(fā) ---> 接口權(quán)限

  找到“網(wǎng)頁(yè)授權(quán)獲取用戶基本信息”,點(diǎn)擊后面對(duì)應(yīng)的“修改”,在彈框響應(yīng)位置填寫授權(quán)回調(diào)域名即可,此處的域名不需要加http:// (關(guān)于網(wǎng)頁(yè)授權(quán)回調(diào)域名的說(shuō)明詳情可參考公眾平臺(tái)開(kāi)發(fā)者文檔)

微信開(kāi)發(fā)中如何實(shí)現(xiàn)網(wǎng)頁(yè)授權(quán)獲取用戶信息

微信開(kāi)發(fā)中如何實(shí)現(xiàn)網(wǎng)頁(yè)授權(quán)獲取用戶信息

2、獲取授權(quán)

  實(shí)際上,獲取用戶信息的關(guān)鍵在于獲取用戶的openid。博主想要實(shí)現(xiàn)用戶點(diǎn)擊公眾號(hào)菜單打開(kāi)頁(yè)面即可自動(dòng)授權(quán),從而針對(duì)該用戶進(jìn)行數(shù)據(jù)庫(kù)操作,于是有下面兩種方式: 

  (1)利用自定義菜單請(qǐng)求授權(quán)頁(yè)面

    自定義菜單后面會(huì)單獨(dú)寫一篇博文,在這里先簡(jiǎn)述一下通過(guò)自定義菜單進(jìn)行授權(quán),該方法需要高級(jí)接口權(quán)限,且局限于關(guān)注公眾號(hào)的用戶直接從菜單進(jìn)入頁(yè)面。

$menu = '{
"button":[
{
"type": "view",
"name": "商城",
"url": "https://open.weixin.qq.com/connect/oauth/authorize?appid=xxx&redirect_uri=http://tx.heivr.com/index.php&response_type=code&scope=snsapi_base&state=#wechat_redirect"
},
{
"name":"快遞服務(wù)",
"sub_button":[
{
"type":"click",
"name":"發(fā)快遞",
"key":"express"
},
{
"type":"click",
"name":"快遞查詢",
"key":"ww"
}
]
},
]
}';

需要授權(quán)的view直接在url處填寫微信提供的授權(quán)請(qǐng)求地址,其中:

?appid:填寫微信公眾平臺(tái)基本配置中的AppID;
?redirect_uri:填寫授權(quán)完成后跳轉(zhuǎn)的頁(yè)面地址,即自己的html5頁(yè)面;
?state:跳轉(zhuǎn)至回調(diào)頁(yè)面所帶參數(shù);
?response_type:網(wǎng)頁(yè)授權(quán)的兩種scope,微信官方文檔中說(shuō)明如下:

1、以snsapi_base為scope發(fā)起的網(wǎng)頁(yè)授權(quán),是用來(lái)獲取進(jìn)入頁(yè)面的用戶的openid的,并且是靜默授權(quán)并自動(dòng)跳轉(zhuǎn)到回調(diào)頁(yè)的。用戶感知的就是直接進(jìn)入了回調(diào)頁(yè)(往往是業(yè)務(wù)頁(yè)面)

2、以snsapi_userinfo為scope發(fā)起的網(wǎng)頁(yè)授權(quán),是用來(lái)獲取用戶的基本信息的。但這種授權(quán)需要用戶手動(dòng)同意,并且由于用戶同意過(guò),所以無(wú)須關(guān)注,就可在授權(quán)后獲取該用戶的基本信息。
按照此方法點(diǎn)擊“商城”即可接收到返回的openid,繼而進(jìn)行下一步用戶信息的獲取?!?/p>

(2)利用JS自動(dòng)請(qǐng)求授權(quán)頁(yè)面

這個(gè)方法相對(duì)而言比較笨拙,步驟略復(fù)雜,但目前能解決需求還沒(méi)有研究簡(jiǎn)化方法,且由于頁(yè)面的跳轉(zhuǎn)多數(shù)情況下訪問(wèn)頁(yè)面的時(shí)間會(huì)增加,但相比于前一個(gè)方法,該方法可以獲取到非關(guān)注用戶的基本信息。有些程序可能涉及到頁(yè)面分享,程序沒(méi)有強(qiáng)制關(guān)注但其他用戶通過(guò)分享直接進(jìn)入頁(yè)面也需要記錄用戶信息,此時(shí)可以考慮該方法。(微信開(kāi)發(fā)相關(guān)的代碼博主封裝成工具類調(diào)用,這里先貼用到的部分,以后整理完成會(huì)全部貼出來(lái)并附下載鏈接)

該方法的思路為:js請(qǐng)求鏈接獲取code ---> 利用code換取openid ---> 得到用戶基本信息

a. 編輯配置

為了方便把用到的一些微信參數(shù)單獨(dú)寫入一個(gè)類,方便修改添加及調(diào)用

<?php
namespace common\tools\wechat;
/**
* 微信請(qǐng)求相關(guān)配置類庫(kù)
*/
class ConfigTool {
/**
* 微信配置參數(shù)
* @return array 配置參數(shù)
*/
public function setConfig() {
// 用于驗(yàn)證微信接口配置信息的Token,可以任意填寫
$config['token'] = '自己的token';
// appID
$config['appid'] = '自己的appid';
// appSecret
$config['secret'] = '自己的secret';
// 回調(diào)鏈接地址
$config['redirect_uri'] = 'http://tx.heivr.com/index.php?';
// 是否以 HTTPS 安全協(xié)議訪問(wèn)接口
$config['https_request'] = false;
// 授權(quán)作用域,snsapi_base (不彈出授權(quán)頁(yè)面,直接跳轉(zhuǎn),只能獲取用戶openid),
// snsapi_userinfo (彈出授權(quán)頁(yè)面,可通過(guò)openid拿到昵稱、性別、所在地。并且,
// 即使在未關(guān)注的情況下,只要用戶授權(quán),也能獲取其信息)
$config['scope'] = 'snsapi_userinfo';
// 語(yǔ)言
$config['lang'] = 'zh_CN'; // zh_CN 簡(jiǎn)體,zh_TW 繁體,en 英語(yǔ)
// 微信公眾賬戶授權(quán)地址
$config['mp_authorize_url'] = 'https://api.weixin.qq.com/cgi-bin/token';
// 微信公眾賬戶js臨時(shí)票據(jù)地址
$config['jsapi_ticket_url'] = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
// 授權(quán)地址
$config['authorize_url'] = 'https://open.weixin.qq.com/connect/oauth/authorize';
// 獲取access token 的地址
$config['access_token_url'] = 'https://api.weixin.qq.com/sns/oauth/access_token';
// 刷新 token 的地址
$config['refresh_token_url'] = 'https://api.weixin.qq.com/sns/oauth/refresh_token';
// 獲取用戶信息地址
$config['userinfo_url'] = 'https://api.weixin.qq.com/sns/userinfo';
// 驗(yàn)證access token
$config['valid_token_url'] = 'https://api.weixin.qq.com/sns/auth';
// 上傳臨時(shí)素材地址
$config['media_temp_upload_url'] = 'https://api.weixin.qq.com/cgi-bin/media/upload?';
// 上傳永久素材地址
$config['media_forever_upload_url'] = 'https://api.weixin.qq.com/cgi-bin/material/add_material?';
return $config;
}
}

b. https請(qǐng)求工具

<?php
namespace common\tools;
/**
* https請(qǐng)求相關(guān)類庫(kù)
*/
class HttpsTool {
const TIMEOUT = ; // 設(shè)置超時(shí)時(shí)間
private $ch; // curl對(duì)象
/**
* 發(fā)送curl請(qǐng)求,并獲取請(qǐng)求結(jié)果
* @param string 請(qǐng)求地址
* @param array 如果是post請(qǐng)求則需要傳入請(qǐng)求參數(shù)
* @param string 請(qǐng)求方法,get 或者 post, 默認(rèn)為get
* @param bool 是否以https協(xié)議請(qǐng)求
*/
public function send_request($requests, $params = null, $method = 'get', $https = true) {
// 以get方式提交
if ($method == 'get') {
if($params){
$request = $requests . $this->create_url($params);
}else{
$request = $requests;
}
}else{
$request = $requests;
}
$this->ch = curl_init($request);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, );// 設(shè)置不顯示結(jié)果,儲(chǔ)存入變量
curl_setopt($this->ch, CURLOPT_TIMEOUT, self::TIMEOUT); // 設(shè)置超時(shí)限制防止死循環(huán)
// 判斷是否以https方式訪問(wèn)
if ($https) {
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, ); // 對(duì)認(rèn)證證書(shū)來(lái)源的檢查
curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, ); // 從證書(shū)中檢查SSL加密算法是否存在
}
if ($method == 'post') { // 以post方式提交
//curl_setopt($this->ch, CURLOPT_SAFE_UPLOAD, false); //php .文件上傳必加內(nèi)容,.不需要
curl_setopt($this->ch, CURLOPT_POST, ); // 發(fā)送一個(gè)常規(guī)的Post請(qǐng)求
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params); // Post提交的數(shù)據(jù)包
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, );
}
$tmpInfo = curl_exec($this->ch); // 執(zhí)行操作
if (curl_errno($this->ch)) {
echo 'Errno:'.curl_error($this->ch);//捕抓異常
}
curl_close($this->ch); // 關(guān)閉CURL會(huì)話
//var_dump($tmpInfo);exit;
return $tmpInfo; // 返回?cái)?shù)據(jù)
}
/**
* 生成url
*/
public function create_url($data) {
$temp = '?';
foreach ($data as $key => $item) {
$temp = $temp . $key . '=' . $item . '&';
}
return substr($temp, , -);
}
}

關(guān)于curl_setopt($this->ch, CURLOPT_SAFE_UPLOAD, false)會(huì)在微信圖片資源上傳博文中詳細(xì)講述它出現(xiàn)的心酸史,這里暫時(shí)用不到,不做解釋

c. 授權(quán)基類

<?php 
namespace common\tools\wechat;
use common\tools\wechat\ConfigTool;
use common\tools\HttpsTool;
/**
* Weixin_oauth 類庫(kù)
*/
class OauthTool {
public $conf;
public function __construct(){
$re = new ConfigTool; 
$this->conf = $re->setConfig();
} 
/**
* 生成用戶授權(quán)的地址
* @param string 自定義需要保持的信息
* @param sting 請(qǐng)求的路由
* @param bool 是否是通過(guò)公眾平臺(tái)方式認(rèn)真
*/
public function authorize_addr($route, $state='', $mp=false) {
if ($mp) {
$data = [
'appid' => $this->conf['appid'],
'secret' => $this->conf['token'],
'grant_type' => 'client_credential'
];
$url = $this->conf['mp_authorize_url'];
} else {
$data = [
'appid' => $this->conf['appid'], //公眾號(hào)唯一標(biāo)識(shí)
'redirect_uri' => urlencode($this->conf['redirect_uri'] . $route), //授權(quán)后重定向的回調(diào)鏈接地址
'response_type' => 'code', //返回類型,此處填寫code
'scope'=>$this->conf['scope'], //應(yīng)用授權(quán)作用域
'state'=>$state, //重定向后帶上state參數(shù),開(kāi)發(fā)者可以填寫任意參數(shù)
'#wechat_redirect'=>'' //直接在微信打開(kāi)鏈接,可不填,做頁(yè)面重定向時(shí)必須帶此參數(shù)
];
$url = $this->conf['authorize_url'];
}
$send = new HttpsTool;
//var_dump($url . $send->create_url($data));exit;
return $url . $send->create_url($data);
}
/**
* 獲取 access token
* @param string 用于換取access token的code,微信提供
*/
public function access_token($code) {
$data = [
'appid' => $this->conf['appid'],
'secret' => $this->conf['secret'],
'code' => $code,
'grant_type' => 'authorization_code'
];
// 生成授權(quán)url
$url = $this->conf['access_token_url'];
$send = new HttpsTool;
return $send->send_request($url, $data);
}
/**
* 獲取用戶信息
* @param string access token
* @param string 用戶的open id
*/
public function userinfo($token, $openid) {
$data = [
'access_token' => $token,
'openid' => $openid,
'lang' => $this->conf['lang']
];
// 生成授權(quán)url
$url = $this->conf['userinfo_url'];
$send = new HttpsTool;
return $send->send_request($url, $data);
}
}

d. 授權(quán)基類調(diào)用及用戶數(shù)據(jù)處理(在控制器調(diào)用前,先對(duì)用戶數(shù)據(jù)存入或更新)

<?php
namespace wechat\controllers\classes;
use common\tools\wechat\OauthTool;
use common\models\User;
use common\tools\EmojiTool;
/**
* 微信用戶基本信息獲取
*/
class UserinfoClass {
/**
* 用戶授權(quán)并獲取code 
* @return string 用戶code
*/
public function getCode($route, $state){
$re = new OauthTool;
$request = $re->authorize_addr($route, $state);
$code = isset($_GET['code']) ? $_GET['code'] : '';
return [$request,$code];
}
/**
* 獲取用戶信息并寫入數(shù)據(jù)庫(kù)(之后加參數(shù)傳給code)
*/
public function info($code) {
$re = new OauthTool;
//獲取access token
$access = $re->access_token($code);
$token = json_decode($access,true);
//header("Content-type: text/html; charset=gbk"); 
//獲取用戶信息
if(count($token) != ) {
$response = $re->userinfo($token['access_token'], $token['openid']);
$user = json_decode($response,true);
//用戶昵稱轉(zhuǎn)換
//$user['nickname'] = EmojiTool::emoji_trans($user['nickname']);
if($model = User::findOne(['openid' => $user['openid'] ])) { //用戶已存在更新數(shù)據(jù)
$model->attributes = $user;
$model->modify_time = time();
$model->save(false);
}else{ //用戶不存在寫入
$model = new User;
$model->attributes = $user;
$model->create_time = time();
$model->save(false);
}
}
return isset($model->id) ? $model->id : '';
}
}

e. 控制器調(diào)用(這里只貼其中一個(gè)方法)

/**
* 產(chǎn)品列表
* @return object 所有可用產(chǎn)品信息
*/
public function actionIndex(){
//判斷頁(yè)面是否自動(dòng)刷新
if(isset($_GET['state'])) {
$refresh = ;
}else{
$refresh = ;
}
//獲取用戶code
$user = new UserinfoClass;
$request = $user->getCode('r=store/index', );
//該用戶userid
$userid = $user->info($request[]);
$model = new Product;
$list = $model->find()->where(['status' => ])->all();
return $this->render('index',['list' => $list, 'refresh' => $refresh, 'userid' => $userid, 'request' => $request]);
}

程序要求用戶打開(kāi)產(chǎn)品列表即獲取用戶信息并存入數(shù)據(jù)庫(kù),其中設(shè)計(jì)了幾個(gè)變量作用如下:

$refresh:判斷頁(yè)面是否刷新,由于首次打開(kāi)頁(yè)面未進(jìn)行oauth驗(yàn)證時(shí)才自動(dòng)請(qǐng)求驗(yàn)證,避免反復(fù)刷新,這里用回調(diào)的state參數(shù)作為判斷依據(jù)且設(shè)state=1(若有特定參數(shù)需要可將state賦值為所需值);

$request:即為驗(yàn)證請(qǐng)求地址

f. 視圖自動(dòng)刷新

只需要在視圖中添加以下js代碼即可

<script type="text/javascript">
//自動(dòng)請(qǐng)求獲取code
$(function(){
var refresh = <?= $refresh; ?>;
var request = '<?= $request[]; ?>';
if(refresh == ){
console.log();
location = request;
}
});
</script>

感謝各位的閱讀!關(guān)于“微信開(kāi)發(fā)中如何實(shí)現(xiàn)網(wǎng)頁(yè)授權(quán)獲取用戶信息”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI