微信掃碼登錄:
第一步:去 微信開放平臺 申請權(quán)限接口 創(chuàng)建應(yīng)用
微信掃碼登錄
第二步:在代碼里創(chuàng)建微信登錄方法
//微信掃碼登錄
public function wxLogin()
{
header("Content-type: text/html; charset=utf-8");
$redirect_uri="http://www.wxqfx1688.com\get_user_info";
$redirect_uri=urlencode($redirect_uri);//該回調(diào)需要url編碼
$appID="wx5bf9a4b25fd3ec3d";
$scope="snsapi_login";//寫死嘀倒,微信暫時只支持這個值
//準(zhǔn)備向微信發(fā)請求
$url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $appID."&redirect_uri=".$redirect_uri
."&response_type=code&scope=".$scope."&state=STATE#wechat_redirect";
//請求返回的結(jié)果(實際上是個html的字符串)
$result = file_get_contents($url);
//替換圖片的src才能顯示二維碼
$result = str_replace("/connect/qrcode/", "https://open.weixin.qq.com/connect/qrcode/", $result);
return $result; //返回頁面
}
第三步:微信授權(quán)回調(diào)域 同步返回地址
返回的數(shù)據(jù):
array(10) {
["openid"] => string(28) "oA9I11vLa_dx33eeRdHn28BdN4yk"
["nickname"] => string(11) "hello world"
["sex"] => int(1)
["language"] => string(5) "zh_CN"
["city"] => string(0) ""
["province"] => string(0) ""
["country"] => string(2) "AD"
["headimgurl"] => string(129) "http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eo1FN51iaAdhGUbAXmAjskOqSobVaFSDMHaMBdyP2f5jqGIk66rKK7wMc3j6GASkjR7uh7HKqgic5Xw/132"
["privilege"] => array(0) {
}
["unionid"] => string(28) "oS5sU5mrcU7-KGiW7BYnlT67Q5iU"
}
返回地址方法處理
方法處理:
public function get_user_info()
{
$code = $_GET["code"];
$appid = "wx5bf9a4b25fd3ec3d";
$secret = "2862c4b1cdeb57ff6484e5529d8fcaf4";
if (!empty($code)) //有code
{
//通過code獲得 access_token + openid
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid
. "&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
$jsonResult = file_get_contents($url);
$resultArray = json_decode($jsonResult, true);
$access_token = $resultArray["access_token"];
$openid = $resultArray["openid"];
//通過access_token + openid 獲得用戶所有信息,結(jié)果全部存儲在$infoArray里,后面再寫自己的代碼邏輯
$infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid;
$infoResult = file_get_contents($infoUrl);
$infoArray = json_decode($infoResult, true);
//寫你的邏輯帶代碼
}
}
內(nèi)嵌JS顯示:
這里就是通過js端實例化一個對象即可似芝,首先在<head>標(biāo)簽內(nèi)添加如下js文件臭家,
<script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
其次在html中定義一個div包含二維碼趣钱,
<div id="login_container"></div>
最后在$(document).ready()內(nèi)進行實例化:
$(document).ready(function()
{
var obj = new WxLogin
({
id:"login_container",//div的id
appid: "你的appid",
scope: "snsapi_login",//寫死
redirect_uri:encodeURI("你的處理掃碼事件的方法") ,
state: "",
style: "black",//二維碼黑白風(fēng)格
href: "https://某個域名下的css文件"
});
});
注意其中href里指向的css文件必須放在https協(xié)議下才能引用的到,不然頁面上就是默認(rèn)樣式(顯示上是一個比較大的二維碼舰始,你無法調(diào)節(jié)二維碼的大小鸠儿,位置,太痛苦了)末捣。最后部分頁面大概長成這樣,這里的二維碼大概只有140px:
邏輯圖:
邏輯圖