1. 程式人生 > >小程式app.js整合授權儲存機制

小程式app.js整合授權儲存機制

客戶端

App({

  onLaunch: function() {
    //呼叫API從本地快取中獲取資料
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },

getUserInfo: function(cb) {
    var that = this
    var unionId = wx.getStorageSync('unionId');
            console.log('unionid:'+unionId);
    if (unionId) {
wx.getUserInfo({
success: function (res) {
that.globalData.userInfo = res.userInfo
// that.setData({
// nickName: res.userInfo.nickName,
// avatarUrl: res.userInfo.avatarUrl,
// })
},
fail: function () {
console.log("獲取失敗!")
},
complete: function () {
console.log("獲取使用者資訊完成!")
}
})
    } else {
    wx.login({
success: function (r) {
var code = r.code;//登入憑證
if (code) {
//2、呼叫獲取使用者資訊介面
wx.getUserInfo({
success: function (res) {
  // console.log({ encryptedData: res.encryptedData, iv: res.iv, code: code })
//3.解密使用者資訊 獲取unionId
wx.request({
url: '',//自己的服務介面地址
method: 'post',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: { encryptedData: res.encryptedData, iv: res.iv, code: code },
success: function (res) {
//4.解密成功後 獲取自己伺服器返回的結果
if (res.data.code == 200) {
var userInfo_ = res.data.data;
// that.setData({
// nickName: userInfo_.nickName,
// avatarUrl: userInfo_.avatarUrl,
   //})
            wx.setStorageSync('openId', userInfo_.openId);
            wx.setStorageSync('unionId', userInfo_.unionId);
wx.showToast({
title: res.data.msg,
icon: 'success',
duration: 1500
})
}else {
wx.showToast({
title: res.data.msg,
icon: 'none',
duration: 1500
})
}
},
fail: function () {
console.log('系統錯誤')
}
})
}, fail: function () {
wx.showModal({
title: '警告通知',
content: '您點選了拒絕授權,將無法正常顯示個人資訊,點選確定重新獲取授權。',
success: function (res) {
if (res.confirm) {
wx.openSetting({
success: (res) => {
if (res.authSetting["scope.userInfo"]) {//如果使用者重新同意了授權登入
wx.login({
success: function (res_login) {
if (res_login.code) {
wx.getUserInfo({
withCredentials: true,
success: function (res_user) {
wx.request({
url: '',//自己的服務介面地址
method: 'post',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: { encryptedData: res_user.encryptedData, iv: res_user.iv, code: res_login.code },
success: function (res) {
//4.解密成功後 獲取自己伺服器返回的結果
if (res.data.code == 200) {
var userInfo_ = res.data.data;
// that.setData({
  //nickName: userInfo_.nickName,
  //avatarUrl: userInfo_.avatarUrl,
   //})
            wx.setStorageSync('openId', userInfo_.openId);
            wx.setStorageSync('unionId', userInfo_.unionId);
wx.showToast({
title: res.data.msg,
icon: 'success',
duration: 1500
})
}else {
wx.showToast({
title: res.data.msg,
icon: 'none',
duration: 1500
})
}
},
fail: function () {
console.log('系統錯誤')
}
})
}
})
}
}
});
}
}, fail: function (res) {


}
})
}
}
})
}
})
} else {
  console.log('獲取使用者登入態失敗!' + r.errMsg)
}
},
fail: function () {
callback(false)
}
})
}
  },


globalData: {
userInfo: null
}

})

服務端PHP:

    //獲取unionID
    public function authorizationUnionid()
    {
        $authData = I('post.');
        $url = self::AUTHURL.'?appid='.self::APPID.'&secret='.self::APPSECRET.'&js_code='.$authData['code'].'&grant_type=authorization_code';
        $result = file_get_contents($url);
        $userInfo = json_decode($result, true);
        try{
            $authInfo = $this->decryptData($authData['encryptedData'], $userInfo['session_key'], $authData['iv']);
            //儲存小程式授權標識
            $this->get_openid($authInfo->openId);
            $this->get_unionid($authInfo->unionId);
            $this->get_signkey($userInfo['session_key']);
            $this->ajaxReturn(['code' => 200, 'data' => $authInfo, 'msg' => '獲取成功']);
        }catch(\Exception $e){
            $this->ajaxReturn(['code' => 500, 'msg' => $e->getMessage()]);
        }

    }

/**
* 檢驗資料的真實性,並且獲取解密後的明文.
* @param $encryptedData string 加密的使用者資料
* @param $iv string 與使用者資料一同返回的初始向量
* @param $data string 解密後的原文
     *
* @return int 成功0,失敗返回對應的錯誤碼
*/
public function decryptData($encryptedData, $key, $iv)
{
$aesKey = base64_decode($key);
$aesIV = base64_decode($iv);
$aesCipher = base64_decode($encryptedData);
$result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
$dataObj = json_decode($result);
return $dataObj;
}