微信公众号开发需要获取用户的openid,根据微信公众号的官方文档说明,需要做以下几个准备工作
1.开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”配置选项中,修改授权回调域名。请注意,这里填写的是域名。注意:不能是ip地址
如果不进行域名授权配置,微信在授权回调的时候会返回redirect_uri错误。
2.配置域名是要求在web服务器中有微信提供的能访问到的文件,所以还需要一个web服务器,如下图
第一步:跳转到授权页,获取code
appid在微信开发者工具中获取
let urlNow=encodeURIComponent(window.location.href);// let scope='snsapi_userinfo'; //snsapi_userinfo 非静默授权用户有感知 snsapi_base 静默授权用户无感知 let url= 'https://open.'+'/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+urlNow+'&response_type=code&scope=snsapi_userinfo#wechat_redirect';window.location.href = url
授权成功后会重定向的页面中,会带有code参数,通过以下代码获取code,code每5分钟会更新,请勿保存。
getUrlKey:function(name){//获取url 参数return decodeURIComponent((new RegExp('[?|&]'+name+'='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;},
第二步.通过code换取网页授权openid
appsecret在微信开发者工具中获取
this.$axios.get('https://api.'+'/sns/oauth2/access_token?appid='+appid+'&secret='+appsecret+'&code='+code+'&grant_type=authorization_code').then(res=>{this.openid = res.data.openid;}).catch(error=>{})
第三步.解决刚开始的两个问题
3.1由于本地测试没有域名,可以使用natapp用临时域名映射到本地。参考
3.2有了配置后需要配置web服务器,这里我使用Tomcat,下载Tomcat并安装。
打开Tomcat的目录进入webapps目录下,新建文件夹:myapp,并在该目录下创建WEB-INF文件夹,新建web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_3_1.xsd"version="3.1"metadata-complete="true"><display-name>myword</display-name><description><error-code>404</error-code><location>/index.html</location></description></web-app>
将从微信公众号下载下来的text文件放入myapp文件夹下,同时在微信开发者工具配置域名。点击保存
第四步.vue打包
打包前在vue.config.js中配置(这里使用vue-cli3.0)。
publicPath: process.env.NODE_ENV === 'production'? '/myapp/': '/',
执行 npm run build
将打包好的放入tomcat的myapp文件夹下
此时的目录结构如上。
启动Tomcat,mac的启动命令:sudo sh ./startup.sh
5.跨域
由于微信限制,微信授权页面必须在微信开发中工具中打开。由于本地服务和微信接口的api存在跨域问题,本地调试时可以调用一下命令打开微信开发中工具:
open -a /Applications/wechatwebdevtools.app --args --disable-web-security --user-data-dir --allow-running-insecure-content
或者使用Nginx解决跨域问题。
在微信开发中工具中输入: /myapp
vue的完整代码
created(){let code= this.getUrlKey("code");if(code){this.$axios.get('https://api.'+'/sns/oauth2/access_token?appid='+appid+'&secret='+appsecret+'&code='+code+'&grant_type=authorization_code').then(res=>{this.openid = res.data.openid;}).catch(error=>{})}else{this.getCodeApi();}},methods:{getCodeApi(){//获取code let urlNow=encodeURIComponent(window.location.href);// let scope='snsapi_userinfo'; //snsapi_userinfo snsapi_base //静默授权 用户无感知let url= 'https://open./connect/oauth2/authorize?appid='+appid+'&redirect_uri='+urlNow+'&response_type=code&scope=snsapi_userinfo#wechat_redirect';window.location.href = url},getUrlKey:function(name){//获取url 参数return decodeURIComponent((new RegExp('[?|&]'+name+'='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;},},