nest-wechat

repository·main·Indexed 41 days ago

https://github.com/baaxl9vh/nest-wechat

A NestJS module and utility library providing a comprehensive wrapper for WeChat server-side APIs, including Official Accounts, Mini Programs, WeChat Pay, and Enterprise WeChat. Version 0.2.50 includes support for access token management, JS-SDK signatures, electronic invoicing (Fapiao), and a MessageCrypto utility for SHA1, MD5, and AES encryption.

Tokens
19.5K
Snippets
69
Records
93
Agent score
51%

What's inside nest-wechat

  1. Integrate WeChatMobileModule in NestJS

    main

    To use mobile application features in a NestJS application, import and register the WeChatMobileModule in your root module.

    import { Module } from '@nestjs/common';
    import { WeChatMobileModule } from 'nest-wechat';
    
    @Module({
      imports: [WeChatMobileModule.register()],
    })
    export class AppModule {
    }
  2. Integrate WeChatModule into NestJS

    main

    You can integrate nest-wechat into your NestJS application using two primary methods: register for static configuration or forRootAsync for dynamic configuration (e.g., using ConfigService).

    // Method 1: Static registration using .register()
    import { Module } from '@nestjs/common';
    import { WeChatModule } from 'nest-wechat';
    
    @Module({
      imports: [WeChatModule.register({appId: 'your app id', secret: 'your secret'})],
    })
    export class AppModule {}
    
    // Method 2: Dynamic registration using .forRootAsync()
    import { CACHE_MANAGER, Module } from '@nestjs/common';
    import { ConfigModule, ConfigService } from '@nestjs/config';
    import { Cache } from 'cache-manager';
    import { RedisCache, WeChatModule } from 'nest-wechat';
    
    @Module({
      imports: [
        ConfigModule.forRoot({
          envFilePath: '.env.test.local',
        }),
        WeChatModule.forRootAsync({
          imports: [ConfigModule],
          inject: [ConfigService, CACHE_MANAGER],
          useFactory: (configService: ConfigService, cache: Cache) => ({
            appId: configService.get('WX_APPID'),
            secret: configService.get('WX_SECRET'),
            token: configService.get('WX_TOKEN'),
            encodingAESKey: configService.get('WX_AESKEY'),
            cacheAdapter: new RedisCache(cache),
            debug: true,
          }),
        }),
      ]
    })
    export class AppModule {}
  3. Run tests for nest-wechat

    main

    To run tests, you must first create a .env.test.local file containing your test credentials and Redis configuration.

    1. Configure Environment

    Create .env.test.local with the following keys:

    • TEST_APPID: Your test AppID
    • TEST_SECRET: Your test Secret
    • TEST_JSSDK_URL: Your website URL for JSSDK testing
    • TEST_TOKEN: Your WeChat token
    • TEST_AESKEY: Your WeChat AES key
    • REDIS_HOST, REDIS_PORT, REDIS_PASSWORD, REDIS_DB: Redis connection details
    • REDIS_TTL: Redis Time-To-Live

    2. Execute Test Commands

    Use the following commands to run different test suites:

    # Run end-to-end tests
    npm run test:e2e
    
    # Run a specific unit test
    npm run test wechat.service.userinfo.spec.ts
  4. Configure commitlint and husky for automated linting

    main

    To enforce the commit message standard automatically, set up husky and commitlint using the following steps.

    1. Install and initialize Husky

    npm install husky --save-dev
    npx husky-init

    2. Add the commit-msg hook

    npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'

    3. Install commitlint and conventional configuration

    npm install --save-dev @commitlint/config-conventional @commitlint/cli

    4. Configure commitlint

    Create a commitlint.config.js file to extend the conventional configuration:

    echo "module.exports = { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js

    Alternatively, you can customize rules in commitlint.config.js:

    module.exports = {
      extends: ['@commitlint/config-conventional'],
      rules: {
        'body-max-line-length': [2, 'always', 60],
      }
    }
    npm install husky --save-dev
    npx husky-init
    npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
    npm install --save-dev @commitlint/config-conventional @commitlint/cli
  5. Test WeChat Message Push (Webhook)

    main

    To test the WeChat Official Account message push functionality, you can run a local test server and configure the WeChat Official Account testing platform to point to your local URL.

    1. Start the Test Server

    Run the following command to start the e2e test entry point:

    npx ts-node -T tests/e2e/wechat-app.main.ts

    2. Configure WeChat Testing Platform

    Use the WeChat Official Account Debug Tool with the following settings:

    • URL: http://your/url/wechat/push (e.g., http://127.0.0.1:3001/wechat/push)
    • Token: pamtest

    3. Verify Access Token

    Ensure you have a valid access_token by using the following request body in the WeChat debug tool:

    {
      "grant_type": "client_credential", 
      "appid": "your/appid", 
      "secret": "your/secret", 
      "force_refresh": false
    }

    4. Simulate Message Push

    Use the WeChat Open Platform Message Push Test Tool to simulate incoming message pushes to your server.

  6. Follow the commit message standard

    main

    This project follows a specific commit message format. Every commit must include a type and a subject. The body and footer are optional.

    Format:

    <type>: <subject>
    <BLANK LINE>
    <body>
    <BLANK LINE>
    <footer>

    Allowed Types:

    • ci: Changes to CI configuration files and scripts.
    • feat: A new feature.
    • fix: A bug fix.
    • docs: Documentation only changes.
    • style: Changes that do not affect the meaning of the code (white-space, formatting, etc).
    • refactor: A code change that neither fixes a bug nor adds a feature.
    • perf: A code change that improves performance.
    • test: Adding missing tests or correcting existing tests.
    • build: Changes that affect the build system or external dependencies.
    • chore: Other changes that do not modify source or test files (e.g., updating tools).
    • revert: Reverting a previous commit.

    Note: Do not use git commit -m 'message' to bypass the standard; use the interactive commit flow to ensure compliance.

  7. Configure WeChatService Cache Adapter

    main

    The WeChatService uses an ICache implementation to store access_token and jsapi_ticket to avoid hitting WeChat API rate limits. By default, it uses MapCache, but you can provide your own implementation via the cacheAdapter property.

    // Customizing the cache adapter
    const myCache: ICache = { /* implementation */ };
    wechatService.cacheAdapter = myCache;
  8. WeChatService Configuration

    main

    The WeChatService is configured via WeChatModuleOptions. Key properties include:

    • config: Configuration read/write properties.
    • cacheAdapter: An object implementing ICache. Defaults to a Map-based implementation.
  9. Use WeChatService as a standalone utility

    main

    If you are not using NestJS, you can instantiate WeChatService directly as a utility class.

    import { WeChatService } from 'nest-wechat';
    const service = new WeChatService({ appId: 'your app id', secret: 'your secret'});
  10. WeChat Official Account: Access Token Management

    main

    Methods for retrieving various types of access tokens for Official Accounts.

    // Get standard account access token
    public async getAccountAccessToken (_appId?: string, _secret?: string): Promise<AccountAccessTokenResult>;
    
    // Get stable version access token
    public async getStableAccessToken (_appId?: string, _secret?: string, force = false): Promise<AccountAccessTokenResult>;
    
    // Get jsapi_ticket
    public async getJSApiTicket (_appId?: string, _secret?: string): Promise<TicketResult>;
  11. WeChat Pay: Mini Program JSAPI Operations

    main

    The pay object provides methods for Mini Program payment flows, including order creation, querying, closing, and refunding. Most methods require mchId, serialNo, and a privateKey (Buffer or string).

    // Example: JSAPI Order Creation
    pay.jsapi (order: TransactionOrder, serialNo: string, privateKey: Buffer | string): Promise<{prepay_id: string}>;
    
    // Example: Build Mini Program Payment Parameters
    pay.buildMiniProgramPayment (appId: string, prepayId: string, privateKey: Buffer | string): MiniProgramPaymentParameters;
    
    // Example: Handle Payment Notification
    pay.paidCallback (publicKey: Buffer | string, apiKey: string, req: Request, res: Response): Promise<Trade>;