View Javadoc
1   package com.foxinmy.weixin4j.mp.component;
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.PerTicketManager;
9   import com.foxinmy.weixin4j.token.TokenCreator;
10  import com.foxinmy.weixin4j.token.TokenManager;
11  
12  /**
13   * 微信公众号token创建(永久刷新令牌)
14   *
15   * @className WeixinTokenComponentCreator
16   * @author jinyu(foxinmy@gmail.com)
17   * @date 2016年7月5日
18   * @since JDK 1.6
19   */
20  public class WeixinTokenComponentCreator extends TokenCreator {
21  
22  	private final PerTicketManager perTicketManager;
23  	private final TokenManager componentTokenManager;
24  
25  	/**
26  	 *
27  	 * @param perTicketManager
28  	 *            第三方套件永久授权码
29  	 * @param componentTokenManager
30  	 *            第三方套件凭证token
31  	 */
32  	public WeixinTokenComponentCreator(PerTicketManager perTicketManager, TokenManager componentTokenManager) {
33  		this.perTicketManager = perTicketManager;
34  		this.componentTokenManager = componentTokenManager;
35  	}
36  
37  	@Override
38  	public String name() {
39  		return String.format("mp_token_component_%s_%s", perTicketManager.getThirdId(),
40  				perTicketManager.getAuthAppId());
41  	}
42  
43  	@Override
44  	public String uniqueid() {
45  		return String.format("%s_%s", perTicketManager.getThirdId(), perTicketManager.getAuthAppId());
46  	}
47  
48  	@Override
49  	public Token create() throws WeixinException {
50  		JSONObject obj = new JSONObject();
51  		obj.put("component_appid", perTicketManager.getThirdId());
52  		obj.put("authorizer_appid", perTicketManager.getAuthAppId());
53  		obj.put("authorizer_refresh_token", perTicketManager.getAccessTicket());
54  		WeixinResponse response = weixinExecutor.post(
55  				String.format(URLConsts.TOKEN_COMPONENT_URL, componentTokenManager.getAccessToken()),
56  				obj.toJSONString());
57  		obj = response.getAsJson();
58  		perTicketManager.cachingTicket(obj.getString("authorizer_refresh_token"));
59  		return new Token(obj.getString("authorizer_access_token"), obj.getLongValue("expires_in") * 1000l);
60  	}
61  }