Java生成微信小程序码

Posted 天葬

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    

项目根目录生成小程序码

生成微信小程序码java实现

 @Override
    public ModelAndView onSubmit(HttpServletRequest req, HttpServletResponse res, WxQrCodeForm cmd, BindException err) throws Exception {
        SimpleResult<Object> result = SimpleResult.create(false);
        Locale locale = new Locale("en", "US");
        ResourceBundle resource = ResourceBundle.getBundle("config/wx-config", locale);   //读取属性文件
        String appId = resource.getString("appId"); //开发者设置中的appId
        String secret = resource.getString("appSecret"); //开发者设置中的appSecret
        AccessToken accessToken = null;
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
        JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET", null);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new AccessToken();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getIntValue("expires_in"));
            } catch (JSONException e) {
                accessToken = null;
                // 获取token失败
                logger.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getIntValue("errcode"), jsonObject.getString("errmsg"));
            }
        }
        String token = accessToken.getToken();
        getminiqrQr(token);
        return ModelAndViewUtil.json(result);
    }

    public Map getminiqrQr(String accessToken) {
        RestTemplate rest = new RestTemplate();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            String url = "https://api.weixin.qq.com/weixin/getwxacode?access_token=" + accessToken;
            Map<String, Object> param = new HashMap<>();
            param.put("path", "pages/search/search"); //跳转到查询物流(自定义)
            param.put("width", 430);
            param.put("auto_color", false);
            Map<String, Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
            logger.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(JSON.toJSONString(param), headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            logger.info("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
            byte[] result = entity.getBody();
            logger.info(Base64.encodeBase64String(result));
            inputStream = new ByteArrayInputStream(result);
            File file = new File("/Users/apple/Desktop/abc.png");
            if (!file.exists()) {
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            logger.error("调用小程序生成微信永久小程序码URL接口异常", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

 

以上是关于Java生成微信小程序码的主要内容,如果未能解决你的问题,请参考以下文章

微信小程序码如何生成 微信小程序码生成方法攻略教程大全

微信小程序 获取小程序码和二维码java接口开发

微信小程序菊花码生成

微信小程序菊花码生成

微信小程序生成太阳码

微信小程序码如何弄怎么生成 获取小程序二维码方法