首页>代码>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);
	}

}
最近下载更多
ewan007  LV29 2月24日
是夜在熬我.  LV6 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日
yiss343  LV1 2022年6月19日
最近浏览更多
李朝磊  LV18 3月6日
ewan007  LV29 2月24日
1134116035 2月24日
暂无贡献等级
是夜在熬我.  LV6 2月20日
小测子 1月20日
暂无贡献等级
sublinex 1月16日
暂无贡献等级
半夏bx  LV14 1月13日
微信网友_6786215447367680  LV4 2023年12月20日
万魔殿 2023年12月19日
暂无贡献等级
去码头整点薯条  LV3 2023年11月15日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友