Java后台生成小程序二维码

微信小程序官方文档https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html

在此使用接口B获取大量小程序码

接口B

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

 以下将获取token和生成结合了

package com.ajia.zhengding.cms.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.net.HttpURLConnection;
import java.net.URL;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.EncodeHintType;

/**
 * @author huangzheng
 */
public class WxUtill {
    /**
     * @return access_token
     * @throws Exception
     */
    public static String postToken() throws Exception {
        String apiKey = "";//小程序id
        String secretKey = "";//小程序密钥
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + apiKey + "&secret=" + secretKey;
        URL url = new URL(requestUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes("");
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        if (requestUrl.contains("nlp"))
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        else
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        JSONObject jsonObject = JSON.parseObject(result);
        String accesstoken = jsonObject.getString("access_token");
        return accesstoken;
    }

    /**
     * 生成带参小程序二维码
     *
     * @param sceneStr    参数
     * @param accessToken token
     */
    public static Map getminiqrQr(String sceneStr, String accessToken) {
        Map retMap = null;
        try {
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", sceneStr);
            paramJson.put("page", "pages/index/main");
            paramJson.put("width", 430);
            paramJson.put("auto_color", true);


            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            /*ByteArrayOutputStream os = new ByteArrayOutputStream();*/
            OutputStream os = new FileOutputStream(new File("D:/test/2.jpg"));
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
//            // 上传到oss
//            String fileName = CurrentTimeMillisId.next() + ".jpg";
//            String urls = createFilePath(fileName, sourceType);
//            InputStream is = new ByteArrayInputStream(os.toByteArray());
//            String miniCodeUrl = ossFileService.uploadFile(is, urls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retMap;
    }

    public static void main(String[] args) throws Exception {
        String accessToken = postToken();
        System.out.println("获取的accessToken:" + accessToken);
        System.out.println("D:/test/2.jpg");
//        getminiqrQr("HelloApplet", accessToken);
//        getminiqrQr("2/17613/9216", accessToken);
//        getminiqrQr("1/17613/475", accessToken);
        getminiqrQr("0/17613", accessToken);
    }


}
  • 其中paramJson.put("page", "pages/index/main");路径得看前端是怎么约定的,我这是pages/index/main
  • 我方完整访问路径“pages/index/main?2/17613/9216”
  • scene 中只填写参数(有可能前端没意识到参数放在scene对象中或前端没解码导致扫描二维码后不能跳转到指定页面)
  • scene最大32个字符,且不能有特殊字符。(生成的二维码图片报错经常是这个两个原因)
  • 如果生成的图片报错,可以将后缀改成txt打开后有报错信息
  • 在线调试工具https://cli.im/weapp
  • 参考https://blog.csdn.net/qq_36537546/article/details/88914643

 生成效果:

Java后台生成小程序二维码_第1张图片

你可能感兴趣的:(java)