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   
10  /**
11   * 微信公众平台TOKEN创建者
12   *
13   * @className WeixinTokenCreator
14   * @author jinyu(foxinmy@gmail.com)
15   * @date 2015年1月10日
16   * @since JDK 1.6
17   * @see <a href=
18   *      "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183&token=&lang=zh_CN">微信公众平台获取token说明</a>
19   * @see com.foxinmy.weixin4j.model.Token
20   */
21  public class WeixinTokenCreator extends TokenCreator {
22  
23      private final String appid;
24      private final String secret;
25  
26      /**
27       *
28       * @param appid
29       *            公众号ID
30       * @param secret
31       *            公众号secret
32       */
33      public WeixinTokenCreator(String appid, String secret) {
34          this.appid = appid;
35          this.secret = secret;
36      }
37  
38      @Override
39      public String name() {
40          return "mp_token";
41      }
42  
43      @Override
44      public String uniqueid() {
45          return appid;
46      }
47  
48      @Override
49      public Token create() throws WeixinException {
50          String tokenUrl = String.format(URLConsts.ASSESS_TOKEN_URL, appid, secret);
51          WeixinResponse response = weixinExecutor.get(tokenUrl);
52          JSONObject result = response.getAsJson();
53          return new Token(result.getString("access_token"), result.getLongValue("expires_in") * 1000l);
54      }
55  }