Java 生成 微信小程序码 (getwxacodeunlimit)

1.java 代码

package cn.xyz.commons.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
 
import com.alibaba.fastjson.JSON;

import cn.xyz.commons.autoconfigure.KApplicationProperties.WXConfig;
import cn.xyz.mianshi.utils.SKBeanUtils;
 /**
  * 
  * @author cf
  * @date 2019年8月27日 下午12:12:15
  */
public class WXXCXUtil {
 
	private static WXConfig wxConfig =SKBeanUtils.getLocalSpringBeanManager().getApplicationConfig().getWxConfig();
	//获取小程序连接
		private final static String GETWXACODEUNLIMIT=
				"https://api.weixin.qq.com/wxa/getwxacodeunlimit";
		
	/**
     * @return
     */
    public static Map getToken() {
        Map data = new HashMap();
        try {
            // ======================================================================//
            // 拼接调用微信的URL
            // grant_type:client_credential
            // appid:小程序
            // secret:小程序
            // ======================================================================//
            StringBuilder urlSb = new StringBuilder();
            urlSb.append("https://api.weixin.qq.com/cgi-bin/token");
            urlSb.append("?");
            urlSb.append("grant_type=%s&appid=%s&secret=%s");
            String tokenUrl = String.format(urlSb.toString(), "client_credential", wxConfig.getXcxappid(), wxConfig.getXcxsecret());
            // ======================================================================//
            // 执行URL Get调用
            // ======================================================================//
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(tokenUrl);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String resultText = EntityUtils.toString(httpEntity, "utf-8");
            // ======================================================================//
            // 处理HTTP返回结果
            // ======================================================================//
            @SuppressWarnings("unchecked")
            Map resultMap = JSON.parseObject(resultText, Map.class);
            if (resultMap != null) {
                if (resultMap != null && resultMap.size() > 0) {
                    // 合并2次调用结果
                    Set keySet = resultMap.keySet();
                    for (Object key : keySet) {
                        if (!data.containsKey(key)) {
                            data.put((String) key, resultMap.get(key));
                        }
                    }
                }
            }
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return data;
    }
 
    /**
     * @param accessToken
     * @param page
     * @param scene
     * @param width
     * @return
     */
    public static Map getMiniQrCode(String accessToken, String page, String scene, int width) {
        Map data = new HashMap();
        try {
            // ======================================================================//
            // 拼接调用微信的URL
            // ======================================================================//
            String url = GETWXACODEUNLIMIT+"?access_token=" + accessToken;
            Map paramsMap = new HashMap<>();
            paramsMap.put("page", page);
            paramsMap.put("scene", scene);
            paramsMap.put("width", width <= 0 ? 430 : width);
            paramsMap.put("auto_color", false);
            Map line_color = new HashMap();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            paramsMap.put("line_color", line_color);
            System.out.println("调用生成微信URL接口传参:" + paramsMap);
            // ======================================================================//
            // 执行URL Post调用
            // ======================================================================//
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            // 必须是json模式的 post
            String body = JSON.toJSONString(paramsMap);
            StringEntity entity = new StringEntity(body);
            entity.setContentType("image/png");
            httpPost.setEntity(entity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            // ======================================================================//
            // 处理HTTP返回结果
            // ======================================================================//
            InputStream contentStream = httpEntity.getContent();
            byte[] bytes = toByteArray(contentStream);
            contentStream.read(bytes);
            // 返回内容
            data.put("qrLength", bytes.length);
            data.put("qrBytes", bytes);
            data.put("qrBytesEncoder", Base64.getEncoder().encodeToString(bytes));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用生成微信小程序码URL接口异常"+e);
        }
        return data;
    }
 
    /**
     * @param input
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        copy(input, output);
        return output.toByteArray();
    }
 
    /**
     * @param input
     * @param output
     * @return
     * @throws IOException
     */
    public static int copy(InputStream input, OutputStream output) throws IOException {
        long count = copyLarge(input, output);
        if (count > 2147483647L) {
            return -1;
        }
        return (int) count;
    }
 
    /**
     * @param input
     * @param output
     * @return
     * @throws IOException
     */
    public static long copyLarge(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[4096];
        long count = 0L;
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        String access_token = (String) WXXCXUtil.getToken().get("access_token");
        Map data = WXXCXUtil.getMiniQrCode(access_token, "pages/index/index",
                "btype=1&border=xxx",60);
        String qrBytesEncoder = (String) data.get("qrBytesEncoder");
        Integer qrLength = (Integer) data.get("qrLength");
        System.out.println(qrBytesEncoder);
        System.out.println(qrLength);
        byte[] qrBytes = (byte[]) data.get("qrBytes");
        //saveToImg("d://qrcode.png",qrBytes);
    }
 
    /**
     * @param imgPath
     * @param bytes
     * @return
     */
    public static int saveToImg(String imgPath, byte[] bytes) {
        int stateInt = 1;
        try {
            FileOutputStream fos = new FileOutputStream(imgPath);
            fos.write(bytes);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            stateInt = 0;
            e.printStackTrace();
        } finally {
        }
        return stateInt;
    }
 
} 
  

2.小程序代码

onLoad: function (options) {
    var that = this;

    var logs = wx.getStorageSync('logs') || []
    

    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      //&是我们定义的参数链接方式
      let toUserId = scene.split("&")[0];
      let inviteCode = scene.split('&')[1];
      //其他逻辑处理。。。。。
      this.setData({
        toUserId: toUserId,
        inviteCode: inviteCode
      })

    }
}

 

你可能感兴趣的:(java,小程序)