微信网页 H5 授权获取用户信息

198 阅读2分钟

介绍一下

微信公众号:如果用户在微信客户端中访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑。

云函数:云函数是运行在云端的 JavaScript 代码,是基于 Node.js 的扩展。

一、微信公众平台接口测试帐号申请

无需公众帐号、快速申请接口测试号,直接体验和测试公众平台所有高级接口

申请地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
文档地址:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

二、测试号管理

  1. 获取测试号信息
appID
appsecret
//本地测试环境域名
127.0.0.1:5173

2. JS 接口安全域名修改

WX20250305-114945@2x.png 3. 修改网页授权获取用户基本信息

WX20250305-114659@2x.png

三、网页开发

uni-app 文档地址

https://uniapp.dcloud.net.cn/tutorial/vue3-composition-api.html
  1. 在 uni-app 中使用,Vue3 组合式 API 开发 H5
<template>
	<view>
		<p>This is WeChat H5 login</p>
		<p>userInfo:{{userInfo}}</p>
	</view>
</template>

<script setup>
	import { ref } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	const userInfo = ref('userInfo')
	const appid = 'wx3b6698c6f3749cf0';
	onLoad(async() => {
		// 获取当前页面完整 url 地址
		let url = window.location.href;
		let code = null;

		// 判断 url 中有没有code=字符串,没有跳转到授权页面  
		if (url.indexOf('code=') == -1) {
			let currentURL = encodeURIComponent(url);
			
			//scope 为 snsapi_userinfo
			let redirect_uri = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${currentURL}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
			window.location.href = redirect_uri;
		} else {
			//回调函数已经执行 返回的链接存在code= 地址解析
			let code = url.split("code=")[1].split("&")[0];
			//对 getUserOpenid 云函数发送请求传参 code 获取用户信息
			const res = await uniCloud.callFunction({
				name: 'getUserOpenid',
				data: {
					code: code
				},
			})
			console.log(res.result)
			if(res.result.code==200){
				userInfo.value=res.result.userInfo
			}
		}		
	})
</script>

<style>

</style>
  1. 使用 uniCloud 的云函数
'use strict';
const axios = require('axios');

//微信公众平台 测试号信息
const APPID = 'wx3b6698c6f3749cf0';
const SECRET = '2fe77717925a83a17a8c29033500f72a';

exports.main = async (event, context) => {
	// 1.用户同意授权,获取code ,event 为客户端上传的参数
	const { code } = event;  
	const url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${APPID}&secret=${SECRET}&code=${code}&grant_type=authorization_code`;

	try {
		//2.通过 code 换取网页授权 access_token
		const response = await axios.get(url); 
		const { openid,access_token } = response.data;
		
		//3.拉取用户信息(需scope为 snsapi_userinfo)
		const userinfoURL = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`;
		const userInfo = await axios.get(userinfoURL);
		return {
			code: 200,
			userInfo: userInfo.data
		};
	} catch (error) {
		return {
			code: 400,
			error: error
		};
	}
};
  1. 通过 HTTP URL 方式访问云函数

代码调整

const body = JSON.parse(event.body);

文档地址

https://doc.dcloud.net.cn/uniCloud/http.html#request-url

4. 示例代码

// 以uni.request为例
uni.request({
  method: 'POST',
  url: 'https://${云函数Url化域名}/${functionPath}',
  data: {
    a: 1,
    b: 2
  },
  success(res) {
    console.log(res);
  }
})

// 云函数收到的event为, 注意如果直接return此格式数据可能会被作为集成响应处理,参考下面的集成响应文档
{
    path: '/',
    httpMethod: 'POST',
    headers: {
    	...
    	"content-type": 'application/json'
    },
    isBase64Encoded: false,
    body: '{"a":1,"b":2}', // 注意此处可能是base64,需要根据isBase64Encoded判断
}

  1. 最后获取用户信息展示

WX20250305-122337@2x.png