View Javadoc
1   package com.foxinmy.weixin4j.mp.token;
2   
3   import com.alibaba.fastjson.JSONObject;
4   import com.foxinmy.weixin4j.exception.WeixinException;
5   import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
6   import com.foxinmy.weixin4j.model.Token;
7   import com.foxinmy.weixin4j.mp.type.URLConsts;
8   import com.foxinmy.weixin4j.token.TokenCreator;
9   import com.foxinmy.weixin4j.token.TokenManager;
10  import com.foxinmy.weixin4j.type.TicketType;
11  
12  /**
13   * 微信公众平台TICKET创建(包括jsticket、其它JSSDK所需的ticket的创建
14   *
15   * @className WeixinTicketCreator
16   * @author jinyu(foxinmy@gmail.com)
17   * @date 2015年1月10日
18   * @since JDK 1.6
19   * @see <a href=
20   *      "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_CN">
21   *      JS TICKET</a>
22   */
23  public class WeixinTicketCreator extends TokenCreator {
24  
25      private final TicketType ticketType;
26      private final TokenManager weixinTokenManager;
27  
28      /**
29       * jssdk
30       *
31       * @param ticketType
32       *            票据类型
33       * @param weixinTokenManager
34       *            <font color="red">公众平台的access_token</font>
35       */
36      public WeixinTicketCreator(TicketType ticketType, TokenManager weixinTokenManager) {
37          this.ticketType = ticketType;
38          this.weixinTokenManager = weixinTokenManager;
39      }
40  
41      @Override
42      public String name() {
43          return String.format("mp_ticket_%s", ticketType.name());
44      }
45  
46      @Override
47      public String uniqueid() {
48          return weixinTokenManager.getWeixinId();
49      }
50  
51      @Override
52      public Token create() throws WeixinException {
53          WeixinResponse response = weixinExecutor
54                  .get(String.format(URLConsts.JS_TICKET_URL, weixinTokenManager.getAccessToken(), ticketType.name()));
55          JSONObject result = response.getAsJson();
56          return new Token(result.getString("ticket"), result.getLongValue("expires_in") * 1000l);
57      }
58  }