Java生成微信小程序码

官网文档地址:获取小程序码

package test;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: Mr.Fang
 * @create: 2023-04-03 17:06
 **/

public class WxUtils {

    /**
     * description: 获取token,返回结果为 JSON 自行转 map
     * create by: Mr.Fang
     *
     * @return: java.lang.String
     * @date: 2023/4/3 17:46
     */
    public String getToken() throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        Map<String, Object> params = new HashMap<>();
        params.put("appid", "appid");
        params.put("secret", "secret");
        params.put("grant_type", "client_credential");

        String url = handleParams("https://api.weixin.qq.com/cgi-bin/token", params);
        HttpGet httpGet = new HttpGet(url);

        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity(); // 响应结果

        return EntityUtils.toString(entity, CharSetType.UTF8.getType());
    }

    /**
     * description: 对象转 字符串
     * create by: Mr.Fang
     *
     * @param obj
     * @return: java.lang.String
     * @date: 2023/4/3 17:45
     */
    public String objToStr(Object obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        if (Objects.nonNull(obj)) {
            try {
                return objectMapper.writeValueAsString(obj);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * description:  字符串 转 对象转
     * create by: Mr.Fang
     *
     * @param jsonStr
     * @param objClass
     * @return: java.lang.String
     * @date: 2023/4/3 17:45
     */
    public <T> T strToObj(String jsonStr, Class<T> objClass) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            T t = objectMapper.readValue(jsonStr, objClass);
            return t;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    
    /**
     * description: 生成小程序码
     * create by: Mr.Fang
     *
     * @param scene 携带参数
     * @param page  页面路径
     * @param token token
     * @param path  保存路径
     * @return: java.lang.String
     * @date: 2023/5/11 14:22
     */
    public String appletQR(String scene, String page, String token, String path) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        Map<String, Object> params = new HashMap<>();
        params.put("scene", scene);
        params.put("page", page); //developer为开发版;trial为体验版;formal为正式版;默认为正式版
        params.put("env_version", "develop"); //要打开的小程序版本。正式版为 "release",体验版为 "trial",开发版为 "develop"。默认是正式版。
        HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token);
        httpPost.addHeader("ContentTyp", "application/json");

        // 参数转 JSON 格式
        String json = objToStr(params);
        StringEntity stringEntity = new StringEntity(json, CharSetType.UTF8.getType());
        stringEntity.setContentEncoding(CharSetType.UTF8.getType());
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity(); // 响应结果
        byte[] data;
        try {
            data = readInputStream(entity.getContent());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        if (data.length < 100) { // 异常
            String error = new String(data);
            return null;
        }
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".png";
        String filePath = path + File.separator + fileName;
        // 创建文件
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(filePath);
            fileOutputStream.write(data);
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 释放资源
        try {
            assert fileOutputStream != null;
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * description: 输入流转字节数组
     * create by: Mr.Fang
     *
     * @param inStream 输入流
     * @return: byte[]
     * @date: 2023/5/11 11:52
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        // 每次读取的字符串长度,如果为-1,代表全部读取完毕
        int len = 0;
        // 使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            // 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        // 关闭输入流
        inStream.close();
        // 把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    public static void main(String[] args) throws IOException {
        WxUtils wxUtils = new WxUtils();
        // 获取 token
        String token = wxUtils.getToken();
        // 字符串转 map 对象
        Map map = wxUtils.strToObj(token, Map.class);
        // 生成小程序码
        String path = wxUtils.appletQR("2023", "pages/index/index", map.get("access_token").toString(), System.getProperty("user.dir") + File.separator);
        System.out.println(path);
    }

}

项目根目录生成小程序码

posted @ 2023-05-11 14:47  天葬  阅读(182)  评论(0编辑  收藏  举报