最近要求做一个h5签到页面,需要是在微信外面扫描二维码链接,不同城市的共事填写个人信息,提交到后盾,实现签到性能。
微信受权文档,
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect\_uri=REDIRECT\_URI&response\_type=code&scope=SCOPE&state=STATE#wechat\_redirect
,这个是获取微信code的申请,
//为测试号id let appid = "你的appid"; // 正式门路 let link = '你的h5正式门路'; //重定向后会带上state参数,我这边的需要要辨别是哪个城市的,不须要参数能够不写state这个字段 let city = 'nj'; window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(link)}&response_type=code&scope=snsapi_base&state=${city}#wechat_redirect`;
我这边只须要获取open,所以用的静默受权scope=snsapi_base
我这边须要判断是否是微信内置浏览器关上,还有截取判断公众号截取code,上面是我这一整个业务的代码:
<template> <div class="index"> <div> <div class="isWechatBrowser" v-if="isWechatText">请用微信内置浏览器关上</div> <alert v-model="isWechatBrowser" title="提醒">请用微信内置浏览器关上</alert> </div> </div></template><script> import { enterData } from "@/assets/js/api"; import { Alert } from "vux"; // 判断是否为公众号模拟器环境 const isWechat = () => { return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger"; }; // 判断公众号截取code const getUrlParam = (name) => { let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); let r = window.location.search.substr(1).match(reg); if (r != null) { return unescape(r[2]); } return null; } export default { name: "index", data() { return { // 弹层,是否是微信内置浏览器 isWechatBrowser: false, // 微信code wxCode: '', isWechatText: false, }; }, components: { Alert }, methods: { // 获取微信code getWxCode() { if (isWechat()) { let code = getUrlParam('code'); this.isWechatText = false; if (code) { this.wxCode = code; console.log(this.wxCode) return; } //为测试号id let appid = "appid"; // 正式门路 let link = '正式门路'; let city = 'nj'; window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(link)}&response_type=code&scope=snsapi_base&state=${city}#wechat_redirect`; } else { // 不是用微信关上链接 this.isWechatBrowser = true; this.isWechatText = true; } }, }, mounted() { // 页面一加载就执行 this.getWxCode(); } };</script><style lang="sass" scoped> </style>
逻辑都在getWxCode()这个办法外面。
先判断是否为公众号模拟器环境。上面调用getUrlParam('code')这个办法,如果有的话,阐明曾经申请获取到了,如果没有获取到的话,就去申请微信接口获取code。获取胜利之后,就能够把code给后端,后端申请拿失去openid了。
下面的代码不多,然而参考了很多的网上的写法,我把这些链接也贴出来,心愿能帮到须要的人。
通过微信网页受权获取用户OpenId(微信公众平台配置我次要参考这个链接)
微信H5受权获取code,拿取用户信息(我次要参考这位前辈的代码,写的真好)
在公众号配置域名
微信开放平台
微信开放平台(另一个),
在看了官网的文档和下面各位前辈的代码后,我这边是实现了需要了的,很感激他们,也心愿能帮到须要的敌人。