PageRenderTime 414ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/src/main/java/com/penuel/mythopoet/service/WxAuthService.java

https://gitlab.com/tycoon/mythopoet
Java | 264 lines | 181 code | 41 blank | 42 comment | 16 complexity | 4bb101993714dd8fd966894e378b5185 MD5 | raw file
  1. package com.penuel.mythopoet.service;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.penuel.mythopoet.dao.WxAuthUserDAO;
  4. import com.penuel.mythopoet.model.Orders;
  5. import com.penuel.mythopoet.model.WxAuthUser;
  6. import com.penuel.mythopoet.utils.Constants;
  7. import com.penuel.mythopoet.utils.HttpClientUtil;
  8. import com.penuel.mythopoet.utils.WxPayUtil;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.stereotype.Service;
  13. import java.io.UnsupportedEncodingException;
  14. import java.net.URLEncoder;
  15. import java.util.SortedMap;
  16. import java.util.TreeMap;
  17. /**
  18. * WxAuthService Created with mythopoet.
  19. * User: penuel (penuel.leo@gmail.com)
  20. * Date: 15/4/23 下午9:26
  21. * Desc: http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
  22. */
  23. @Service
  24. public class WxAuthService {
  25. private static final Logger LOGGER = LoggerFactory.getLogger(WxAuthService.class);
  26. /** 获取code url */
  27. 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";
  28. public static final String CODE_RECALL_URL = Constants.get("HOST_URL")+"/auth/wxcode";
  29. public static final String SHARE_CODE_RECALL_URL = Constants.get("HOST_URL")+"/share/wxcode";
  30. /** 获取 accesstoken url */
  31. 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";
  32. /** 获取 openid url */
  33. 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";
  34. /** 获取 jsapi_ticket url*/
  35. public static final String REFRESH_JSAPI_TICKET_URL="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi";
  36. /** 获取 jsapi_accesstoken url
  37. * http://mp.weixin.qq.com/wiki/15/54ce45d8d30b6bf6758f68d2e95bc627.html*/
  38. public static final String REFRESH_JSAPI_ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
  39. @Autowired
  40. private WxAuthUserDAO wxAuthUserDAO;
  41. public WxAuthUser getByUserId(long userId) {
  42. return wxAuthUserDAO.getByUserId(userId);
  43. }
  44. public int add(WxAuthUser wxAuthUser) {
  45. return wxAuthUserDAO.insert(wxAuthUser);
  46. }
  47. /**
  48. * @param
  49. * @return {
  50. * {
  51. "access_token":"ACCESS_TOKEN",
  52. "expires_in":7200,
  53. "refresh_token":"REFRESH_TOKEN",
  54. "openid":"OPENID",
  55. "scope":"SCOPE",
  56. "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
  57. }
  58. */
  59. public int getAccessToken(WxAuthUser wxAuthUser) {
  60. String accessTokenUrl = genrateAccessTokenUrl(wxAuthUser.getCode());
  61. String content = HttpClientUtil.sendGetRequest(accessTokenUrl, "UTF-8");
  62. LOGGER.info("WxAuthService.getAccessToken content = "+content);
  63. JSONObject obj = JSONObject.parseObject(content);
  64. // if ( ERR_CODE_INVALID_CRE.equals(obj.getString("errcode")) ){
  65. // return refreshAccessToken(wxAuthUser);
  66. // }
  67. wxAuthUser.setAccessToken(obj.getString("access_token"));
  68. wxAuthUser.setExpiresIn(obj.getLongValue("expires_in"));
  69. wxAuthUser.setRefreshToken(obj.getString("refresh_token"));
  70. wxAuthUser.setOpenId(obj.getString("openid"));
  71. wxAuthUser.setScope(obj.getString("scope"));
  72. wxAuthUser.setUnionId(obj.getLongValue("unionid"));
  73. return wxAuthUserDAO.updateAccessToken(wxAuthUser);
  74. }
  75. public WxAuthUser getAccessToken(String code, Long userId) {
  76. String accessTokenUrl = genrateAccessTokenUrl(code);
  77. String content = HttpClientUtil.sendGetRequest(accessTokenUrl, "UTF-8");
  78. LOGGER.info("WxAuthService.getAccessToken content = " + content);
  79. JSONObject obj = JSONObject.parseObject(content);
  80. WxAuthUser wxAuthUser = wxAuthUserDAO.getByOpenId(obj.getString("openid"));
  81. if (wxAuthUser == null) {
  82. wxAuthUser = new WxAuthUser();
  83. wxAuthUser.setCode(code);
  84. wxAuthUser.setUserId(userId);
  85. wxAuthUser.setAccessToken(obj.getString("access_token"));
  86. wxAuthUser.setExpiresIn(obj.getLongValue("expires_in"));
  87. wxAuthUser.setRefreshToken(obj.getString("refresh_token"));
  88. wxAuthUser.setOpenId(obj.getString("openid"));
  89. wxAuthUser.setScope(obj.getString("scope"));
  90. wxAuthUser.setUnionId(obj.getLongValue("unionid"));
  91. wxAuthUserDAO.add(wxAuthUser);
  92. }else{
  93. wxAuthUser.setCode(code);
  94. //wxAuthUser.setUserId(userId);
  95. wxAuthUser.setAccessToken(obj.getString("access_token"));
  96. wxAuthUser.setExpiresIn(obj.getLongValue("expires_in"));
  97. wxAuthUser.setRefreshToken(obj.getString("refresh_token"));
  98. wxAuthUser.setOpenId(obj.getString("openid"));
  99. wxAuthUser.setScope(obj.getString("scope"));
  100. wxAuthUser.setUnionId(obj.getLongValue("unionid"));
  101. wxAuthUserDAO.updateAccessToken(wxAuthUser);
  102. }
  103. return wxAuthUser;
  104. }
  105. /**
  106. * @param wxAuthUser
  107. * @return {
  108. * "access_token":"ACCESS_TOKEN",
  109. * "expires_in":7200,
  110. * "refresh_token":"REFRESH_TOKEN",
  111. * "openid":"OPENID",
  112. * "scope":"SCOPE"
  113. * }
  114. */
  115. public int refreshAccessToken(WxAuthUser wxAuthUser) {
  116. String accessTokenUrl = refreshAccessTokenUrl(wxAuthUser.getRefreshToken());
  117. String content = HttpClientUtil.sendGetRequest(accessTokenUrl, "UTF-8");
  118. JSONObject obj = JSONObject.parseObject(content);
  119. int errcode = obj.getIntValue("errcode");
  120. LOGGER.info("WxAuthService.refreshAccessToken content = "+content+",errcode="+errcode);
  121. if ( errcode == 40001 || errcode == 41001){//invalid credential, access_token is invalid or not latest
  122. getAccessToken(wxAuthUser);
  123. }
  124. wxAuthUser.setAccessToken(obj.getString("access_token"));
  125. wxAuthUser.setExpiresIn(obj.getLongValue("expires_in"));
  126. wxAuthUser.setRefreshToken(obj.getString("refresh_token"));
  127. wxAuthUser.setOpenId(obj.getString("openid"));
  128. wxAuthUser.setScope(obj.getString("scope"));
  129. return wxAuthUserDAO.updateAccessToken(wxAuthUser);
  130. }
  131. public int refreshJsapiAccessToken(WxAuthUser wxAuthUser){
  132. String content = HttpClientUtil.sendGetSSLRequest(getRefreshJsapiAccesstokenUrl(),"UTF-8");
  133. LOGGER.info("WxAuthService.refreshJsapiAccessToken content = "+content+",authUser="+JSONObject.toJSONString(wxAuthUser));
  134. JSONObject obj = JSONObject.parseObject(content);
  135. int errcode = obj.getIntValue("errcode");
  136. if ( errcode == 0 ){//OK
  137. String access_token = obj.getString("access_token");
  138. long expires_in = obj.getLongValue("expires_in");
  139. wxAuthUser.setJsapiToken(access_token);
  140. wxAuthUser.setJsapiTokenExpiresIn(expires_in);
  141. return wxAuthUserDAO.updateJsapiToken(wxAuthUser);
  142. }else{
  143. return 0;
  144. }
  145. }
  146. public int refreshJsapiTicket(WxAuthUser wxAuthUser) {
  147. String jsapiTicketUrl = refreshJsapiTicket(wxAuthUser.getJsapiToken());
  148. String content = HttpClientUtil.sendGetRequest(jsapiTicketUrl, "UTF-8");
  149. LOGGER.info("WxAuthService.refreshJsapiTicket content = "+content);
  150. JSONObject obj = JSONObject.parseObject(content);
  151. int errcode = obj.getIntValue("errcode");
  152. String errmsg = obj.getString("errmsg");
  153. if ( errcode == 40001 || errcode == 41001 || errcode == 42001){//invalid credential, access_token is invalid or not latest,42001=access_token expired
  154. refreshJsapiAccessToken(wxAuthUser);
  155. jsapiTicketUrl = refreshJsapiTicket(wxAuthUser.getJsapiToken());
  156. content = HttpClientUtil.sendGetRequest(jsapiTicketUrl, "UTF-8");
  157. obj = JSONObject.parseObject(content);
  158. errcode = obj.getIntValue("errcode");
  159. }
  160. if ( errcode != 0 ){
  161. LOGGER.error("WxAuthService.refreshJsapiTicket Error: errcode="+errcode+",errmsg="+errmsg);
  162. return 0;
  163. }
  164. wxAuthUser.setJsapiTicket(obj.getString("ticket"));
  165. wxAuthUser.setJsapiExpiresIn(obj.getLongValue("expires_in"));
  166. return wxAuthUserDAO.updateJsapiTicket(wxAuthUser);
  167. }
  168. public SortedMap<Object, Object> fillJsapiTicketParam(String jsapiTicket,String url) {
  169. SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
  170. parameters.put("noncestr", PayService.genNonceStr());
  171. parameters.put("jsapi_ticket", jsapiTicket);
  172. long timestamp = System.currentTimeMillis()/1000;
  173. parameters.put("timestamp", String.valueOf(timestamp));
  174. parameters.put("url", url);
  175. String sign = WxPayUtil.createSha1Sign(parameters);
  176. parameters.put("sign", sign);
  177. parameters.put("appId",Constants.get("APP_ID"));
  178. return parameters;
  179. }
  180. private String genrateCodeUrl(String state) {
  181. try {
  182. String redirect_url = URLEncoder.encode(CODE_RECALL_URL, "UTF-8");
  183. return String.format(CODE_URL, Constants.get("APP_ID"), redirect_url, "code", "snsapi_base", state);
  184. } catch ( UnsupportedEncodingException e ) {
  185. LOGGER.error("WxAuthService.genrateCodeUrl Error:", e);
  186. }
  187. return null;
  188. }
  189. private String genrateShareCodeUrl(String state) {
  190. try {
  191. String redirect_url = URLEncoder.encode(SHARE_CODE_RECALL_URL, "UTF-8");
  192. return String.format(CODE_URL, Constants.get("APP_ID"), redirect_url, "code", "snsapi_base", state);
  193. } catch ( UnsupportedEncodingException e ) {
  194. LOGGER.error("WxAuthService.genrateCodeUrl Error:", e);
  195. }
  196. return null;
  197. }
  198. private String genrateAccessTokenUrl(String code) {
  199. return String.format(ACCESS_TOKEN_URL, Constants.get("APP_ID"), Constants.get("APP_AUTH_SECRET"), code, "authorization_code");
  200. }
  201. /**
  202. * @param accessToken
  203. * @return
  204. */
  205. private String refreshAccessTokenUrl(String accessToken) {
  206. return String.format(REFRESH_ACCESS_TOKEN_URL, Constants.get("APP_ID"), "refresh_token", accessToken);
  207. }
  208. private String refreshJsapiTicket(String accessToken) {
  209. return String.format(REFRESH_JSAPI_TICKET_URL, accessToken);
  210. }
  211. public String authorizeURL(Long userId, Long orderId) {
  212. return genrateCodeUrl(orderId + "@" + userId);
  213. }
  214. public String authorizeURL(Long userId, String currentUrl) {
  215. return genrateShareCodeUrl(currentUrl + "@" + userId);
  216. }
  217. public String getRefreshJsapiAccesstokenUrl(){
  218. return String.format(REFRESH_JSAPI_ACCESSTOKEN_URL,Constants.get("APP_ID"),Constants.get("APP_AUTH_SECRET"));
  219. }
  220. public int clearWxUserCodeByUserId(long userId) {
  221. return wxAuthUserDAO.clearCodeByUserId(userId);
  222. }
  223. }