1 package com.foxinmy.weixin4j.qy.api;
2
3 import com.alibaba.fastjson.JSON;
4 import com.alibaba.fastjson.JSONObject;
5 import com.foxinmy.weixin4j.cache.CacheStorager;
6 import com.foxinmy.weixin4j.exception.WeixinException;
7 import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
8 import com.foxinmy.weixin4j.model.Token;
9 import com.foxinmy.weixin4j.qy.model.OUserInfo;
10 import com.foxinmy.weixin4j.qy.type.LoginTargetType;
11 import com.foxinmy.weixin4j.token.TokenCreator;
12 import com.foxinmy.weixin4j.token.TokenManager;
13 import com.foxinmy.weixin4j.util.StringUtil;
14
15
16
17
18
19
20
21
22
23
24
25 public class ProviderApi extends QyApi {
26 private final TokenManager providerTokenManager;
27 private final CacheStorager<Token> cacheStorager;
28
29 public ProviderApi(TokenManager providerTokenManager,
30 CacheStorager<Token> cacheStorager) {
31 this.providerTokenManager = providerTokenManager;
32 this.cacheStorager = cacheStorager;
33 }
34
35
36
37
38
39
40
41
42
43
44
45
46 public OUserInfo getOUserInfoByCode(String authCode) throws WeixinException {
47 String oauth_thirdinfo_uri = getRequestUri("oauth_logininfo_uri");
48 WeixinResponse response = weixinExecutor.post(
49 String.format(oauth_thirdinfo_uri,
50 providerTokenManager.getAccessToken()),
51 String.format("{\"auth_code\":\"%s\"}", authCode));
52 JSONObject obj = response.getAsJson();
53 OUserInfo oUser = JSON.toJavaObject(obj, OUserInfo.class);
54 obj = obj.getJSONObject("redirect_login_info");
55 Token loginInfo = new Token(obj.getString("login_ticket"),
56 obj.getLongValue("expires_in") * 1000l);
57 oUser.setRedirectLoginInfo(loginInfo);
58 cacheStorager.caching(getLoginTicketCacheKey(oUser.getCorpInfo()
59 .getCorpId()), oUser.getRedirectLoginInfo());
60 return oUser;
61 }
62
63 private String getLoginTicketCacheKey(String coprId) {
64 return String.format("%sqy_provider_ticket_%s",
65 TokenCreator.CACHEKEY_PREFIX, coprId);
66 }
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82 public String getLoginUrl(String corpId, LoginTargetType targetType,
83 int agentId) throws WeixinException {
84 Token token = cacheStorager.lookup(getLoginTicketCacheKey(corpId));
85 if (token == null || StringUtil.isBlank(token.getAccessToken())) {
86 throw new WeixinException("maybe oauth first?");
87 }
88 String oauth_loginurl_uri = getRequestUri("oauth_loginurl_uri");
89 JSONObject obj = new JSONObject();
90 obj.put("login_ticket", token.getAccessToken());
91 obj.put("target", targetType.name());
92 if (agentId > 0) {
93 obj.put("agentid", agentId);
94 }
95 WeixinResponse response = weixinExecutor.post(
96 String.format(oauth_loginurl_uri,
97 providerTokenManager.getAccessToken()),
98 obj.toJSONString());
99 return response.getAsJson().getString("login_url");
100 }
101 }