首页>代码>jfinal开发java web开源微信商城源码>/jfinal-wxmall/weixin-sdk/src/main/java/com/weixin/sdk/api/AccessTokenApi.java
/**
* Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.weixin.sdk.api;
import java.util.Map;
import java.util.concurrent.Callable;
import com.weixin.sdk.cache.IAccessTokenCache;
import com.weixin.sdk.kit.ParaMap;
import com.weixin.sdk.utils.HttpUtils;
import com.weixin.sdk.utils.RetryUtils;
/**
* 认证并获取 access_token API
* http://mp.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96access_token
*
* AccessToken默认存储于内存中,可设置存储于redis或者实现IAccessTokenCache到数据库中实现分布式可用
*
* 具体配置:
* <pre>
* ApiConfigKit.setAccessTokenCache(new RedisAccessTokenCache());
* </pre>
*/
public class AccessTokenApi {
// "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
private static String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
// 利用 appId 与 accessToken 建立关联,支持多账户
static IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();
/**
* 从缓存中获取 access token,如果未取到或者 access token 不可用则先更新再获取
*/
public static AccessToken getAccessToken() {
String appId = ApiConfigKit.getApiConfig().getAppId();
AccessToken result = accessTokenCache.get(appId);
if (result != null && result.isAvailable())
return result;
refreshAccessToken();
return accessTokenCache.get(appId);
}
/**
* 直接获取 accessToken 字符串,方便使用
* @return String accessToken
*/
public static String getAccessTokenStr() {
return getAccessToken().getAccessToken();
}
/**
* 强制更新 access token 值
*/
public static synchronized void refreshAccessToken() {
ApiConfig ac = ApiConfigKit.getApiConfig();
String appId = ac.getAppId();
String appSecret = ac.getAppSecret();
final Map<String, String> queryParas = ParaMap.create("appid", appId).put("secret", appSecret).getData();
// 最多三次请求
AccessToken result = RetryUtils.retryOnException(3, new Callable<AccessToken>() {
@Override
public AccessToken call() throws Exception {
String json = HttpUtils.get(url, queryParas);
return new AccessToken(json);
}
});
// 三次请求如果仍然返回了不可用的 access token 仍然 put 进去,便于上层通过 AccessToken 中的属性判断底层的情况
accessTokenCache.set(ac.getAppId(), result);
}
}
最近下载更多
微信网友_6790966844739584 LV5
2024年6月12日
ewan007 LV30
2024年2月24日
是夜在熬我. LV6
2024年2月20日
去码头整点薯条 LV3
2023年11月15日
wuying8208 LV15
2023年7月27日
gdt633 LV2
2023年6月30日
稻草人a LV1
2023年4月6日
臧家旺 LV3
2022年12月7日
zymnba LV2
2022年6月25日
我喜欢蔡徐坤 LV1
2022年6月20日
最近浏览更多
段池卿 LV5
8月28日
微信网友_7596468628459520
7月14日
暂无贡献等级
空中飞尘 LV13
7月8日
微信网友_6956978011000832 LV2
6月30日
周粥粥
4月11日
暂无贡献等级
zhangkk LV7
2月8日
微信网友_6955249237250048 LV5
2024年12月28日
txf123 LV6
2024年12月10日
sjwc88 LV4
2024年12月4日
pangzhihui LV14
2024年11月12日

