package com.sinata.web.controller.tool.weChat; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpUtil; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; /** * 微信工具类 */ @Slf4j @Component public class WeChatUtil { @Value("wxedd0252e100ab5c2") private String wxAppletsAppid; @Value("15f25b47540c78cc29aae8d71d144628") private String wxAppletsAppSecret; // @Value("${wx.appid}") private String webAppId; // @Value("${wx.appSecret}") private String webAppSecret; /** * 小程序使用jscode获取openid * @param jscode * @return */ public Map code2Session(String jscode) { String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxAppletsAppid + "&secret=" + wxAppletsAppSecret + "&js_code=" + jscode + "&grant_type=authorization_code"; HttpRequest get = HttpUtil.createGet(url); HttpResponse response = get.execute(); int status = response.getStatus(); if(200 != status){ throw new RuntimeException(response.body()); } JSONObject jsonObject = JSON.parseObject(response.body()); int errcode = jsonObject.getIntValue("errcode"); Map map = new HashMap<>(); map.put("errcode", errcode); if(errcode == 0){//成功 map.put("openid", jsonObject.getString("openid")); map.put("sessionKey", jsonObject.getString("session_key")); map.put("unionid", jsonObject.getString("unionid")); return map; } if(errcode == -1){//系统繁忙,此时请开发者稍候再试 map.put("msg", jsonObject.getString("errmsg")); return map; } if(errcode == 40029){//code 无效 map.put("msg", jsonObject.getString("errmsg")); return map; } if(errcode == 45011){//频率限制,每个用户每分钟100次 map.put("msg", jsonObject.getString("errmsg")); return map; } return null; } }