0
点赞
收藏
分享

微信扫一扫

Uni-App - 接口 - 第三方登录(小程序)(Hcoder 版)


重要说明

因小程序和app登录接口不同,需要在前端进行跨端兼容处理!

小程序端必须的配置

小程序端必须配置 app id(申请小程序开发者并获取 appid 及相关秘钥,支持个人开发者)。获取appid后编辑 manifest.json :

"mp-weixin" : {
"appid" : "您的app id"
}

接口地址

​​https://developers.weixin.qq.com/miniprogram/dev/api/open.html#wxgetuserinfoobject​​

app 端必须的配置

app 端支持微信、qq、微博等多种登录方式,都需要申请对应的开发者并获取对应的 appid。获取对应的appid后打开 manifest 可视化操作填写即可:

Uni-App - 接口 - 第三方登录(小程序)(Hcoder 版)_.net

是否登录判断(App.vue)

global.isLogin = function(){
try{
var suid = uni.getStorageSync('suid');
var srand = uni.getStorageSync('srand');
}catch(e){
//TODO handle the exception
}
if(suid == '' || srand == ''){
return false;
}else{
return [suid, srand];
}
};

需要登录的页面判断

var res = global.isLogin();
if(!res){
uni.showModal({
title:'请登录',
content:"请登录",
success:function(){
uni.navigateTo({
url:"/pages/login"
});
}
})
}

登录页面开发

<template>
<view style="padding:35px;">
<!-- #ifdef MP-WEIXIN -->
<button type="primary" open-type="getUserInfo" @getuserinfo="getuserinfo" withCredentials="true">微信登录</button>
<!-- #endif -->
<!-- #ifdef APP-PLUS -->
<button type="primary" open-type="getUserInfo" @click="getuserinfo" withCredentials="true">微信登录</button>
<!-- #endif -->
<button style="margin-top:50px;">手机号码登录</button>
</view>
</template>
<script>
var _self;
export default {
data:{

},
onLoad:function(){
_self = this;
},
methods:{
getuserinfo : function(res1){
console.log(res1);
//如果只需要opendid 和非加密数据至此登录完成
//此处连接数据库利用openid 就可以进行登录环节
//免费的视频教程 http://www.hcoder.net/tutorials/info_141.html
wx.login({
success:function(res2){
//获取 sessionKey
wx.request({
url : 'https:///hoa.hcoder.net/xcxencode/?c=sk&appid=wxbb7f9f1f2c6f4f33&secret=739b970b832f0df158f54c494a08e440&code='+res2.code,
success:function(res3){
console.log(res3);
//记录到本地
try{
uni.setStorageSync('sk', res3.data.session_key);
uni.setStorageSync('openid', res3.data.openid);
}catch(e){
//TODO handle the exception
}
uni.hideLoading();
//以下步骤可以获取加密信息,需要授权
//获取加密信息
if(!res1.detail.iv){
uni.showToast({
title:"您取消了授权,登录失败",
icon:"none"
});
return false;
}
try{
var sessionKey = uni.getStorageSync('sk');
console.log(sessionKey);
}catch(e){
//TODO handle the exception
}
uni.request({
/**
* $appid = $_POST['appid'];
$sessionKey = $_POST['sessionKey'];
$encryptedData = $_POST['encryptedData'];
$iv = $_POST['iv'];
*/
method : "POST",
url : 'https:///hoa.hcoder.net/xcxencode/',
header : {'content-type':'application/x-www-form-urlencoded'},
data : {
appid : "wxbb7f9f1f2c6f4f33",
sessionKey : sessionKey,
iv : res1.detail.iv,
encryptedData : res1.detail.encryptedData
},
success:function(res4){
//"{"openId":"oS6of0V0rdp9nY_BuvCnQUasOHYc","nickName":"深海",
//"gender":1,"language":"zh_CN","city":"Xi'an","province":"Shaanxi",
//"country":"China","avatarUrl":"https://wx.qlogo.cn/mmopen/vi_32/7iags6YD4enyU"
console.log(res4);
//至此登录完成
}
});
}
})
}
});
}
}
}
</script>
<style>

</style>


举报

相关推荐

0 条评论