| | |
| | | |
| | | import com.google.gson.Gson; |
| | | import com.taoke.autopay.dto.WXAppInfoDto; |
| | | import lombok.Data; |
| | | import net.sf.json.JSONObject; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | import org.yeshi.utils.HttpUtil; |
| | | import org.yeshi.utils.entity.wx.WXAPPInfo; |
| | | |
| | | import java.net.URLEncoder; |
| | | |
| | | /** |
| | | * @author hxh |
| | |
| | | * @date 2024/6/28 17:27 |
| | | */ |
| | | public class WxApiUtil { |
| | | |
| | | private static Logger wxLogger = LoggerFactory.getLogger("wxLogger"); |
| | | |
| | | public class WXAccessTokenInfo { |
| | | private String access_token; |
| | |
| | | } |
| | | } |
| | | |
| | | @Data |
| | | public static class WXUserInfo{ |
| | | private String openid;// 用户的唯一标识 |
| | | private String nickname ;// 用户昵称 |
| | | private Integer sex;// 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知 |
| | | private String province;// 用户个人资料填写的省份 |
| | | private String city ;// 普通用户个人资料填写的城市 |
| | | private String country;// 国家,如中国为CN |
| | | private String headimgurl;// 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。 |
| | | private String unionid;// 只有在用户将公众号绑定到微信开放平台账号后,才会出现该字段。 |
| | | |
| | | } |
| | | |
| | | |
| | | public static WXAccessTokenInfo getAcessTokenInfo(String code, WXAppInfoDto app) throws Exception { |
| | | String tokenUrl = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", app.getAppId(), app.getAppSecret(), code); |
| | | String result = HttpUtil.get(tokenUrl); |
| | | System.out.println(result); |
| | | wxLogger.info(result); |
| | | JSONObject root = JSONObject.fromObject(result); |
| | | if (root.optInt("errcode", 0) != 0) { |
| | | throw new Exception(root.optString("errmsg")); |
| | |
| | | return JsonUtil.getSimpleGson().fromJson(result, WXAccessTokenInfo.class); |
| | | } |
| | | |
| | | public static WXUserInfo getUserInfo(String accessToken,String openid) throws Exception { |
| | | String tokenUrl = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", URLEncoder.encode(accessToken,"UTF-8"),openid); |
| | | String result = HttpUtil.get(tokenUrl); |
| | | result = new String(result.getBytes("ISO-8859-1"),"UTF-8"); |
| | | System.out.println(result); |
| | | wxLogger.info(result); |
| | | JSONObject root = JSONObject.fromObject(result); |
| | | if (root.optInt("errcode", 0) != 0) { |
| | | throw new Exception(root.optString("errmsg")); |
| | | } |
| | | return JsonUtil.getSimpleGson().fromJson(result, WXUserInfo.class); |
| | | } |
| | | |
| | | public static void main(String[] args) throws Exception { |
| | | |
| | | getAcessTokenInfo("061KT5ll2vgWHd4VyIll2UVQZV0KT5lP", new WXAppInfoDto("wx6217429129959b05", "14ae1808a271111954c509d8cb06df92")); |