Java后台生成微信小程序码并以流的形式返回给前端

后端代码

  1. 获取access_token
import net.sf.json.JSONObject;

public class WeChatUtil {
    /**
     * 获取token
     */
    private static String ACCESSTOKENURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";

    /**
     * 获取登陆的token
     *
     * @param appId
     * @param appSecret
     * @return
     * @throws Exception
     */
    public static String getAccessToken(String appId, String appSecret) {
        String url = ACCESSTOKENURL.replace("{appId}", appId).replace("{appSecret}", appSecret);
        JSONObject jsonObject = CommonUtil.httpsRequest(url, "GET", null);
 
        if (null != jsonObject) {
            return  jsonObject.getString("access_token");
        }
        return null;
    }
}
  1. 生成图片流
package com.ruoyi.common.utils;

import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import net.sf.json.JSONObject;

public class QrCodeUtils {

	/**
	 * 生成图片流
	 * @param url
	 * @param paraMap
	 * @return
	 * @throws Exception
	 */
	public static byte[] getminiqrQr(String url, Map<String, Object> paraMap) throws Exception {
		byte[] result = null;
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-Type", "application/json");

		// 设置请求的参数
		JSONObject postData = new JSONObject();
		for (Map.Entry<String, Object> entry : paraMap.entrySet()) {
			postData.put(entry.getKey(), entry.getValue());
		}
		httpPost.setEntity(new StringEntity(postData.toString(), "UTF-8"));
		HttpClient httpClient = HttpClientBuilder.create().build();
		HttpResponse response = httpClient.execute(httpPost);
		HttpEntity entity = response.getEntity();
		result = EntityUtils.toByteArray(entity);
		return result;
	}
}
  1. 后台接口返回流到前端
	import javax.servlet.http.HttpServletResponse;
	import java.io.OutputStream;
	import java.util.Map;
	import java.util.HashMap;

	@GetMapping("/getInviteCode")
	@ResponseBody
	public void getInviteCode(@RequestParam(value = "id") String id,
			HttpServletResponse response) {
		try {
			String accessToken = WeChatUtil.getAccessToken(appId, appSecret);
			byte[] qrCodeBytes = null;
			Map<String, Object> paraMap = new HashMap<String, Object>();
			String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="
					+ accessToken ;
			// 二维码携带参数 不超过32位 参数类型必须是字符串
			paraMap.put("scene", id); // 存入的参数
			paraMap.put("path", "pages/index/index");
			qrCodeBytes = QrCodeUtils.getminiqrQr(url, paraMap);
			response.setContentType("image/jpg");
			// 写入response的输出流中
			OutputStream stream = response.getOutputStream();
			stream.write(qrCodeBytes);
			stream.flush();
			stream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

前端代码

	uni.request({
	    url: baseUrl+'getInviteCode?id='+that.id,
	    method: "GET",
	    responseType: 'arraybuffer',
	    success: function(res) {
	        uni.hideToast();
			let datas = res.data
			const arrayBuffer = new Uint8Array(datas)
			that.codeImg = "data:image/png;base64," + uni.arrayBufferToBase64(arrayBuffer) //这里需要添加前缀
		},
		fail(res) {
			console.log(res, '错误')
		}
	})

你可能感兴趣的:(java,微信小程序,前端)