View Javadoc
1   package com.foxinmy.weixin4j.qy.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.qy.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年12月25日
18   * @since JDK 1.6
19   * @see <a href= "https://work.weixin.qq.com/api/doc#10029/附录1-JS-SDK使用权限签名算法">JSTICKET</a>
20   */
21  public class WeixinTicketCreator extends TokenCreator {
22  
23  	private final TicketType ticketType;
24  	private final TokenManager weixinTokenManager;
25  
26  	/**
27  	 * @param ticketType
28  	 *            票据类型
29  	 * @param weixinTokenManager
30  	 *            <font color="red">企业号的access_token</font>
31  	 */
32  	public WeixinTicketCreator(TicketType ticketType,
33  			TokenManager weixinTokenManager) {
34  		this.ticketType = ticketType;
35  		this.weixinTokenManager = weixinTokenManager;
36  	}
37  
38  	@Override
39  	public String name() {
40  		return String.format("qy_ticket_%s", ticketType.name());
41  	}
42  
43  	@Override
44  	public String uniqueid() {
45  		return weixinTokenManager.getWeixinId();
46  	}
47  
48  	@Override
49  	public Token create() throws WeixinException {
50  		WeixinResponse response = null;
51  		if (ticketType == TicketType.jsapi) {
52  			response = weixinExecutor.get(String.format(
53  					URLConsts.JS_TICKET_URL, weixinTokenManager.getCache()
54  							.getAccessToken()));
55  		} else {
56  			response = weixinExecutor.get(String.format(
57  					URLConsts.SUITE_TICKET_URL, weixinTokenManager.getCache()
58  							.getAccessToken(), ticketType.name()));
59  		}
60  		JSONObject result = response.getAsJson();
61  		return new Token(result.getString("ticket"),
62  				result.getLong("expires_in") * 1000l).pushExtra("group_id",
63  				result.getString("group_id"));
64  	}
65  }