/src/main/java/com/penuel/mythopoet/service/WxAuthService.java
Java | 264 lines | 181 code | 41 blank | 42 comment | 16 complexity | 4bb101993714dd8fd966894e378b5185 MD5 | raw file
- package com.penuel.mythopoet.service;
- import com.alibaba.fastjson.JSONObject;
- import com.penuel.mythopoet.dao.WxAuthUserDAO;
- import com.penuel.mythopoet.model.Orders;
- import com.penuel.mythopoet.model.WxAuthUser;
- import com.penuel.mythopoet.utils.Constants;
- import com.penuel.mythopoet.utils.HttpClientUtil;
- import com.penuel.mythopoet.utils.WxPayUtil;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import java.io.UnsupportedEncodingException;
- import java.net.URLEncoder;
- import java.util.SortedMap;
- import java.util.TreeMap;
- /**
- * WxAuthService Created with mythopoet.
- * User: penuel (penuel.leo@gmail.com)
- * Date: 15/4/23 下午9:26
- * Desc: http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
- */
- @Service
- public class WxAuthService {
- private static final Logger LOGGER = LoggerFactory.getLogger(WxAuthService.class);
- /** 获取code url */
- public static final String CODE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=%s&scope=%s&state=%s#wechat_redirect";
- public static final String CODE_RECALL_URL = Constants.get("HOST_URL")+"/auth/wxcode";
- public static final String SHARE_CODE_RECALL_URL = Constants.get("HOST_URL")+"/share/wxcode";
-
- /** 获取 accesstoken url */
- public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=%s";
- /** 获取 openid url */
- public static final String REFRESH_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=%s&refresh_token=%s";
- /** 获取 jsapi_ticket url*/
- public static final String REFRESH_JSAPI_TICKET_URL="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi";
- /** 获取 jsapi_accesstoken url
- * http://mp.weixin.qq.com/wiki/15/54ce45d8d30b6bf6758f68d2e95bc627.html*/
- public static final String REFRESH_JSAPI_ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
- @Autowired
- private WxAuthUserDAO wxAuthUserDAO;
- public WxAuthUser getByUserId(long userId) {
- return wxAuthUserDAO.getByUserId(userId);
- }
- public int add(WxAuthUser wxAuthUser) {
- return wxAuthUserDAO.insert(wxAuthUser);
- }
- /**
- * @param
- * @return {
- * {
- "access_token":"ACCESS_TOKEN",
- "expires_in":7200,
- "refresh_token":"REFRESH_TOKEN",
- "openid":"OPENID",
- "scope":"SCOPE",
- "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
- }
- */
- public int getAccessToken(WxAuthUser wxAuthUser) {
- String accessTokenUrl = genrateAccessTokenUrl(wxAuthUser.getCode());
- String content = HttpClientUtil.sendGetRequest(accessTokenUrl, "UTF-8");
- LOGGER.info("WxAuthService.getAccessToken content = "+content);
- JSONObject obj = JSONObject.parseObject(content);
- // if ( ERR_CODE_INVALID_CRE.equals(obj.getString("errcode")) ){
- // return refreshAccessToken(wxAuthUser);
- // }
- wxAuthUser.setAccessToken(obj.getString("access_token"));
- wxAuthUser.setExpiresIn(obj.getLongValue("expires_in"));
- wxAuthUser.setRefreshToken(obj.getString("refresh_token"));
- wxAuthUser.setOpenId(obj.getString("openid"));
- wxAuthUser.setScope(obj.getString("scope"));
- wxAuthUser.setUnionId(obj.getLongValue("unionid"));
- return wxAuthUserDAO.updateAccessToken(wxAuthUser);
- }
-
- public WxAuthUser getAccessToken(String code, Long userId) {
- String accessTokenUrl = genrateAccessTokenUrl(code);
- String content = HttpClientUtil.sendGetRequest(accessTokenUrl, "UTF-8");
- LOGGER.info("WxAuthService.getAccessToken content = " + content);
- JSONObject obj = JSONObject.parseObject(content);
- WxAuthUser wxAuthUser = wxAuthUserDAO.getByOpenId(obj.getString("openid"));
- if (wxAuthUser == null) {
- wxAuthUser = new WxAuthUser();
- wxAuthUser.setCode(code);
- wxAuthUser.setUserId(userId);
- wxAuthUser.setAccessToken(obj.getString("access_token"));
- wxAuthUser.setExpiresIn(obj.getLongValue("expires_in"));
- wxAuthUser.setRefreshToken(obj.getString("refresh_token"));
- wxAuthUser.setOpenId(obj.getString("openid"));
- wxAuthUser.setScope(obj.getString("scope"));
- wxAuthUser.setUnionId(obj.getLongValue("unionid"));
- wxAuthUserDAO.add(wxAuthUser);
- }else{
- wxAuthUser.setCode(code);
- //wxAuthUser.setUserId(userId);
- wxAuthUser.setAccessToken(obj.getString("access_token"));
- wxAuthUser.setExpiresIn(obj.getLongValue("expires_in"));
- wxAuthUser.setRefreshToken(obj.getString("refresh_token"));
- wxAuthUser.setOpenId(obj.getString("openid"));
- wxAuthUser.setScope(obj.getString("scope"));
- wxAuthUser.setUnionId(obj.getLongValue("unionid"));
- wxAuthUserDAO.updateAccessToken(wxAuthUser);
- }
- return wxAuthUser;
- }
- /**
- * @param wxAuthUser
- * @return {
- * "access_token":"ACCESS_TOKEN",
- * "expires_in":7200,
- * "refresh_token":"REFRESH_TOKEN",
- * "openid":"OPENID",
- * "scope":"SCOPE"
- * }
- */
- public int refreshAccessToken(WxAuthUser wxAuthUser) {
- String accessTokenUrl = refreshAccessTokenUrl(wxAuthUser.getRefreshToken());
- String content = HttpClientUtil.sendGetRequest(accessTokenUrl, "UTF-8");
- JSONObject obj = JSONObject.parseObject(content);
- int errcode = obj.getIntValue("errcode");
- LOGGER.info("WxAuthService.refreshAccessToken content = "+content+",errcode="+errcode);
- if ( errcode == 40001 || errcode == 41001){//invalid credential, access_token is invalid or not latest
- getAccessToken(wxAuthUser);
- }
- wxAuthUser.setAccessToken(obj.getString("access_token"));
- wxAuthUser.setExpiresIn(obj.getLongValue("expires_in"));
- wxAuthUser.setRefreshToken(obj.getString("refresh_token"));
- wxAuthUser.setOpenId(obj.getString("openid"));
- wxAuthUser.setScope(obj.getString("scope"));
- return wxAuthUserDAO.updateAccessToken(wxAuthUser);
- }
- public int refreshJsapiAccessToken(WxAuthUser wxAuthUser){
- String content = HttpClientUtil.sendGetSSLRequest(getRefreshJsapiAccesstokenUrl(),"UTF-8");
- LOGGER.info("WxAuthService.refreshJsapiAccessToken content = "+content+",authUser="+JSONObject.toJSONString(wxAuthUser));
- JSONObject obj = JSONObject.parseObject(content);
- int errcode = obj.getIntValue("errcode");
- if ( errcode == 0 ){//OK
- String access_token = obj.getString("access_token");
- long expires_in = obj.getLongValue("expires_in");
- wxAuthUser.setJsapiToken(access_token);
- wxAuthUser.setJsapiTokenExpiresIn(expires_in);
- return wxAuthUserDAO.updateJsapiToken(wxAuthUser);
- }else{
- return 0;
- }
- }
- public int refreshJsapiTicket(WxAuthUser wxAuthUser) {
- String jsapiTicketUrl = refreshJsapiTicket(wxAuthUser.getJsapiToken());
- String content = HttpClientUtil.sendGetRequest(jsapiTicketUrl, "UTF-8");
- LOGGER.info("WxAuthService.refreshJsapiTicket content = "+content);
- JSONObject obj = JSONObject.parseObject(content);
- int errcode = obj.getIntValue("errcode");
- String errmsg = obj.getString("errmsg");
- if ( errcode == 40001 || errcode == 41001 || errcode == 42001){//invalid credential, access_token is invalid or not latest,42001=access_token expired
- refreshJsapiAccessToken(wxAuthUser);
- jsapiTicketUrl = refreshJsapiTicket(wxAuthUser.getJsapiToken());
- content = HttpClientUtil.sendGetRequest(jsapiTicketUrl, "UTF-8");
- obj = JSONObject.parseObject(content);
- errcode = obj.getIntValue("errcode");
- }
- if ( errcode != 0 ){
- LOGGER.error("WxAuthService.refreshJsapiTicket Error: errcode="+errcode+",errmsg="+errmsg);
- return 0;
- }
- wxAuthUser.setJsapiTicket(obj.getString("ticket"));
- wxAuthUser.setJsapiExpiresIn(obj.getLongValue("expires_in"));
- return wxAuthUserDAO.updateJsapiTicket(wxAuthUser);
- }
- public SortedMap<Object, Object> fillJsapiTicketParam(String jsapiTicket,String url) {
- SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
- parameters.put("noncestr", PayService.genNonceStr());
- parameters.put("jsapi_ticket", jsapiTicket);
- long timestamp = System.currentTimeMillis()/1000;
- parameters.put("timestamp", String.valueOf(timestamp));
- parameters.put("url", url);
- String sign = WxPayUtil.createSha1Sign(parameters);
- parameters.put("sign", sign);
- parameters.put("appId",Constants.get("APP_ID"));
- return parameters;
- }
- private String genrateCodeUrl(String state) {
- try {
- String redirect_url = URLEncoder.encode(CODE_RECALL_URL, "UTF-8");
- return String.format(CODE_URL, Constants.get("APP_ID"), redirect_url, "code", "snsapi_base", state);
- } catch ( UnsupportedEncodingException e ) {
- LOGGER.error("WxAuthService.genrateCodeUrl Error:", e);
- }
- return null;
- }
-
- private String genrateShareCodeUrl(String state) {
- try {
- String redirect_url = URLEncoder.encode(SHARE_CODE_RECALL_URL, "UTF-8");
- return String.format(CODE_URL, Constants.get("APP_ID"), redirect_url, "code", "snsapi_base", state);
- } catch ( UnsupportedEncodingException e ) {
- LOGGER.error("WxAuthService.genrateCodeUrl Error:", e);
- }
- return null;
- }
- private String genrateAccessTokenUrl(String code) {
- return String.format(ACCESS_TOKEN_URL, Constants.get("APP_ID"), Constants.get("APP_AUTH_SECRET"), code, "authorization_code");
- }
- /**
- * @param accessToken
- * @return
- */
- private String refreshAccessTokenUrl(String accessToken) {
- return String.format(REFRESH_ACCESS_TOKEN_URL, Constants.get("APP_ID"), "refresh_token", accessToken);
- }
- private String refreshJsapiTicket(String accessToken) {
- return String.format(REFRESH_JSAPI_TICKET_URL, accessToken);
- }
- public String authorizeURL(Long userId, Long orderId) {
- return genrateCodeUrl(orderId + "@" + userId);
- }
-
- public String authorizeURL(Long userId, String currentUrl) {
- return genrateShareCodeUrl(currentUrl + "@" + userId);
- }
- public String getRefreshJsapiAccesstokenUrl(){
- return String.format(REFRESH_JSAPI_ACCESSTOKEN_URL,Constants.get("APP_ID"),Constants.get("APP_AUTH_SECRET"));
- }
- public int clearWxUserCodeByUserId(long userId) {
- return wxAuthUserDAO.clearCodeByUserId(userId);
- }
- }