第一步:
先去微信公众平台登录微信公众平台,去开启两个东西,一个是网页授权权限,第二个是配置你的域名
然后封装一个方式, 要注意的是,这里需要几个东西要你自己更改
1. getWxCode 方法有两个地方 1 你的appid 2 你的前端地址
2. getTokenByCode 方法里的 一个地方 你的接口地址
// 用于h5获取公众号的openid
//有三个地方需要修改
//getWxCode 方法有两个地方 1 你的appid 2 你的前端地址
//getTokenByCode 方法里的 一个地方 你的接口地址
//判断字符串是否为空
const stringIsEmpty = function(obj) {
if (typeof obj == "undefined" || obj == null || obj == "") {
return true;
} else {
return false;
}
}
const costomShowToast = function(title, duration = 2000) {
uni.showToast({
title: title,
duration: duration,
icon: 'none',
})
}
/**
* 判断是否是在微信打开
*/
const isWechat = function() {
return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}
/**
* 获取微信登录code
* @param {Object} redirect_path
*/
const getWxCode = function(redirect_path) {
if (isWechat()) {
//微信公众号appid
let appid = 'wx2c4c4b729532d64f'
// 微信回调url
let redirect_uri = encodeURIComponent('https://gpt.dpcloud.top' + redirect_path)
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
appid +
'&redirect_uri=' +
redirect_uri +
'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
//redirect_uri地址里面不能多/,如果多一个/就会跳转不成功,所以redirect_path要注意是/pages/clue/cule
// redirect_uri是授权成功后,跳转的url地址,微信会帮我们跳转到该链接,并且通过?的形式拼接code,这里需要用encodeURIComponent对链接进行处理。
// 如果配置参数一一对应,那么此时已经通过回调地址刷新页面后,你就会再地址栏中看到code了。
// http://127.0.0.1/pages/views/profile/login/login?code=001BWV4J1lRzz00H4J1J1vRE4J1BWV4q&state=1
} else {
costomShowToast('请在微信客户端打开!');
}
}
/**
* 对外方法,对外调用就这个就可以,判断微信H5登录并跳转到相应的地址toUrl
* @param {Object} toUrl 要跳转的地址
*/
const isLoginAndwxLoginH5Login = function(toUrl) {
getWxCode(toUrl);
}
module.exports = {
stringIsEmpty,
isLoginAndwxLoginH5Login,
}
然后这边直接使用,这里传你前端的路由地址
// #ifdef H5
// this.$refs.weblogin.show = true
this.$login.isLoginAndwxLoginH5Login('/#/pages/clue/index')
// #endif
需要一个页面来解析code
<template>
<view>
授权登录中请稍后...
</view>
</template>
<script>
export default {
onReady() {
// 获取code
const params = this.getQueryParams()
// 把code传过去
this.getCode(params)
},
methods: {
// 获取地址栏参数
getQueryParams() {
var queryParams = {};
// 获取当前页面的URL
var url = window.location.href;
// 创建URLSearchParams对象并传入URL的查询参数部分
var searchParams = new URLSearchParams(url.split('?')[1]);
// 遍历URLSearchParams对象,将参数和值添加到queryParams对象中
for (var param of searchParams.entries()) {
queryParams[param[0]] = param[1];
}
return queryParams;
},
// 根据code获取openid
getCode (params) {
// 根据code,请求返回openid、access token等信息
this.$http.request({
url: 'chatgpt_api/user/wechat/code_to_openid',
data: {
code: params.code
},
mask: 1
}, res => {
this.login(res.data)
})
},
login (params) {
this.$http.request({
url: 'chatgpt_api/user/login_by_openid',
data: {
open_id: params.openid,
username: params.nickname,
avatar: params.headimgurl
},
mask: 1
}, res => {
uni.setStorageSync('token', res.data.show_msg.token)
uni.redirectTo({
url: '/pages/index/index'
})
window.location.reload();
})
}
},
}
</script>
<style scoped>
page{
background-color: #fff;
}
</style>