com.zopen.wechat.mp.service.WechatMpOauth2Service Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of zopen-ato-starter Show documentation
Show all versions of zopen-ato-starter Show documentation
Alibaba Tencent And Others For Spring Boot.
package com.zopen.wechat.mp.service;
import com.google.gson.Gson;
import com.zcj.util.UtilString;
import com.zopen.wechat.exception.WechatAssert;
import com.zopen.wechat.exception.WechatException;
import com.zopen.wechat.mp.dto.oauth2.UserInfo;
import com.zopen.wechat.mp.dto.oauth2.WebAccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component("atoWechatMpOauth2Service")
public class WechatMpOauth2Service {
private static final Logger logger = LoggerFactory.getLogger(WechatMpOauth2Service.class);
@Autowired
private RestTemplate restTemplate;
public String getAuthorizeUrl(String redirectUrl, String state, String appId) {
WechatAssert.notNullAndEmpty(redirectUrl, "redirect_uri 不能为空");
WechatAssert.notNullAndEmpty(appId, "app_id 不能为空");
return String.format(WechatHttpUrl.OAUTH2_AUTHORIZE_USER_INFO, appId, redirectUrl, state == null ? "" : state);
}
public WebAccessToken getWebAccessToken(String code, String appId, String appSecret) {
if (UtilString.isBlank(code) || "authdeny".equals(code)) {
throw new WechatException("回调时获取微信 code 失败,请检查微信的配置是否正确");
}
WechatAssert.notNullAndEmpty(appId, "app_id 不能为空");
WechatAssert.notNullAndEmpty(appSecret, "secret 不能为空");
WechatAssert.notNullAndEmpty(code, "code 不能为空");
String url = String.format(WechatHttpUrl.OAUTH2_ACCESS_TOKEN, appId, appSecret, code);
String accessTokenRespStr = restTemplate.getForObject(url, String.class);
WechatAssert.notNullAndEmpty(accessTokenRespStr, "获取网页授权凭证失败:接口返回的内容为空");
WebAccessToken accessToken = new Gson().fromJson(accessTokenRespStr, WebAccessToken.class);
WechatAssert.notNull(accessToken, "获取网页授权凭证失败");
accessToken.valid("获取网页授权凭证失败");
logger.debug("获取网页授权凭证成功,内容:" + accessToken.toString());
return accessToken;
}
public UserInfo getUserInfo(String webAccessToken, String openId) {
WechatAssert.notNullAndEmpty(webAccessToken, "access_token 不能为空");
WechatAssert.notNullAndEmpty(openId, "open_id 不能为空");
String url = String.format(WechatHttpUrl.OAUTH2_USER_INFO, webAccessToken, openId);
String userInfoRespStr = restTemplate.getForObject(url, String.class);
WechatAssert.notNullAndEmpty(userInfoRespStr, "获取用户信息失败:接口返回的内容为空");
UserInfo userInfo = new Gson().fromJson(userInfoRespStr, UserInfo.class);
WechatAssert.notNull(userInfo, "获取用户信息失败");
userInfo.valid("获取用户信息失败");
logger.debug("获取用户信息成功,内容:" + userInfo.toString());
return userInfo;
}
}