说明:这里以微信作为第三方登入为例。第三方登入思路都是前端传递code请求第三方登入接口,通过请求获得openId,后端就会通过openId请求第三方的登入(这步交给后端做)。小程序和app端都需要手动通过uni.login这个API来获得code,H5端则通过路径获取code。
一、微信小程序端
loginWX() {
let that = this
uni.login({//首先通过uni.login这个API获取code
provider: "weixin",
success(wxres) {//成功后会返回code
let data ={
loginType: 1,
raw: JSON.stringify(wxres)
}
console.log(wxres,"wxres");
post("user", "thirdPartLogin", data).then(res => {
//然后请求后台第三方登入接口,data中是有code的,请求成功后会获得openId
console.log(res, "登入成功");
uni.showToast({
icon: "success",
title: res.data.errmsg,
duration: 1000
})
setTimeout(function() {
uni.switchTab({
url: '/pages/index/index'
});
}, 1000);
}).catch(err => {
uni.showToast({
icon: "error",
title: err.errmsg,
duration: 1000
})
})
}
})
}
二、app端
loginAPP() {
let that = this
uni.login({
provider: "weixin",
success(wxres) {
let data ={
loginType: 2,
raw: JSON.stringify(wxres)
}
post("user", "thirdPartLogin", data).then(res => {
console.log(res, "登入成功");
uni.showToast({
icon: "success",
title: res.data.errmsg,
duration: 1000
})
setTimeout(function() {
uni.switchTab({
url: '/pages/index/index'
});
}, 1000);
}).catch(err => {
uni.showToast({
icon: "error",
title: err.errmsg,
duration: 1000
})
})
}
})
}
三、H5
新建中转页面loginH5.vue
在根路径下新建config文件,新建index.js文件
/config/index.js中
// 微信公众号APPID(由公司提供)
const WX_APPID = process.env.NODE_ENV === "development"?
"wxfc796989c8321034"://测试账号
"wxfc796989c8321034";//上线账号
// 微信公众号H5回调地址
const CALL_URL = "http://127.0.0.1:8080"+"/pages/public/loginH5"
// console.log(location.origin,555);
export {WX_APPID,CALL_URL}
在第三方登入页面中
import {WX_APPID,CALL_URL} from "@/config/index.js"//引入封装的变量
loginH5() {
let BACKURL = encodeURIComponent(CALL_URL); //用户获取code的页面地址,获取code后需要请求后台接口
console.log(CALL_URL, "123");
let url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WX_APPID + "&redirect_uri=" +
BACKURL + "&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect";
console.log(url, "回调地址");
window.location.href = url
}
说明:引号中的代码不需要改,只需要改引入的变量名
4.实现第三方登入
/pages/public/loginH5中
<template>
<div>我是h5页面</div>
</template>
<script>
import {
post,get
} from "@/uilt/http.js"
onload(options){
const that = this;
const code = options?.code//获取code
let data ={
loginType: 3,
raw: code
}
post("user", "thirdPartLogin", data).then(res => {
console.log(res, "登入成功");
uni.showToast({
icon: "success",
title: res.data.errmsg,
duration: 1000
})
setTimeout(function() {
uni.switchTab({
url: '/pages/index/index'
});
}, 1000);
}).catch(err => {
uni.showToast({
icon: "error",
title: err.errmsg,
duration: 1000
})
})
}
</script>