使用Spring Boot 生成微信小程序二维码进入对应页面携带参数

使用Spring Boot 生成微信小程序二维码进入对应页面携带参数-摘录

来由

最近使用uni-app 开发微信小程序,客户有一个需求就是后台系统能根据后台中的企业信息生成对应的企业微信小程序二维码,提供给企业用户进行扫描注册,从而减少后台系统进行员工信息录入。

个人建议

微信的文档更新速度很快建议先每次开发微信相关的业务最好先看下微信官方的文档再进行百度查询防止编写出问题找不到原因。

微信api

微信二维码有3种类型的具体的可以看微信介绍

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html

我使用的这种:

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.get.html

还有注意微信要是已经上线的小程序才可以,但本地测试也是可以的只是不能上线体验

进入微信公众平台 ->小程序 ->开发 -> 开发管理 ->开发设置->扫普通链接二维码打开小程序

进行相关配置

因为要Java后端生成所以要使用微信的服务端地址生成二维码

请求地址:

POST https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN

后端开发

查看微信的这个请求参数要求携带 access_token 接口凭证 那获取生成二维码的过程就简单了

1 获取ACCESS_TOKEN -> 2 调用微信二维码生成地址

获取 access_token

微信文档:

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html

GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

这里微信要求携带

appid 和secret

JAVA 代码如下:

使用到了fastjson

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.62</version>
		</dependency>
1,创建微信配置类:
@Component
public class WechatConfig {

	public static String wechatMiniAppId;
	public static String wechatMiniSecret;
	
	@Value("${wechat.mini.appid:''}")
	public void setWechatMiniAppId(String wechatMiniAppId) {
		WechatConfig.wechatMiniAppId = wechatMiniAppId;
	}

	@Value("${wechat.mini.secret:''}")
	public void setWechatMiniSecret(String wechatMiniSecret) {
		WechatConfig.wechatMiniSecret = wechatMiniSecret;
	}
	
}
2.yml 配置 参数
#微信开发 属性 具体获取查看微信小程序开发
wechat:
  mini:
    appid : xxxxxx
    secret : xxxxxxxxx
3 .获取access_token

创建一个pojo 接收返回结果

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html

@Data
public class WeChatAccessResult implements Serializable {
    @JSONField(name = "access_token")
    private String accessToken;
    @JSONField(name ="expires_in")
    private String expiresIn;
    @JSONField(name ="errcode")
    private String errCode;
    @JSONField(name ="errmsg")
    private String errMsg;
}

这里的HttpUtils 是我公司在公司封装的一个请求类不好公开可以使用HuTool 中的请求HttpUtils

https://www.hutool.cn/docs/#/http/Http%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%B7%A5%E5%85%B7%E7%B1%BB-HttpUtil

/**
 * 微信小程序配置
 *
 */
@Component
public class WeChatCommon {
    @Value("${wechat.mini.appid}")
    private String appId ;
    @Value("${wechat.mini.secret}")
    private String secret;
    /**
     * 获取微信access_token
     */
    public WeChatAccessResult returnAccessToken() throws IOException {
        if (StringUtils.isNotEmpty(appId) && StringUtils.isNotEmpty(secret)){
            String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;
            String returnBody = HttpUtils.get(url).body();
            WeChatAccessResult weChatAccessResult = JSONObject.parseObject(returnBody, WeChatAccessResult.class);

            return weChatAccessResult;
        }
        return  null;
    }
}
获取微信二维码
1.封装一个请求 POJO

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.get.html

微信官网说

POST 参数需要转成 JSON 字符串,不支持 form 表单提交 所以我使用pojo 然后使用fastjson 转成json字符串

/**
 * 微信请求对象
 * https://developers.weixin.qq.com/miniprogram/
 * dev/api-backend/open-api/qr-code/wxacode.get.html
 */
@Data
public class WeChatQueryObject  implements Serializable {
    private String path;
    private Integer width;
    private boolean auto_color;
//    private Object line_color;
    private  boolean is_hyaline;
}
2.创建生成微信二维码方法
@Component
public class WeChatCommon {

    @Value("${wechat.mini.appid}")
    private String appId ;
    @Value("${wechat.mini.secret}")
    private String secret;
    /**
     * 获取微信access_token
     */
    public WeChatAccessResult returnAccessToken() throws IOException {
        if (StringUtils.isNotEmpty(appId) && StringUtils.isNotEmpty(secret)){
            String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;
            String returnBody = HttpUtils.get(url).body();
            WeChatAccessResult weChatAccessResult = JSONObject.parseObject(returnBody, WeChatAccessResult.class);

            return weChatAccessResult;
        }
        return  null;
    }

