Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including wechat-component with all npm packages installed. Try it out:

var wechatComponent = require("wechat-component")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

wechat-component v2.0.1

Wechat component Node.js SDK

wechat-component

Usage

Basic

const WechatComponent = require('wechat-component');

const component = new WechatComponent({
  appid: '<WECHAT_COMPONENT_APPID>',
  appsecret: '<WECHAT_COMPONENT_APPSECRET>',
  getComponentTicketAsync: async () => ... // get component ticket from cache/database;
  getTokenAsync: async () => ... // get access token from cache/database;
  saveTokenAsync: async token => ... // save access token to cache/database;
});

// Step 1
const authorizeURL = await component.getAuthorizeURL(redirectURI);
=> redirect to authorizeURL

// Step 2
const result = await component.queryAuth(code);
=> result.authorization_info.authorizer_access_token

// Step 3
const authorizerAppid = result.authorization_info.authorizer_appid;
=> await component.getAuthorizerInfo(authorizerAppid);

Wrap wechat-api

const util = require('util');
const API = require('wechat-api');
const api = new API(authorizerAppid, null, getToken, saveToken);

api.getAccessToken = async (callback) => {
  try {
    api.getTokenAsync = util.promisify(api.getToken);
    api.saveTokenAsync = util.promisify(api.saveToken);

    const refresh = await api.getTokenAsync();
    const token = await service.getAuthorizerToken(authorizerAppid, refresh.refreshToken);
    // service should use a Central Control Server

    await api.saveTokenAsync(token);

    callback(null, token);
  } catch (e) {
    callback(e);
  }
};

Wrap wechat-oauth

const OAuth = require('wechat-oauth');
const oauth = new OAuth(authorizerAppid, null, getToken, saveToken);

oauth.getAccessToken = async (code, callback) => {
  const token = await component.getOAuthAccessToken(authorizerAppid, code);

  oauth.saveToken(token.openid, token, err => callback(err, { data: token }));
};

oauth.refreshAccessToken = async (refreshToken, callback) => {
  const token = await component.refreshOAuthAccessToken(authorizerAppid, refreshToken);

  oauth.saveToken(token.openid, token, err => callback(err, { data: token }));
};

oauth.getAuthorizeURL = (redirect, state, scope) => component
  .getOAuthAuthorizeURL(authorizerAppid, redirect, scope, state);
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free