Introduction to the

TNW: TypeScript(The) + Node.js(Next) + WeChat public account development scaffolding, support HTTP module extension, support any Node.js server framework (Express, NestJS, eggJS, etc.)

An overview of the

The access_token is the global unique interface call credential of the public number. The public number needs to use the Access_token to invoke all interfaces. Developers need to keep it safe. The access_token must be stored with a minimum of 512 characters. The validity period of the Access_Token is two hours. The validity period of the access_token must be updated periodically. If the access_token is obtained repeatedly, the access_token obtained last time becomes invalid.

Description of the use and generation of access_token required by API call of public platform:

1. It is recommended that developers of public accounts use the central control server to obtain and refresh the Access_token uniformly. All the Access_token used by other business logic servers come from the central control server, so they should not refresh the access_token separately.

2. The validity period of the access_token is expressed by the returned expire_in value, which is within 7200 seconds. The central server needs to refresh the access_token in advance based on this validity period. In the process of refreshing, the central control server can continue to output the old access_tokens. At this time, the background of the public platform will ensure that both the old and new access_tokens are available within 5 minutes, which ensures the smooth transition of third-party services.

3. The validity time of access_token may be adjusted in the future. Therefore, the central control server not only needs to update the access_token actively by internal timing, but also needs to provide an interface to refresh the Access_token passively, which is convenient for the service server when the API call is informed that the access_token has timed out. The access_token refresh process can be triggered.

Public accounts and applets can call this interface using AppId and AppSecret to obtain access_token. AppId and AppSecret can be obtained in the “wechat Public Platform – Development – Basic Configuration” page (you need to be a developer and the account has no abnormal status). ** Before invoking the interface, log in to “wechat Public Platform – Development – Basic Configuration” and add the server IP address to the IP whitelist in advance; otherwise, the invocation fails. ** Small programs do not need to configure IP address whitelist.

The above is from official documentation

To highlight:

  • To invoke the Access_token interface, you need to configure an IP address whitelist on the wechat public platform
  • The validity period of the access_token is 7200 seconds
  • You can refresh the Access_token in advance, and the background of the public platform will ensure that it is new and old within 5 minutesaccess_tokenAll available

Obtain the access_token in TNW

export class AccessTokenApi {
    private static url: string = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    /** * get acces_token * 1, get it from cache first, return acces_token * 2 if available, call refresh interface to get new acces_token */ if stale in cache
    public static async getAccessToken() {
        let ac: ApiConfig = ApiConfigKit.getApiConfig;
        let accessToken: AccessToken | undefined = this.getAvailableAccessToken(ac);
        if (accessToken) {
            if(ApiConfigKit.isDevMode) console.log("Accesstoken in cache");
            return accessToken;
        }
        if(ApiConfigKit.isDevMode) console.log("Refresh accesstoken");
        return await this.refreshAccessToken(ac);;
    }

    /** * Get acces_token * @param apiConfig */ from the cache via appId
    private static getAvailableAccessToken(apiConfig: ApiConfig): AccessToken | undefined {
        let result: AccessToken | undefined;
        let accessTokenCache: IAccessTokenCache = ApiConfigKit.getAccessTokenCache;
        let accessTokenJson: string = accessTokenCache.get(apiConfig.getAppId);
        if (accessTokenJson) {
            result = new AccessToken(accessTokenJson);
        }
        if (result && result.isAvailable()) {
            return result;
        } else {
            return undefined; }}/** * get the new acces_token and set the cache * @param apiConfig */
    public static async refreshAccessToken(apiConfig: ApiConfig) {
        let url = util.format(this.url, apiConfig.getAppId, apiConfig.getAppScrect);
        let data = await HttpKit.getHttpDelegate.httpGet(url);
        if (data) {
            let accessToken: AccessToken = new AccessToken(data)
            let accessTokenCache: IAccessTokenCache = ApiConfigKit.getAccessTokenCache;
            accessTokenCache.set(apiConfig.getAppId, accessToken.getCacheJson);
            return accessToken;
        } else {
            new Error("Get an accessToken exception"); }}}Copy the code

The default access_token is cached in memory, but this has the disadvantage of having to be retrieved when the application is shut down. So TNW provides an extension to set up the cache.

Cache extension

Access_token Cache interface IAccessTokenCache

export interface IAccessTokenCache {
    get(key: string) :string;
    set(key: string, jsonValue: string) :void;
    remove(key: string) :void;
}
Copy the code

DefaultAccessTokenCache is implemented by default

export class DefaultAccessTokenCache implements IAccessTokenCache {

    private map: Map<string.string> = new Map<string.string> ();get(key: string) :string {
        return this.map.get(key) || ' ';
    }

    set(key: string, jsonValue: string) {
        this.map.set(key, jsonValue);
    }

    remove(key: string) {
        this.map.delete(key); }}Copy the code

Set up to replace the default cache

DefaultAccessTokenCache can be replaced with your implementation class such as caches to files, Redis, etc

ApiConfigKit.setAccessTokenCache(new DefaultAccessTokenCache());
Copy the code

legacy

The implementation class passed directly into the interface has an exception that cannot be called. The expression that lacks the calling signature is waiting to be resolved

Open source is recommended

  • TNWScaffolding for the development of wechat official account:Gitee.com/javen205/TN…
  • IJPayMake payment at your fingertips:Gitee.com/javen205/IJ…
  • Efficient development of SpringBoot microservicesmicaTools:Gitee.com/596392912/m…
  • AvueA fantastic framework based on VUE configurable:Gitee.com/smallweigit…
  • pigThe Strongest Microservices in the universe (required for Architects) :gitee.com/log4j/pig
  • SpringBladeComplete online solution (necessary for enterprise development) :Gitee.com/smallc/Spri…