    /**
     * @param weChatQueryObject 查询参数
     * @return
     * @throws IOException
     */
    public BufferedInputStream getWxCode(WeChatQueryObject weChatQueryObject) throws IOException{
        WeChatAccessResult weChatAccessResult = returnAccessToken();
        if (weChatAccessResult!=null && StringUtils.isNotEmpty(weChatAccessResult.getAccessToken())
            && weChatQueryObject !=null
        ){
        String  queryURL ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="+weChatAccessResult.getAccessToken();
        String wxParams =JSON.toJSONString(weChatQueryObject);
        return HttpUtils.post(queryURL,wxParams).bodyStream();
        }
        return null;
    }

}
3.创建生成接口并可以下载这个生成的微信二维码图片

我这里是先让其可以下载二维码 然后保存到后台管理系统中,提供给企业使用

/**
     * 微信企业员工注册
     * @param companyWxCode 企业信息
     * @param response   响应
     * @throws Exception
     */
    @RequestMapping(value = "wxCompanyCode.do", method = RequestMethod.GET)
    @ResponseBody
    public void wxCompanyCode(CompanyWxCode companyWxCode, HttpServletResponse response) throws Exception {
        Integer companyId = companyWxCode.getCompanyId();
        if (companyId!=null){
            QMemberTT byId = qMemberTTService.findById(companyId);
            String fileName ="wxCode";
            if (byId !=null) {
                //设置名称 电话号码
                fileName =byId.getQyMobile();
            }
            // TATD 后期添加到yml 中自定义配置
            WeChatQueryObject weChatQueryObject = new WeChatQueryObject();
            //设置参数
            weChatQueryObject.setPath("pages/regist/invitationUser?companyId="+companyId);
            weChatQueryObject.setWidth(340);
            weChatQueryObject.setAuto_color(true);
            //微信二维码封装方法
            BufferedInputStream returnWxCode = WeChatCommon.getWxCode(weChatQueryObject);
            byte[] buf = new byte[1024];
            int len = 0;
            // 非常重要
            response.reset();
            response.setContentType("image/jpeg;");
            response.setHeader("Content-Disposition", "attachment; filename="+fileName+".jpg");

            OutputStream out = response.getOutputStream();
            //让其导出
            while ((len = returnWxCode.read(buf)) > 0){
                out.write(buf, 0, len);
                out.flush();
            }
            returnWxCode.close();
            out.close();
        }else{
            System.out.println("企业信息输入未完全");
        }
    }

前端

这里使用的是uniapp 可以在微信配置好的页面进行业务开发

//接受到参数 方式一 这个可能是uniapp 的params 自动获取的参数 挺强大的
onLoad(option) {
			if (option.companyId) {
				 option.companyId
					console.log(option.companyId)
			}
}, 
//方式二 微信官方提供了这个这个扫码是使用微信那边普通网址链接
      onLoad: function(options) {
    if (options.q) {
     //获取二维码的携带的链接信息
      let qrUrl = decodeURIComponent(options.q)
      console.log(qrUrl)
    } 
  },

以上就可以完成一个带参数的微信小程序二维码,建议还是多看微信文档,开发这个当时没怎么看文档让坑了不少

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Spring Boot接入微信支付需要进行以下几个步骤: 1. 引入依赖:在pom.xml文件中添加相关依赖,包括Spring Boot Web、微信支付SDK、发送http请求的依赖、模板引擎等。 2. 开通JSAPI支付:在开发环境中,需要进行JSAPI支付的开通。具体步骤可以参考微信支付的开发文档。 3. 生成二维码:根据开发模式,在商户后台系统中生成预付交易并生成二维码,或者由商户生成二维码并提供给用户扫描。 4. 用户支付:用户使用微信扫一扫功能扫描二维码,输入密完成支付交易。 以上是使用Spring Boot接入微信支付的一般步骤,具体实现可以根据微信支付的开发文档进行配置和调试。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [【SpringBoot应用篇】接入微信支付](https://blog.csdn.net/qq_45297578/article/details/118115577)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [SpringBoot实现小程序微信支付(超级详细)](https://blog.csdn.net/qq_19007169/article/details/123628306)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值