Java获取小程序带参二维码并保存到本地

业务场景

下载并保存带参数的小程序二维码,用户直接扫描带参二维码就进入小程序,自动根据参数完成部分业务。这个时候就需要用到微信小程序提供的二维码接口 wxacode.getUnlimited ,官方文档地址 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html

网上介绍的很多方法有些过时了,有些不科学,调用起来不方便,所以自己也总结了一份出来。虽然很久之前直接用jfinal+jfinal-wx写的,几句代码就搞定了,但是最近需要迁移项目到SpringBoot2,所以就踩了个坑顺便总结一下,确实找了大半天。

POSTMAN调试

如果一个借口postman都调用不通,那就更别说用java代码去写了,调用接口第一步就是熟悉接口请求方式 method请求格式 Content-Type接口参数 Body/Param以及返回的内容,POSTMAN调用参数过程

  • url https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={{access_token}}
  • json raw { "scene":"EGAG-SAL**-******"}
    在这里插入图片描述

WxUtil封装:下载带参数的小程序二维码


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
 * 微信小程序辅助工具类 https://developers.weixin.qq.com/miniprogram/dev/api-backend/
 * @Author zhengkai.blog.csdn.net
 * */
@Slf4j
public class WxUtil {
    public static String GET_MINICODE_URL="https://api.weixin.qq.com/wxa/getwxacodeunlimit";
    public static String APPID="你的APPID";
    public static String APPSECRET="你的APPSECRET";

    public static String getAccessTokenAsUrl(){
        String tokenStr=HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET+"");
        log.info(tokenStr);
        JSONObject jsonObject = JSONObject.parseObject(tokenStr);
        return "?access_token="+jsonObject.getString("access_token");
    }
    /**
     * 下载带参数的小程序二维码
     * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
     * by zhengkai.blog.csdn.net
     * @param pathStr 保存图片的的path
     * @param certNumber 带过去小程序的参数,一般为你的业务参数,建议是id或者number
     * */
    public static String downloadMiniCode(String pathStr , String certNumber){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("scene",certNumber);
        paramMap.put("is_hyaline",true);
        String imgFilePath = pathStr+"/certificate/"+certNumber+".png";// 新生成的图片
        try
        {
            URL url = new URL(GET_MINICODE_URL+getAccessTokenAsUrl());
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
            httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            printWriter.write(JSON.toJSONString(paramMap));
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            OutputStream os = new FileOutputStream(new File(imgFilePath));
            int len;
            //设置缓冲写入
            byte[] arr = new byte[2048];
            while ((len = bis.read(arr)) != -1)
            {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return imgFilePath;
    }
}

Controller调用

传入保存的 path地址scene参数

WxUtil.downloadMiniCode(storageService.getPathString(),certCompany.getCertNumber());

下载验证

之前试过很多方法就是保存后的png图片无法使用,可能是保存的姿势、方法不对。用这个方法亲测可行
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/moshowgame/article/details/107586571