Java 微信公众平台开发(三)——定时获取access_token

access_token

access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。

https请求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

参数说明

参数         是否必须         说明
grant_type   是              获取access_token填写client_credential
appid        是              第三方用户唯一凭证
secret       是              第三方用户唯一凭证密钥,即appsecret

返回说明

正常情况下,微信会返回下述JSON数据包给公众号:

{"access_token":"ACCESS_TOKEN","expires_in":7200}

获取access_token
由于access_token的值是有实效性的,7200秒就会过期,所以我们每次使用的时候都需要重新获取。
这里我是使用线程定时获取access_token,在程序启动时将access_token的值赋给全局变量,从而避免来每次使用时都要去重新获取。
首先看下启动类:

package cc.feefox.wechat;

import javax.servlet.ServletException;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

import cc.feefox.wechat.token.TokenThread;

@SpringBootApplication
@EnableScheduling // 这里,启用定时任务(待扩展)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        init();
    }

    public static void init() throws ServletException {

        // 启动线程定时获取access_token
        new Thread(new TokenThread()).start();
    }
}

再看定时任务

package cc.feefox.wechat.token;

import cc.feefox.wechat.common.constant.WechatConstant;

/**
 * 定时获取accesstoken
 * @Package: cc.feefox.wechat.token
 * @author: cc
 * @date: 2018年8月20日 上午10:44:10
 */
public class TokenThread implements Runnable {

    public static AccessToken accesstoken = null;

    public void run() {

        while (true) {
            try {
                accesstoken = GetAccessToken.getInterfaceToken(WechatConstant.APPID, WechatConstant.APPSECRET);
                if (null != accesstoken) {
                    WechatConstant.ACCESS_TOKEN = accesstoken.getAccess_token();
                    System.out.println("获取accesstoken成功,accesstoken:" + accesstoken.getAccess_token() + " 有效时间为"
                            + accesstoken.getExpires_in());
                    Thread.sleep((accesstoken.getExpires_in() - 200) * 1000);// 休眠7000秒
                } else {
                    Thread.sleep(60 * 1000);
                }
            } catch (Exception e) {
                try {
                    Thread.sleep(60 * 1000);
                } catch (Exception e2) {
                    System.out.println(e2.getMessage());
                }
            }
        }
    }
}

这里我将获取到的accesstoken值赋给来WechatConstant.ACCESS_TOKEN全局变量,这样就可以很方便的使用了

如有错漏请指出,欢迎加群 581817132
这里写图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值