微信公众号:生成二维码,扫码进入指定的H5页面并获取openid,实现自定义分享【完整过程,附主要代码】

您所在的位置:网站首页 扫描屏幕二维码进入百度账号绑定页面 微信公众号:生成二维码,扫码进入指定的H5页面并获取openid,实现自定义分享【完整过程,附主要代码】

微信公众号:生成二维码,扫码进入指定的H5页面并获取openid,实现自定义分享【完整过程,附主要代码】

2023-11-22 04:06| 来源: 网络整理| 查看: 265

文章目录 说明一、生成二维码,指定跳转路径二、进入指定的H5页面,并获取openid总结

说明

功能:需要生成二维码,识别二维码后进入指定H5页面,获取到使用人的openid,然后进行自己其他操作。

这篇文章主要记录的是生成二维码、跳转到指定页面的模块。

使用框架如下: 后端:jeecgboot Web、 H5:Vue3

一、生成二维码,指定跳转路径

方式1、微信提供了生成二维码的接口,可直接调用获取 文档地址:微信公众开发者文档 避坑点:开启公众号的服务器配置,JS域名配置等,白名单配置;具体的可以看一看微信公众号开发。

方式2【推荐】:使用草料二维码进行生成,带有扫描后进入的页面路径 生成地址:草料二维码生成地址 注意:跳转到自己的后台微信验证方法,并获取到openid拼接到H5页面,在H5页面通过截取的方式获取到openid。

1、确定回调域名并构造URL,一个参考地址

https://open.weixin.qq.com/connect/oauth2/authorize?appid=微信公众号id&redirect_uri=后端验证方法接口&connect_redirect=1#wechat_redirect

参数说明:【网址需要encodeURL】 在这里插入图片描述

2、后端验证方法接口方法:使用WxOAuth2AccessToken类进行微信验证 (1)引入依赖

com.github.binarywang weixin-java-mp 4.1.0

(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 org.jeecg.common.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 用于获取用户的openid String code = req.getParameter("code"); //获取openid String 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分钟未被使用自动过期。 所以缓存code redisUtil.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 bar to.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`) //微信按钮进入 携带openid console.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);

自定义分享可参考我的这篇文章:微信公众号自定义分享

总结

第一次接触扫码功能的编程,在前端上踩了挺多坑的呜呜呜呜,特此做一个记录。 前端菜鸡,若有错误请指正。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3