文章目录
说明一、生成二维码,指定跳转路径二、进入指定的H5页面,并获取openid总结说明
功能:需要生成二维码,识别二维码后进入指定H5页面,获取到使用人的openid,然后进行自己其他操作。
这篇文章主要记录的是生成二维码、跳转到指定页面的模块。
使用框架如下:
后端:jeecgboot
Web、 H5:Vue3
一、生成二维码,指定跳转路径
方式1、微信提供了生成二维码的接口,可直接调用获取
文档地址:微信公众开发者文档
避坑点:开启公众号的服务器配置,JS域名配置等,白名单配置;具体的可以看一看微信公众号开发。
方式2【推荐】:使用草料二维码进行生成,带有扫描后进入的页面路径
生成地址:草料二维码生成地址
注意:跳转到自己的后台微信验证方法,并获取到openid拼接到H5页面,在H5页面通过截取的方式获取到openid。
1、确定回调域名并构造URL,一个参考地址
https://open./connect/oauth2/authorize?appid=微信公众号id&redirect_uri=后端验证方法接口&connect_redirect=1#wechat_redirect
参数说明:【网址需要encodeURL】
2、后端验证方法接口方法:使用WxOAuth2AccessToken类进行微信验证
(1)引入依赖
<dependency><groupId>com.github.binarywang</groupId><artifactId>weixin-java-mp</artifactId><version>4.1.0</version></dependency>
(2)验证的方法:
@Slf4j@RequiredArgsConstructor(onConstructor_ = @Autowired)@RestController@RequestMapping("wx/redirect/{appid}")public class WxRedirectController {private final WxMpService wxMpService;private final WxMpProperties properties;private final RedisUtil redisUtil;private final IWxUserService wxUserService;/*** 微信验证* @param req :* @param resp :* @return mon.api.vo.Result* @author 张雪*/@GetMapping("index")public void index(@PathVariable String appid, HttpServletRequest req, HttpServletResponse resp) throws Exception {if (!this.wxMpService.switchover(appid)) {throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));}//菜单按钮的回调code 用于获取用户的openidString code = req.getParameter("code");//获取openidString openid = "";WxOAuth2AccessToken accessToken = this.wxMpService.getOAuth2Service().getAccessToken(code);redisUtil.set("get_access_token",accessToken.getAccessToken());WxOAuth2UserInfo user = this.wxMpService.getOAuth2Service().getUserInfo(accessToken, null);openid = user.getOpenid();//code只能使用一次,5分钟未被使用自动过期。 所以缓存coderedisUtil.set(code, openid, 5 * 60);// 跳转到前端的路径带有#,vue的router模式需要使用hash模式String page = properties.getUrl().getH5Url().concat("/#/base/index?openid=").concat(openid);// 重定向resp.sendRedirect(page);}}
二、进入指定的H5页面,并获取openid
在vue的permission.js中通过router来截取到传递过来的openid :
const redirect = '/base/index'router.beforeEach((to, from, next) => {NProgress.start() // start progress barto.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`)//微信按钮进入 携带openidconsole.log("微信按钮进入-参数:",to.query)if (to.path === redirect) {//把openid放置到仓库storage.set(OPENID, to.query.openid, 7 * 24 * 60 * 60 * 1000)console.log(storage.get(OPENID));}next()})
在其他页面上使用时:
this.openid = storage.get(OPENID);
自定义分享可参考我的这篇文章:微信公众号自定义分享
总结
第一次接触扫码功能的编程,在前端上踩了挺多坑的呜呜呜呜,特此做一个记录。
前端菜鸡,若有错误请指正。
微信公众号:生成二维码 扫码进入指定的H5页面并获取openid 实现自定义分享【完整过程 附主要代码】