|
|
@@ -0,0 +1,42 @@
|
|
|
+package com.mrxu.framework.common.weixin.api;
|
|
|
+
|
|
|
+import cn.hutool.http.HttpUtil;
|
|
|
+import com.alibaba.fastjson.JSONObject;
|
|
|
+import com.mrxu.framework.common.util.MrxuAssert;
|
|
|
+import lombok.SneakyThrows;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+
|
|
|
+import java.net.URLEncoder;
|
|
|
+
|
|
|
+@Slf4j
|
|
|
+public class WxAuth2Api {
|
|
|
+
|
|
|
+ private static String authorizeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize";
|
|
|
+
|
|
|
+ private static String getUserUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code";
|
|
|
+
|
|
|
+ @SneakyThrows
|
|
|
+ public static String getAuth2Url(String appId,String redirectUri) {
|
|
|
+ StringBuilder redirectUrl = new StringBuilder();
|
|
|
+ redirectUrl.append(authorizeUrl);
|
|
|
+ redirectUrl.append("?appid=").append(appId);
|
|
|
+ redirectUrl.append("&redirect_uri=").append(URLEncoder.encode(redirectUri, "UTF-8"));
|
|
|
+ redirectUrl.append("&response_type=code&scope=snsapi_base&state=wx#wechat_redirect");
|
|
|
+ return redirectUrl.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String getOpenId(String appId,String appSecret,String code) {
|
|
|
+ StringBuilder sb = new StringBuilder(getUserUrl);
|
|
|
+ sb.append("&appid="+appId);
|
|
|
+ sb.append("&secret="+appSecret);
|
|
|
+ sb.append("&code="+code);
|
|
|
+ String queryUrl = sb.toString();
|
|
|
+ log.info("auth2认证获取微信用户信息url:{}",queryUrl);
|
|
|
+ String rs = HttpUtil.get(queryUrl);
|
|
|
+ log.info("auth2认证返回结果:{}",rs);
|
|
|
+ JSONObject rsJson = JSONObject.parseObject(rs);
|
|
|
+ MrxuAssert.isEmpty(rsJson.getString("errmsg"),rsJson.getString("errmsg"));
|
|
|
+ return rsJson.getString("openid");
|
|
|
+ }
|
|
|
+
|
|
|
+}
|