Native WeChat

repository·main·Indexed 42 days ago

https://github.com/hector-zhuang/native-wechat

A React Native library providing a TypeScript-supported, promisified interface for the WeChat OpenSDK on Android and iOS. Version 1.0.23 includes support for authentication via sendAuthRequest, WeChat Pay via requestPayment, sharing content (text, images, video, webpages), launching Mini Programs, and subscription messages.

Tokens
5.3K
Snippets
18
Records
21
Agent score
52%

What's inside Native WeChat

  1. Register the Native WeChat SDK

    main

    Before calling any WeChat APIs, you must register the SDK by invoking registerApp with your WeChat App ID. This step sets up the necessary listeners to receive events from the WeChat application.

    registerApp returns a cleanup function. You should call this cleanup function (e.g., in a useEffect return block) to remove the listener and prevent receiving further events from WeChat.

    import {registerApp} from 'native-wechat';
    import {useEffect}
    
    useEffect(() => {
      // Register the app with your App ID
      const unregister = registerApp('wx964290141ebe9b7b');
      
      // Return the cleanup function to remove the listener
      return unregister;
    }, []);
  2. Understand the NativeWechatResponse structure

    main

    All API responses from the native-wechat module follow a standardized NativeWechatResponse<T> shape. This allows you to consistently check for errors and handle data across different WeChat features.

    Key fields include:

    • type: A string indicating the response type.
    • errorCode: A numeric code representing the result (0 typically indicates success).
    • errorStr: A string containing error details if errorCode is non-zero.
    • transaction: A transaction identifier, if applicable.
    • data: The actual payload of type T returned by the specific API call.
    type NativeWechatResponse<T> = {
      type: string;
      errorCode: number;
      errorStr: string | null;
      transaction: string | null;
      data: T;
    };
  3. Invoke WeChat APIs like sendAuthRequest

    main

    Most APIs in native-wechat are promisified. For example, sendAuthRequest triggers a WeChat authentication request. When the user successfully confirms the request within the WeChat app, the returned promise resolves with a NativeWechatResponse containing the authentication code.

    import {registerApp, sendAuthRequest} from 'native-wechat';
    import {Button, Text} from 'react-native';
    
    // Ensure registration happens on mount
    useEffect(() => {
      registerApp('wx964290141ebe9b7b');
    }, []);
    
    const onButtonClicked = async () => {
      // sendAuthRequest returns a promise that resolves to a NativeWechatResponse
      const {data: {code}} = await sendAuthRequest();
      
      // Use the code for your backend verification
      await verifyWechatCode(code);
    };
    
    return (
      <Button onClick={onButtonClicked}>
        <Text>Send Auth Request</Text>
      </Button>
    );
  4. Configure changelog.config.js

    main

    The changelog.config.js file defines the schema and behavior for commit message generation and changelog formatting. It allows you to customize the commit types, emojis, message structure, and the interactive prompts used during the commit process.

    Key configuration areas include:

    • Formatting: Use the format string to define the commit message structure (e.g., {type}{scope}: {emoji}{subject}).
    • Types: Define a mapping of commit types (like feat, fix, chore) with their corresponding descriptions, emojis, and values.
    • Prompts: Customize the messages object within types to change the text of interactive CLI questions.
    • Constraints: Set maxMessageLength and minMessageLength to enforce commit message standards.
    • Scope & List: Define allowed scopes and the list of valid types for the CLI interface.
    module.exports = {
      disableEmoji: false,
      format: '{type}{scope}: {emoji}{subject}',
      list: [
        'test',
        'feat',
        'fix',
        'chore',
        'docs',
        'refactor',
        'style',
        'ci',
        'perf',
        'init',
      ],
      maxMessageLength: 64,
      minMessageLength: 3,
      questions: [
        'type',
        'scope',
        'subject',
        'body',
        'breaking',
        'issues',
        'lerna',
      ],
      scopes: [],
      types: {
        feat: {
          description: 'A new feature',
          emoji: '🎸',
          value: 'feat',
        },
        // ... other types
        messages: {
          type: "Select the type of change that you're committing:",
          customScope: 'Select the scope this component affects:',
          subject: 'Write a short, imperative mood description of the change:\n',
          body: 'Provide a longer description of the change:\n ',
          breaking: 'List any breaking changes:\n',
          footer: 'Issues this commit closes, e.g #123:',
          confirmCommit: 'The packages that this commit has affected\n',
        },
      },
    };
  5. Understand the NativeWechatResponse type

    main

    All promisified APIs in this library return a generic type named NativeWechatResponse. This object contains the operation status and the resulting data payload.

    Fields:

    • type: A string indicating the response type.
    • errorCode: A number representing the error code (0 typically indicates success).
    • errorStr: A string containing error details, or null if successful.
    • data: A generic object T containing the actual API response data.
    export type NativeWechatResponse<T = Record<string, unknown>> = {
      type: string;
      errorCode: number;
      errorStr: string | null;
      data: T;
    };
  6. Perform WeChat Authentication with `sendAuthRequest`

    main

    Initiates a WeChat authentication request. This function returns a Promise that resolves with a SendAuthRequestResponse object upon success. It uses an internal notification system to listen for the SendAuthResp event from the native side.

    Parameters:

    • scope: The permission scope requested (defaults to 'snsapi_userinfo').
    • state: An optional state string to prevent CSRF.

    Returns: Promise<SendAuthRequestResponse>

    import { sendAuthRequest } from 'native-wechat';
    
    try {
      const response = await sendAuthRequest({
        scope: 'snsapi_userinfo',
        state: 'random_state_string',
      });
      console.log('Auth Success:', response);
    } catch (error) {
      console.error('Auth Failed:', error);
    }
  7. Launch a Mini Program with `launchMiniProgram`

    main

    Opens a WeChat Mini Program from your app. You can provide an onNavBack callback that is triggered when the user returns from the Mini Program.

    Parameters:

    • userName: The Mini Program user ID.
    • path: The path within the Mini Program.
    • miniprogramType: The type of Mini Program (converted to number).
    • onNavBack: Callback function receiving LaunchMiniProgramResponse when the user returns.
    import { launchMiniProgram } from 'native-wechat';
    
    await launchMiniProgram({
      userName: 'wxc-xxxxxx',
      path: '/pages/home/index',
      miniprogramType: 1,
      onNavBack: (res) => {
        console.log('Returned from Mini Program:', res);
      }
    });
  8. Share a Mini Program with `shareMiniProgram`

    main

    Shares a specific WeChat Mini Program to a WeChat chat.

    Parameters:

    • userName: The Mini Program user ID.
    • path: The path within the Mini Program.
    • miniProgramType: The type of Mini Program (converted to number).
    • webpageUrl: The URL to be used.
    • withShareTicket: Boolean to include a share ticket.
    • title: Title of the share.
    • description: Description of the share.
    • coverUrl: Cover image URL.
    • scene: The sharing context (number).
    import { shareMiniProgram } from 'native-wechat';
    
    await shareMiniProgram({
      userName: 'wxc-xxxxxx',
      path: '/pages/index/index',
      miniProgramType: 1,
      webpageUrl: 'https://example.com',
      scene: 1,
      title: 'Check this Mini Program',
      description: 'It is awesome!',
      coverUrl: 'https://example.com/cover.png'
    });
  9. Register the WeChat SDK with `registerApp`

    main

    Before calling most WeChat-related APIs, you must register your application. This step initializes the native module and sets up event listeners for WeChat responses. registerApp returns a cleanup function that should be used to remove the event listener when the registration is no longer needed.

    Note: You must call registerApp before calling functions like sendAuthRequest, shareText, or requestPayment. Failure to do so will result in an error: Please register SDK before invoking [methodName].

    import { registerApp } from 'native-wechat';
    
    const unregister = registerApp({
      appid: 'YOUR_APPID',
      universalLink: 'https://your-link.com',
      log: true,
      logPrefix: 'MY_APP',
    });
    
    // Call unregister() when the app lifecycle requires it to clean up listeners
  10. Check if WeChat is installed with `isWechatInstalled`

    main

    Returns a boolean indicating whether the WeChat application is installed on the device.

    import { isWechatInstalled } from 'native-wechat';
    
    const installed = await isWechatInstalled();
    if (installed) {
      // Proceed with WeChat features
    }
  11. Share content via `shareText`, `shareImage`, `shareVideo`, or `shareWebpage`

    main

    These functions allow sharing various content types to WeChat. All sharing functions require a scene parameter (a number representing the sharing context).

    shareText

    Shares a plain text string.

    shareText({ text: 'Hello WeChat!', scene: 1 });

    shareImage

    Shares an image via a source URL.

    shareImage({ src: 'https://example.com/image.png', scene: 1 });

    shareVideo

    Shares a video with optional title, description, and cover URL.

    shareVideo({
      title: 'Cool Video',
      description: 'Check this out!',
      scene: 1,
      videoUrl: 'https://example.com/video.mp4',
      coverUrl: 'https://example.com/cover.jpg'
    });

    shareWebpage

    Shares a webpage URL.

    shareWebpage({
      title: 'My Website',
      description: 'Visit my site',
      scene: 1,
      webpageUrl: 'https://example.com',
      coverUrl: 'https://example.com/og-image.png'
    });