咱們須要一個標識來記錄用戶的身份的惟一性,在微信中unionId就是咱們所須要的記錄惟一ID,那麼如何拿到unionId就成了關鍵,我將項目分爲小程序和 後臺PHP代碼兩部分來說。php
從小程序代碼提及html
簡單說下小程序的js代碼登錄流程算法
login -> 獲取code -> getUserInfo獲取iv和encryptedData -> 傳給本身的服務器處理 -> 返回給小程序結果json
var API_URL = '本身服務器地址';
Page({
onLoad: function(){
console.log("iv");
wx.login({
success:function(res){
if(res.code){
var code = res.code;
wx.getUserInfo({
success:function(res2){
console.log(res2);
var encryptedData = encodeURTComponent(res2.encryptedData); //必定要把加密串轉成URI編碼
var iv = res2.iv;
//請求本身的服務器
Login(code,encryptedData,iv);
}
})
}else{
console.log('獲取用戶登錄狀態失敗'+ res.errMsg);
}
}
})
}
});
* code: 服務器用來獲取sessionKey的必要參數小程序
* IV:加密算法的初始向量,encryptedData: 加密過的字符串。api
把code iv encryptedData 傳遞給咱們的服務器服務器
function Login(code,encryptedData,iv){ console.log('code='+code+'&encryptedData='+encryptedData+'&iv='+iv);
//建立一個dialog
wx.showToast({
title:'正在登錄...',
icon:'loading',
duration: 1000
});
//請求服務器
wx.request({
url: API_URL,
data:{
code:code,
encryptedData:encryptedData,
iv:iv
},
method: 'GET', //OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT
header:{
'content-type':'application/json'
},
success: function(res){
wx.hideToast();
console.log('服務器返回'+res.data);
},
fail:function(){
//wx.hideToast();
},
complete:function(){
//complete
}
})
}
咱們所須要的unionId就在encryptedData中,因此服務器須要這些信息來把unionId解析出來。微信
服務器處理邏輯session
先下載微信的解密demo: https://mp.weixin.qq.com/debug/wxadoc/dev/api/signature.html?t=20161122app
咱們選擇php,把除了demo外的三個php文件,放入咱們本身的項目,方便之後調用。
講一下服務器的處理流程:
經過微信的https://api.weixin.qq.com/sns/jscode2session接口獲取seesionKey,而後再經過sessionKey和iv來解密encryptedData數據獲取UnionID
例
/*登錄*/ public function weixinLogin( $user_id = null ){ global $App_Error_Conf,$Gift_Ids,$Server_Http_Path,$Is_Local,$Test_User,$Good_Vcode,$WeiXin_Xd_Conf;
$validator_result = input_validator(array('code','iv','encryptedData'));
if(!empty($validator_result)){
return response($validator_result);
}
$js_code = $_REQUEST['code'];
$encryptedData = $_REQUEST['encryptedData'];
$iv = $_REQUEST['iv'];
$appid = $WeiXin_Xd_Conf['appid'];
$secret = $WeiXin_Xd_Conf['secret'];
$grant_type = $WeiXin_Xd_Conf['grant_type'];
//從微信獲取session_key
$user_info_url = $WeiXin_Xd_Conf['code2session_url'];
$user_info_url = sprintf("%s?appid=%s&js_code=%s&grant_type=%",$user_info_url,$appid,$secret,$js_code,$grand_type);
$weixin_user_data = json_decode(get_url($user_info_url));
$session_key = $weixin_user_data->session_key;
//數據解密
$data='';
$wxBizDataCrypt = new WXBizDataCrypt($appid,$session_key);
$errCode = $wxBizDataCrypt>decryptData($appid,$session_key,$encryptedData,$iv,$data);
}
最後拿到的這個data就是咱們解密後的encryptedData,裏面會包含unionId.
這樣就實現了微信的簡單登陸。
原文地址:http://blog.csdn.net/sk719887916/article/details/53761107