HBuilderX 3.0+版本,新增一鍵登錄,運營商網關認證,免短信驗證獲取手機號;剛好最近開發項目有應用上,簡單分享一下!
1、開通uniapp的“一鍵登錄”權限
在minifest.json文件中勾選一鍵登錄(univerify)
2、申請雲開發空間,開通地址(https://unicloud.dcloud.net.cn)
3、在項目中創建“雲函數”
方法名自己定義即可,創建完後在 index.js 填入以下獲取手機號碼的雲函數代碼:
'use strict';
exports.main = async (event, context) => {
let req = event.queryStringParameters; // 該參數爲獲取後端傳遞的access_token和openid,具體變量可以通過console.log打印查看
const res = await uniCloud.getPhoneNumber({
appid: '__UNI__1222', // 替換成自己開通一鍵登錄的應用的DCloud appid,使用callFunction方式調用時可以不傳(會自動取當前客戶端的appid),如果使用雲函數URL化的方式訪問必須傳此參數
provider: 'univerify',
apiKey: 'xxxx', // 在開發者中心開通服務並獲取apiKey
apiSecret: 'xxxx', // 在開發者中心開通服務並獲取apiSecret
access_token: req.access_token,
openid: req.openid
})
// 執行入庫等操作,正常情況下不要把完整手機號返回給前端
return {
code: 0,
message: '獲取手機號成功',
content: res // res裏面包含了成功獲取的真實手機號碼
}
};
保存代碼後右擊函數目錄,選擇“上傳部署”;
4、前端實現調用
toLogin(){
var _this = this;
uni.preLogin({
provider:"univerify",
success() {
uni.hideLoading();
uni.login({
provider:"univerify",
univerifyStyle:{},// 自定義授權頁面信息,參數參考文檔 https://uniapp.dcloud.io/univerify
success(res) {
let loginRes = res.authResult;
// loginRes : {openid:'deviceIDlength+deviceID+gyuid',access_token:'接口返回的 token'}
requestLogin(); // 執行後端請求邏輯
},
fail(fres) {
uni.closeAuthView(); // 關閉一鍵登錄彈出窗口
if(fres.code == 30002){ // 點擊其他方式登陸
uni.navigateTo({
url:"login/login",
animationType: 'slide-in-bottom',
animationDuration: 200
})
}
// 30003 關閉登陸
},
complete() {
uni.closeAuthView();
}
})
},
fail(res) {
console.log('error',res);
}
})
}
5、後端根據access_token和openid換取手機號碼;以thinkphp爲例
/**
* 一鍵登陸
*/
public function univerify(Request $request){
$secret = "這裏填寫一鍵登錄申請通過後的AppSecret";
$sign = $this->getSignature($request->post(),$secret);
$requestUrl = "uniCloud後臺獲取的請求地址?sign=".$sign."&".http_build_query($request->post());
$result = json_decode(file_get_contents($requestUrl),true);
// 數據返回格式,自行打印查看
// {
// code: 0,
// message: '',
// phoneNumber: '138xxxxxxxx'
// }
if($result['code'] && isset($result['content']['phoneNumber'])){
$mobile = $result['content']['phoneNumber']; // 實際獲取手機號碼
}
}
/**
* 獲取簽名
* @param array $arrdata 簽名數組
* @param string $key 密鑰
* @return boolean|string 簽名值
*/
protected function getSignature($arrdata,$key) {
ksort($arrdata);
$paramstring = "";
foreach($arrdata as $key => $value)
{
if(strlen($paramstring) == 0)
$paramstring .= $key . "=" . $value;
else
$paramstring .= "&" . $key . "=" . $value;
}
$stringSignTemp = rtrim($paramstring, '&');
$paySign = hash_hmac('sha256',$stringSignTemp,$key);
return $paySign;
}
6、前端獲取手機號碼
通過官方提供的雲函數調用方法
uniCloud.callFunction({
name:"雲函數名",
data:{
"access_token":loginRes.access_token,
"openid":loginRes.openid
}
}).then((res)=>{
console.log(res); // res 內容則包含手機號碼
}).catch(){
// 執行失敗
}
7、雲函數請求地址獲取