后端代码
- 获取access_token
import net.sf.json.JSONObject;public class WeChatUtil {private static String ACCESSTOKENURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";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;}
}
- 生成图片流
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 {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;}
}
- 后台接口返回流到前端
import javax.servlet.http.HttpServletResponse;import java.io.OutputStream;import java.util.Map;import java.util.HashMap;@GetMapping("/getInviteCode")@ResponseBodypublic 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 ;paraMap.put("scene", id); paraMap.put("path", "pages/index/index");qrCodeBytes = QrCodeUtils.getminiqrQr(url, paraMap);response.setContentType("image/jpg");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.dataconst arrayBuffer = new Uint8Array(datas)that.codeImg = "data:image/png;base64," + uni.arrayBufferToBase64(arrayBuffer) },fail(res) {console.log(res, '错误')}})