AccountOperator.java 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package com.cyksj.service.wechat;
  2. import com.cyksj.common.exception.BusinessRuntimeException;
  3. import com.cyksj.common.util.IoKit;
  4. import com.cyksj.common.util.J11HttpC;
  5. import com.cyksj.common.util.Jsons;
  6. import com.cyksj.model.dto.AccountJsTicket;
  7. import com.cyksj.model.dto.WeChatAccessToken;
  8. import org.springframework.stereotype.Service;
  9. import java.net.http.HttpResponse;
  10. /**
  11. * @author valor.
  12. * @date 2019/12/3 20:44
  13. */
  14. @Service
  15. public class AccountOperator implements AccountOps {
  16. @Override
  17. public WeChatAccessToken accessToken(String appid, String secret) throws Exception {
  18. // GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}
  19. String url = "https://api.weixin.qq.com/cgi-bin/token" +
  20. "?appid=" + appid +
  21. "&secret=" + secret +
  22. "&grant_type=client_credential";
  23. HttpResponse<byte[]> res =
  24. J11HttpC.custom()
  25. .ofGet()
  26. .url(url)
  27. .send(HttpResponse.BodyHandlers.ofByteArray());
  28. if (200 != res.statusCode()) {
  29. throw BusinessRuntimeException.getInstance("获取access_token失败: " + IoKit.toString(res.body()));
  30. }
  31. WeChatAccessToken token = Jsons.parseObject(res.body(), WeChatAccessToken.class);
  32. if (null == token) {
  33. throw BusinessRuntimeException.getInstance("获取access_token失败: " + IoKit.toString(res.body()));
  34. }
  35. final Integer errcode = token.getErrcode();
  36. if (null != errcode && 0 != errcode) {
  37. throw BusinessRuntimeException.getInstance("获取access_token失败: " + token.getErrmsg() + "[" + errcode + "]");
  38. }
  39. return token;
  40. }
  41. @Override
  42. public AccountJsTicket jsTicket(String access_token) throws Exception {
  43. // GET https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={ACCESS_TOKEN}&type=jsapi
  44. String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket" +
  45. "?access_token=" + access_token +
  46. "&type=jsapi";
  47. HttpResponse<byte[]> res =
  48. J11HttpC.custom()
  49. .ofGet()
  50. .url(url)
  51. .send(HttpResponse.BodyHandlers.ofByteArray());
  52. if (200 != res.statusCode()) {
  53. throw BusinessRuntimeException.getInstance("获取access_token失败: " + IoKit.toString(res.body()));
  54. }
  55. AccountJsTicket ticket = Jsons.parseObject(res.body(), AccountJsTicket.class);
  56. if (null == ticket) {
  57. throw BusinessRuntimeException.getInstance("获取access_token失败: " + IoKit.toString(res.body()));
  58. }
  59. final Integer errcode = ticket.getErrcode();
  60. if (null != errcode && 0 != errcode) {
  61. throw BusinessRuntimeException.getInstance("获取access_token失败: " + ticket.getErrmsg() + "[" + errcode + "]");
  62. }
  63. return ticket;
  64. }
  65. }