Java 生成微信小程序二维码

生成二维码图片,拿到图片路径

   @Value("${xcx.AppletAppId}")
    private String appId;
    @Value("${xcx.AppletAppSecret}")
    private String appSecret;
    @Value("${file.uploadFolder}")
    private String uploadFolder;
    @Value("${file.url}")
    private String url;

    @GetMapping("/shareQr")
    @ApiOperation("自评分享码")
    public AjaxResult shareQr( @RequestParam("id") String id  ) throws Exception {
        if (id == null ){
            return AjaxResult.Error("数据异常。");
        }
            String scene = "id=" + id  ; // 替换成自己的参数值
            String name = id;
           // 替换成自己的页面路径
            String page = "pages/choose/detail/index?"+scene; // 替换成自己的页面路径
            String now = DateUtils.format(new Date(), "yyyy-MM-dd");
            String filePath = uploadFolder +"pcQr" + File.separator + now + "-" + name+".png";
            //正式版为 "release",体验版为 "trial",开发版为 "develop"。
            String envVersion = "trial";
            Boolean checkPath = true ;


            MiniProgramQRCode.getQRCode( appId  ,   appSecret , scene , page , filePath  ,  envVersion  ,  checkPath);

        return AjaxResult.Success("success", filePath);
    }
package com.sipsd.util;




import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class MiniProgramQRCode {

    private static final String API_GET_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private static final String API_GET_QR_CODE = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=%s";
//    private static final String API_GET_QR_CODE = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";
//    private static final String API_GET_QR_CODE = "https://api.weixin.qq.com/wxa/getwxacode?access_token=%s";


//    wxacode.get -----A    path
//    获取小程序码,适用于需要的码数量较少的业务场景。通过该接口生成的小程序码,永久有效,有数量限制,详见获取二维码。
//    POST https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN

//    wxacode.getUnlimited  --B   page
//    获取小程序码,适用于需要的码数量极多的业务场景。通过该接口生成的小程序码,永久有效,数量暂无限制。 更多用法详见 获取二维码。
//    POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN
//
//    wxacode.createQRCode -- C   path
//    获取小程序二维码,适用于需要的码数量较少的业务场景。通过该接口生成的小程序码,永久有效,有数量限制,详见获取二维码。
//    POST https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN



    public static void  getQRCode( String appId  ,  String appSecret , String scenes , String pages ,  String filePaths ,String envVersion , Boolean checkPath) throws Exception {
        String accessToken = getToken(appId, appSecret);
        String scene = scenes; // 替换成自己的参数值
        String page = pages; // 替换成自己的页面路径
        int width = 200; // 替换成自己的二维码宽度
        String filePath = filePaths; // 替换成自己的保存路径
        byte[] qrCodeBytes = getQRCode(accessToken, scene, page, width ,  envVersion ,   checkPath);
        FileOutputStream fos = new FileOutputStream(filePath);
        IOUtils.write(qrCodeBytes, fos);
        fos.flush();
        fos.close();
    }
    public static String getToken(String appId, String appSecret) throws Exception {
        String url = String.format(API_GET_TOKEN, URLEncoder.encode(appId, "UTF-8"), URLEncoder.encode(appSecret, "UTF-8"));
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        InputStream is = conn.getInputStream();
        String json = IOUtils.toString(is);
        is.close();
        conn.disconnect();
        return json.substring(json.indexOf("access_token") + "access_token".length() + 3, json.indexOf("expires_in") - 3);
    }
    public static byte[] getQRCode(String accessToken, String scene, String page, int width , String envVersion  ,Boolean checkPath) throws Exception {
        String url = String.format(API_GET_QR_CODE, accessToken);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        if (StringUtils.isNotBlank(scene)) {
            page = page + "?" + scene;
        }
        if (StringUtils.isBlank(envVersion)) {
            envVersion = "release";
        }
//        正式版为 "release",体验版为 "trial",开发版为 "develop"。
//        String json = "{\"page\":\"" + page + "\",\"width\":" + width + ", \"scene\":\"" + scene + "\" ,  \"env_version\":\" "+ envVersion + "\" ,  \"check_path\":\""+ checkPath + "\"      }";
        String json = "{\"path\":\"" + page + "\",\"width\":" + width + ",   \"env_version\":\" "+ envVersion + "\" ,  \"check_path\":\""+ checkPath + "\"      }";
        conn.getOutputStream().write(json.getBytes("UTF-8"));
        InputStream is = conn.getInputStream();
        byte[] qrCodeBytes = IOUtils.toByteArray(is);
        is.close();
        conn.disconnect();
        return qrCodeBytes;
    }






}
  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是Java生成微信小程序带参数二维码的完整代: ```java import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import org.apache.commons.codec.binary.Base64; import org.json.JSONObject; public class WxMaQrcodeUtils { private static final String API_URL = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode"; private static final String PARAM_PAGE = "page"; private static final String PARAM_SCENE = "scene"; private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token"; /** * 获取access_token * * @param appid 小程序appid * @param secret 小程序secret * @return access_token */ public static String getAccessToken(String appid, String secret) { String accessToken = null; try { String url = ACCESS_TOKEN_URL + "?grant_type=client_credential&appid=" + appid + "&secret=" + secret; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = con.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } bufferedReader.close(); JSONObject jsonObject = new JSONObject(stringBuilder.toString()); accessToken = jsonObject.getString("access_token"); } } catch (Exception e) { e.printStackTrace(); } return accessToken; } /** * 生成小程序带参数二维码 * * @param accessToken 小程序access_token * @param page 小程序页面路径 * @param scene 小程序页面参数 * @return base64格式的二维码图片数据 */ public static String createQrcode(String accessToken, String page, String scene) { String base64Image = null; try { Map<String, Object> params = new HashMap<>(); params.put(PARAM_PAGE, page); params.put(PARAM_SCENE, scene); URL obj = new URL(API_URL + "?access_token=" + accessToken); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.setDoOutput(true); con.getOutputStream().write(new JSONObject(params).toString().getBytes("UTF-8")); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = con.getInputStream(); byte[] imageBytes = new byte[inputStream.available()]; inputStream.read(imageBytes); inputStream.close(); base64Image = Base64.encodeBase64String(imageBytes); } } catch (Exception e) { e.printStackTrace(); } return base64Image; } public static void main(String[] args) { String appid = "your_appid"; String secret = "your_secret"; String accessToken = getAccessToken(appid, secret); String page = "pages/index/index"; String scene = "key=value"; String base64Image = createQrcode(accessToken, page, URLEncoder.encode(scene)); System.out.println(base64Image); } } ``` 注意,需要引入Apache Commons Codec库。 其中,getAccessToken方法用于获取小程序的access_token,createQrcode方法用于生成小程序带参数二维码并返回base64格式的图片数据。在main方法中调用以上两个方法即可生成小程序二维码
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

無飞

叠码不易,鼓励鼓励。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值