1. 介绍
页面加载之前先通过微信授权获取openid(账号唯一标识)
2. 公众号管理者授权
添加开发人员为该公众号的开发者和运营者
3. 使用测试账号
-
配置测试账号信息,可以使用本地 ip 测试公共号授权功能,192.168.xx.xx是本机局域网ip,8080是项目启动端口,要记得关注测试号的公众号
-
使用微信开发者工具本地测试,这里数据上面配置的本地 ip 和 port
-
vue 项目,在 app.vue 中获取 openid
<template><div id="app"><router-view /></div> </template><script> export default {created() {let code = this.getUrlCode("code");const appId = "xxxxxxxxxxxxxx"; // 使用测试账号中的 appidconst secret = "xxxxxxxxxxxxxxxxxxxxxxxx"; // 使用测试账号中的 appsecret// 获取 codeif (!code) {const redirectUri = encodeURIComponent(window.location.href);const scope = "snsapi_userinfo";const state = "123";const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;window.location.href = url;}// 获取 access_token、openIdif (code) {this.axios.get("/sns/oauth2/access_token", {params: {appid: appId,secret: secret,code: code,grant_type: "authorization_code"}}).then(resp => {console.log(resp.data);window.localStorage.setItem("pms_openid", resp.data.openid);});}},methods: {// 获取地址栏的参数getUrlCode(name) {return ((new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(location.href) || [, ""])[1].replace(/\+/g, "%20") || null);}} }; </script>
-
需要注意的地方:获取 access_token、openId 是调用微信api接口,会出现跨域,以下是通过 nginx 代理解决办法
// 开发 module.exports = {devServer: {host: "0.0.0.0",open: true,proxy: {'/sns': {target: 'https://api.weixin.qq.com',secure: true, // 如果是https接口,需要配置这个参数changeOrigin: true,}}} }// 线上# 请求微信获取openid接口location /sns {proxy_pass https://api.weixin.qq.com;}
-
开发需要的 appid 和 appsecret
更多细节可以参考微信官方文档
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html