Obtain openid from public account

Step 1:
First go to the WeChat public platform to log in to the WeChat public platform and enable two things, one is web page authorization and the second is to configure your domain name

Then encapsulate a method. It should be noted that there are several things you need to change here. 1. There are two
places in the getWxCode method. 1. Your appid. 2. Your front-end address.
2. A place in the getTokenByCode method. Your interface address.
 

// 用于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,
}

 Then use it directly here, and pass your front-end routing address here.

//  #ifdef H5
				// this.$refs.weblogin.show = true
				this.$login.isLoginAndwxLoginH5Login('/#/pages/clue/index')
				// #endif

A page is needed to parse the 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>

Guess you like

Origin blog.csdn.net/cwb_2120/article/details/131596208