package com.ruoyi.system.utils.wx;
|
|
import cn.hutool.http.HttpRequest;
|
import cn.hutool.http.HttpResponse;
|
import cn.hutool.http.HttpUtil;
|
import com.alibaba.fastjson2.JSONObject;
|
import com.icbc.api.internal.util.internal.util.fastjson.JSON;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.data.redis.core.RedisTemplate;
|
import org.springframework.stereotype.Component;
|
import org.springframework.web.client.RestTemplate;
|
|
import java.text.MessageFormat;
|
import java.util.Base64;
|
import java.util.HashMap;
|
import java.util.Map;
|
import java.util.concurrent.TimeUnit;
|
|
@Component
|
public class WxQrCodeUtil {
|
|
@Value("${wx.url}")
|
private String ACCESS_TOKEN_URL;
|
|
@Value("${wx.conf.secretId}")
|
private String memberAppSecret;
|
|
@Value("${wx.conf.appId}")
|
private String wxAppId;
|
@Autowired
|
private RestTemplate restTemplate;
|
|
@Autowired
|
private RedisTemplate redisTemplate;
|
|
@Value("${spring.profiles.active}")
|
private String env;
|
|
private String getAccessToken() {
|
Object o = redisTemplate.opsForValue().get("accessToken");
|
if (o != null) {
|
return o.toString();
|
}
|
String requestUrl = MessageFormat.format(ACCESS_TOKEN_URL, wxAppId, memberAppSecret);
|
String respBody = restTemplate.getForEntity(requestUrl, String.class).getBody();
|
JSONObject jsonObject = JSONObject.parseObject(respBody);
|
String string = jsonObject.getString("access_token");
|
redisTemplate.opsForValue().set("accessToken", string, 5000, TimeUnit.SECONDS);
|
return string;
|
}
|
|
/**
|
*
|
* @param code 推荐码
|
* @param type 推荐人类型 1:股东 2:营销员/合伙人
|
* @param cacheKey 缓存key
|
* @return
|
*/
|
|
public String getQrCodeBase64(String code, Integer type, String cacheKey){
|
String accessToken = getAccessToken();
|
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
|
Map<String, Object> param = new HashMap<>();
|
param.put("page", "pages/home/home");
|
param.put("width", 430); // 二维码尺寸
|
param.put("scene", "code=" + code + "&type=" + type); // 二维码尺寸
|
param.put("env_version", env.equals("prod") ? "release" : "trial"); // 二维码尺寸
|
param.put("check_path", false); //二维码尺寸
|
HttpRequest post = HttpUtil.createPost(url);
|
post.body(JSON.toJSONString(param));
|
|
byte[] result = post.execute().bodyBytes();
|
// base64
|
String img = Base64.getEncoder().encodeToString(result);
|
// 后台用户的小程序码
|
redisTemplate.opsForValue().set(cacheKey, img);
|
return img;
|
}
|
}
|