WeiXinUtil.java 1.64 KB
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
package com.lyms.talkonlineweb.util;

import lombok.extern.log4j.Log4j2;

import java.util.HashMap;
import java.util.Map;

/**
* @ProjectName: talkonline
* @Package: com.lyms.talkonlineweb.util
* @ClassName: WeiXinUtil
* @Author: lqy
* @Description: 微信接口调用
* @Date: 2021-09-13 18:10
* @Version:
*/
@Log4j2
public class WeiXinUtil {
//微信返回的key定义
private static final String OPEN_ID_KEY = "openid";
/**
* 获取微信用户的openid
*
* @param code 登录时获取的code
* @return 微信方获取openid
*/
public static String getWxOpenId(String code) {
if (StringUtil.isEmpty(code)) {
return null;
}
try {
StringBuilder reqUrl = new StringBuilder();
reqUrl.append("/sns/jscode2session?appid=").append(Constant.PAT_APP_ID).
append("&secret="). append(Constant.WX_SECRET).append("&js_code=").append(code).
append("&grant_type=").append(Constant.GRANT_TYPE);
log.info("getWxOpenId url : {}",reqUrl);
String response = HttpUtil.getData(Constant.WEIXIN_SERVER + reqUrl);

log.info("getWxOpenId jscode2session response : {}" , response);
if (StringUtil.isNotEmpty(response))
{
Map<String, Object> result = JsonUtil.str2Map(response, HashMap.class);
if (result.containsKey(OPEN_ID_KEY))
{
return result.get(OPEN_ID_KEY).toString();
}
}
} catch (Exception e) {
log.error("getWxOpenId by code: {}", code, e);
}
return null;
}

}