说明一下我现在的具备的条件:开发阶段,没有外网地址,也没有域名
-
建议可以先安装一个微信开发者工具,方便调试,如果不安装也可以,直接用pc微信访问,下载地址 微信开发者工具
-
准备一个域名,如果没有申请好的域名,可以先自己临时定一个,比如www.shouqi6.com, 注意,一定要是一个域名, 如果暂时没有域名, 为了测试, 可以先做映射: 打开C:\Windows\System32\drivers\etc下的hosts (可以用记事本打开), 将域名映射到本地:
编辑
添加图片注释,不超过 140 字(可选)
-
登录微信开放平台,进行网页授权域名设置:
编辑切换为居中
添加图片注释,不超过 140 字(可选)
编辑切换为居中
添加图片注释,不超过 140 字(可选)
4.将自己的微信号添加到公众号的开发者里
编辑切换为居中
添加图片注释,不超过 140 字(可选)
编辑切换为居中
添加图片注释,不超过 140 字(可选)
开发者在自己的微信上接受邀请,即可完成绑定。
5.找到公众号的appid
编辑切换为居中
添加图片注释,不超过 140 字(可选)
6.至此, 公众号需要做的操作基本完成, 终于开始编码 示例:
授权链接参数说明详见:网页授权 | 微信开放文档
在微信或微信开发者工具上打开页面, 注意运行这段代码前, 需要保证是在80端口下启动, redirect_uri里不能带端口号
<!-- 注册页面 --> <template> <view class="bottom-side-otherLogin" @click="getWeChatCode" v-if="isWeixin"> <text>其他社交账号登录</text> <image src="https://xuezhifu-resource.oss-cn-hangzhou.aliyuncs.com/newxuefu/mwx/wx.png"></image> </view> </template> <script> export default { data() { return { isWeixin: false, }; }, onLoad() { this.isWeixin = this.isWechat() if(this.isWeixin){ this.checkWeChatCode()//通过微信官方接口获取code之后,会重新刷新设置的回调地址【redirect_uri】 } }, onShow() { }, mounted() { }, methods: { /*微信登录相关 start*/ //方法:用来判断是否是微信内置的浏览器 isWechat() { return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger"; }, //方法:用来提取code getUrlCode(name) { return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1] .replace(/\+/g, '%20')) || null }, //请求微信接口,用来获取code getWeChatCode() { let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址 let appid = '自己的appid' //打开授权链接: 通过微信官方接口获取code之后,会重新刷新设置的回调地址【redirect_uri】 window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + local + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"; }, //检查浏览器地址栏中微信接口返回的code checkWeChatCode() { let code = this.getUrlCode('code') uni.showToast({ title:`微信code=${code}` }) if (code) { this.getOpenidAndUserinfo(code) } }, //把code传递给后台接口,静默登录 getOpenidAndUserinfo(code) { this.$http({ url:'api/login', data:{ code:code } }).then((res) => { console.log(res) if (res.code != 0) { uni.showToast({ title: res.msg, duration: 3000, icon: 'none' }); return }else{ this.afterLogin(res) } }) }, /*微信登录相关 end*/ afterLogin(res){ let user = res.data.user uni.setStorageSync('token', res.data.token); let u = { avatar: user.avatar ? user.avatar : this.avatar, mobile: user.mobile, nickname: user.nickname ? user.nickname : '土肥圆' } uni.setStorage({ key: 'u', data: u, success: () => { let url = uni.getStorageSync('redirect') uni.reLaunch({ url: url ? url : '/pages/index' }) } }); }, }, } </script>
终于授权成功, 关于服务端的下次继续