View Javadoc
1   package com.foxinmy.weixin4j.token;
2   
3   import com.foxinmy.weixin4j.cache.CacheStorager;
4   import com.foxinmy.weixin4j.exception.WeixinException;
5   import com.foxinmy.weixin4j.model.Token;
6   
7   /**
8    * 第三方应用ticket的存取
9    *
10   * @className TicketManager
11   * @author jinyu(foxinmy@gmail.com)
12   * @date 2015年6月22日
13   * @since JDK 1.6
14   * @see
15   */
16  public class TicketManager {
17  
18  	/**
19  	 * 第三方ID
20  	 */
21  	private final String thirdId;
22  	/**
23  	 * 第三方secret
24  	 */
25  	private final String thirdSecret;
26  	/**
27  	 * ticket存储策略
28  	 */
29  	private final CacheStorager<Token> cacheStorager;
30  
31  	/**
32  	 *
33  	 * @param thirdId
34  	 *            第三方ID suiteId/componentId
35  	 * @param thirdSecret
36  	 *            第三方secret
37  	 * @param cacheStorager
38  	 *            ticket存储策略
39  	 */
40  	public TicketManager(String thirdId, String thirdSecret,
41  			CacheStorager<Token> cacheStorager) {
42  		this.thirdId = thirdId;
43  		this.thirdSecret = thirdSecret;
44  		this.cacheStorager = cacheStorager;
45  	}
46  
47  	/**
48  	 * 获取ticket对象
49  	 *
50  	 * @return token对象
51  	 * @throws WeixinException
52  	 */
53  	public Token getTicket() throws WeixinException {
54  		return cacheStorager.lookup(getCacheKey());
55  	}
56  
57  	/**
58  	 * 获取ticket
59  	 *
60  	 * @return ticket
61  	 * @throws WeixinException
62  	 */
63  	public String getAccessTicket() throws WeixinException {
64  		return getTicket().getAccessToken();
65  	}
66  
67  	/**
68  	 * 获取ticket的key
69  	 *
70  	 * @return
71  	 */
72  	public String getCacheKey() {
73  		return String.format("%sthird_party_ticket_%s",
74  				TokenCreator.CACHEKEY_PREFIX, thirdId);
75  	}
76  
77  	/**
78  	 * 缓存ticket
79  	 *
80  	 * @param ticket
81  	 *            票据凭证
82  	 * @throws WeixinException
83  	 */
84  	public void cachingTicket(String ticket) throws WeixinException {
85  		Token token = new Token(ticket);
86  		cacheStorager.caching(getCacheKey(), token);
87  	}
88  
89  	public String getThirdId() {
90  		return thirdId;
91  	}
92  
93  	public String getThirdSecret() {
94  		return thirdSecret;
95  	}
96  
97  	public CacheStorager<Token> getCacheStorager() {
98  		return cacheStorager;
99  	}
100 }