微信的授權(quán)登錄和QQ、新浪等平臺的授權(quán)登錄都大同小異,均采用OauthOAuth2.0鑒權(quán)方式。
微信授權(quán)分為兩種:
1、靜默授權(quán)
2、彈窗授權(quán),需要用戶手動同意
兩種scope的區(qū)別說明
1、以snsapi_base為scope發(fā)起的網(wǎng)頁授權(quán),是用來獲取進(jìn)入頁面的用戶的openid的,并且是靜默授權(quán)并自動跳轉(zhuǎn)到回調(diào)頁的。用戶感知的就是直接進(jìn)入了回調(diào)頁(往往是業(yè)務(wù)頁面)
2、以snsapi_userinfo為scope發(fā)起的網(wǎng)頁授權(quán),是用來獲取用戶的基本信息的。但這種授權(quán)需要用戶手動同意,并且由于用戶同意過,所以無須關(guān)注,就可在授權(quán)后獲取該用戶的基本信息。
用戶管理類接口中的“獲取用戶基本信息接口”,是在用戶和公眾號產(chǎn)生消息交互或關(guān)注后事件推送后,才能根據(jù)用戶OpenID來獲取用戶基本信息。這個接口,包括其他微信接口,都是需要該用戶(即openid)關(guān)注了公眾號后,才能調(diào)用成功的。
具體而言,網(wǎng)頁授權(quán)流程分為四步:
1、引導(dǎo)用戶進(jìn)入授權(quán)頁面同意授權(quán),獲取code
2、通過code換取網(wǎng)頁授權(quán)access_token(與基礎(chǔ)支持中的access_token不同)
3、如果需要,開發(fā)者可以刷新網(wǎng)頁授權(quán)access_token,避免過期
4、通過網(wǎng)頁授權(quán)access_token和openid獲取用戶基本信息(支持UnionID機(jī)制)
以下是封裝的微信操作類,需要用到兩個數(shù)據(jù)表,用于保存access_token、ticket,由于他們具有一定有效期,且每天請求數(shù)有上限,所以開發(fā)者需自行保存,以下是代碼:
'系統(tǒng)繁忙,此時請開發(fā)者稍候再試',
'0' => '請求成功',
'40001' => 'AppSecret錯誤或者AppSecret不屬于這個公眾號,請開發(fā)者確認(rèn)AppSecret的正確性',
'40002' => '請確保grant_type字段值為client_credential',
'40164' => '調(diào)用接口的IP地址不在白名單中,請在接口IP白名單中進(jìn)行設(shè)置。',
);
function __construct($appid, $appserect) {
$this->appid = $appid;
$this->appserect = $appserect;
$this->curl = new Curl();
}
/*
微信網(wǎng)頁授權(quán)登錄 需要在公眾號設(shè)置 - 功能設(shè)置 - 網(wǎng)頁授權(quán)域名
第一步:用戶同意授權(quán),獲取code
scope : snsapi_base 只能獲取openid 直接跳轉(zhuǎn)
snsapi_userinfo
*/
public function getCode($redirect_uri, $scope = 'snsapi_userinfo',$state = '1') {
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state={$state}#wechat_redirect";
header("Location:{$url}");
exit;
}
/*
第二步:通過code換取網(wǎng)頁授權(quán)access_token
*/
public function getAccessTokenByCode($code) {
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appserect}&code={$code}&grant_type=authorization_code";
// exit($url);
// $curl = new Curl();
$result = $this->curl->doGet($url);
if (!$result) {
// $this->curl->getError()
$this->msg = "獲取token失敗";
return false;
}
$result = json_decode($result, true);
if ($result['errcode']) {
$this->msg = $result['errmsg'];
return false;
}
return $result;
}
// 第三步:刷新access_token(如果需要) 通過code 獲取openid $type 0靜默授權(quán) 1彈窗授權(quán)
public function getUserInfo($code, $type = 0, $lang = 'zh_CN ') {
$result = $this->getAccessTokenByCode($code);
if (!$result) {
return false;
}
$member = C::t(PT_USER)->getByOpenid($result['openid']);
if ($member) {
return $member;
} else {
if ($type) {
$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$result['access_token']}&openid={$result['openid']}&lang={$lang}";
// $return = $this->curl->doGet($url);
// 這接口有病 強制顯示文件頭
$return = file_get_contents($url);
if (!$return) {
$this->msg = '獲取用戶信息失敗';
return false;
}
$return = json_decode($return, true);
if (!$return) {
$this->msg = '獲取用戶信息返回失敗';
return false;
}
// file_put_contents('ccc.txt',print_r($return,true),FILE_APPEND);
$data = array(
'openid' => $return['openid'],
'name' => $return['nickname'],
'sex' => $return['sex'],
'province' => $return['province'],
'city' => $return['city'],
'country' => $return['country'],
'img' => $return['headimgurl'],
'bindtel' => 0,
);
} else {
$data = array(
'openid' => $result['openid'],
'username' => "微信用戶_" . random(6,1)
);
}
$name = rand(100000, 1000000000);
$e = $name . "@qq.com";
$password = $e;
$id = UserAddEdit(0, $data['username'], $password, $e,10,0,"", $msg);
if ($id <= 0) {
$this->msg = $msg;
return false;
}
C::t(PT_USER)->update($data, $id);
$member = C::t(PT_USER)->get($id);
return $member;
}
}
/*
公眾號 安全中心 設(shè)置IP白名單
公眾號的全局唯一接口調(diào)用憑據(jù),公眾號調(diào)用各接口時都需使用access_token。開發(fā)者需要進(jìn)行妥善保存。access_token的存儲至少要保留512個字符空間。access_token的有效期目前為2個小時,需定時刷新,重復(fù)獲取將導(dǎo)致上次獲取的access_token失效。
*/
public function getAccessToken($type) {
$addtime = TIMESTAMP - 7200;
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appserect}";
$row = C::t(PT_WXTOKEN)->getNew($addtime, $type);
if ($row) {
return $row['access_token'];
} else {
$result = $this->curl->doGet($url);
if (!$result) {
$this->msg = "無法獲取令牌內(nèi)容";
return false;
}
$result = json_decode($result, true);
if (!$result) {
$this->msg = "解析令牌內(nèi)容失敗";
return false;
}
if ($result['access_token']) {
C::t(PT_WXTOKEN)->addToken($result['access_token'], $type);
return $result['access_token'];
} else {
$this->msg = "獲取令牌失敗";
return false;
}
}
}
// 獲取js票據(jù) 需要在公眾號設(shè)置 - 功能設(shè)置 - JS接口安全域名設(shè)置
public function getJsTicket() {
$addtime = TIMESTAMP - 7200;
$row = C::t(PT_WXTICKET)->getNew($addtime);
if ($row) {
return $row['ticket'];
} else {
$token = $this->getAccessToken();
if (!$token) {
return false;
}
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$token}&type=jsapi";
$result = $this->curl->doGet($url);
if (!$result) {
$this->msg = "無法獲取js票據(jù)";
return false;
}
$result = json_decode($result, true);
if (!$result) {
$this->msg = "解析js票據(jù)內(nèi)容失敗";
return false;
}
if ($result['ticket']) {
C::t(PT_WXTICKET)->addTicket($result['ticket']);
return $result['ticket'];
} else {
$this->msg = "獲取js票據(jù)失敗";
return false;
}
}
}
// js sdk 票據(jù)簽名 當(dāng)前網(wǎng)頁的URL,不包含#及其后面部分
public function jsSign($data) {
// 1.所有待簽名參數(shù)按照字段名的ASCII 碼從小到大排序(字典序)
ksort($data);
// 2.URL鍵值對的格式(即key1=value1&key2=value2…)拼接成字符串string1 采用原始值,不進(jìn)行URL 轉(zhuǎn)義
$string1 = $this->ToUrlParams($data);
// echo "string1:{$string1}";
// 3.對string1做sha1加密
$sign = sha1($string1);
// echo "signature:{$sign}";
return $sign;
}
// 獲取消息內(nèi)容
public function getMsg() {
return $this->msg;
}
/**
* 格式化參數(shù)格式化成url參數(shù)
*/
public function ToUrlParams($data) {
$buff = "";
foreach ($data as $k => $v) {
if ($k != "sign" && $v != "" && !is_array($v)) {
$buff .= $k . "=" . $v . "&";
}
}
$buff = trim($buff, "&");
return $buff;
}
}
?>
業(yè)務(wù)代碼:
// 微信登錄
function wxlogin() {
global $_G,$identifier,$config,$wx;
if (!$_G['uid']) {
if ($_GET['state']) {
//回調(diào)
$member = $wx->getUserInfo($_GET['code']);
if (!$member) {
exit($wx->getMsg());
}
if (!function_exists("setloginstatus")) {
include_once libfile('function/member');
}
// 設(shè)置登錄狀態(tài)$wx
setloginstatus($member, 2592000);
checkfollowfeed();
$_G['uid'] = $member['uid'];
$_G['member'] = $member;
} else {
//請求授權(quán) 對參數(shù)編碼
$redirect = urlencode(getProtocol() . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
$wx->getCode($redirect, 'snsapi_base');
}
}
}
function getProtocol() {
return is_HTTPS() ? 'https://' : 'http://';
}
function is_HTTPS() { if ($_SERVER['HTTPS'] === 1 || $_SERVER['HTTPS'] === 'on' || $_SERVER['SERVER_PORT'] == 443) {
return true;
}
return false;
}