🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@sohu-bpd/wechat

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@sohu-bpd/wechat - npm Package Compare versions

Comparing version
0.0.2
to
0.0.3
+322
README.md
# @sohu-bpd/wechat
WeChat JS-SDK utility library with automatic SDK loading, initialization, and SPA support.
## Features
- 🚀 **Auto SDK Loading** - Automatically loads WeChat JS-SDK from CDN
- 🔄 **SPA Support** - Auto re-initialization on URL changes for single-page apps
- 📱 **iOS Compatible** - Handles iOS WeChat signature URL quirks automatically
- 🎯 **High-level APIs** - Simple `config()` and `share()` APIs for common tasks
- 📦 **TypeScript** - Full type definitions included
- 🌐 **Multiple Formats** - ESM, CommonJS, and IIFE bundles
## Installation
```bash
npm install @sohu-bpd/wechat
# or
pnpm add @sohu-bpd/wechat
# or
yarn add @sohu-bpd/wechat
```
## Quick Start
### 1. Configure Once
```typescript
import { config } from '@sohu-bpd/wechat'
config({
sdkUrl: 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js',
getSignature: async (url) => {
// Fetch signature from your backend
const response = await fetch(`/api/wechat/signature?url=${encodeURIComponent(url)}`)
return response.json()
},
debug: false,
spa: true, // Enable SPA mode (default)
})
```
### 2. Use Anywhere
```typescript
import { share } from '@sohu-bpd/wechat'
// Set share content
await share({
title: 'My Page Title',
desc: 'Share description',
imgUrl: 'https://example.com/image.jpg',
link: 'https://example.com/page', // optional, defaults to current URL
})
```
## Usage
### ESM / CommonJS
```typescript
import { config, share } from '@sohu-bpd/wechat'
// or
const { config, share } = require('@sohu-bpd/wechat')
```
### Browser (IIFE)
```html
<script src="https://unpkg.com/@sohu-bpd/wechat/dist/index.global.js"></script>
<script>
const { config, share } = SohuWechat
config({
sdkUrl: 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js',
getSignature: async (url) => {
const res = await fetch('/api/wechat/signature?url=' + encodeURIComponent(url))
return res.json()
}
})
share({
title: 'My Page',
desc: 'Description',
imgUrl: 'https://example.com/image.jpg'
})
</script>
```
## API Reference
### High-level APIs
#### config(options)
Set global configuration for WeChat JS-SDK.
```typescript
interface GlobalConfig {
/** WeChat JS-SDK URL */
sdkUrl: string
/** Function to fetch signature, receives current URL */
getSignature: (url: string) => Promise<SignatureResult>
/** Enable debug mode, default false */
debug?: boolean
/** Enable SPA mode (auto re-init on URL change), default true */
spa?: boolean
}
function config(options: GlobalConfig): void
```
**Example:**
```typescript
config({
sdkUrl: 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js',
getSignature: async (url) => {
const res = await fetch(`/api/wechat/signature?url=${encodeURIComponent(url)}`)
return res.json()
},
debug: process.env.NODE_ENV === 'development',
spa: true,
})
```
#### share(options)
Set WeChat share content for both friends and moments.
```typescript
interface ShareOptions {
/** Share title */
title: string
/** Share description (for friends) */
desc?: string
/** Share link, defaults to current URL */
link?: string
/** Share image URL */
imgUrl: string
}
function share(options: ShareOptions): Promise<void>
```
**Example:**
```typescript
await share({
title: 'Amazing Product',
desc: 'Check out this amazing product!',
imgUrl: 'https://example.com/product.jpg',
link: 'https://example.com/product/123',
})
```
#### getConfig()
Get current global configuration (throws if not configured).
```typescript
function getConfig(): GlobalConfig
```
#### isConfigured()
Check if global configuration has been set.
```typescript
function isConfigured(): boolean
```
### Low-level APIs
For advanced use cases, you can use the low-level APIs:
#### loadSDK()
Load WeChat JS-SDK script (automatically called by high-level APIs).
```typescript
function loadSDK(sdkUrl: string): Promise<void>
```
#### initSDK(jsApiList)
Initialize WeChat SDK with specified APIs (automatically called by high-level APIs).
```typescript
function initSDK(jsApiList: string[]): Promise<void>
```
#### getWx()
Get the global `wx` object after SDK is loaded.
```typescript
function getWx(): any
```
#### resetSDK()
Reset SDK state (useful for testing or manual re-initialization).
```typescript
function resetSDK(): void
```
### Original init Function
For use cases that don't need global configuration:
```typescript
interface InitConfig {
/** Public account appId */
appId: string
/** Signature timestamp */
timestamp: number | string
/** Signature nonce string */
nonceStr: string
/** Signature */
signature: string
/** JS API list to use */
jsApiList: string[]
/** Enable debug mode */
debug?: boolean
}
function init(config: InitConfig): Promise<void>
```
## SPA Mode
By default, `spa: true` is enabled, which means:
- On the **first** API call (e.g., `share()`), the SDK is initialized with the current URL
- On **subsequent** API calls, if the URL has changed, the SDK is automatically re-initialized
- This is essential for single-page applications where the URL changes without page reloads
To disable SPA mode:
```typescript
config({
// ...
spa: false, // Only initialize once
})
```
## iOS WeChat Quirk
On iOS WeChat, the signature URL should be the **first entry URL** of the app, not the current URL. This library handles this automatically:
- On iOS, it remembers the first URL and always uses it for signatures
- On Android, it uses the current URL for each signature request
You don't need to do anything special - it just works.
## Backend Signature Endpoint
Your backend should provide an endpoint that generates WeChat JS-SDK signatures. Here's an example implementation:
```typescript
// Node.js + Express example
app.get('/api/wechat/signature', async (req, res) => {
const url = req.query.url as string
// Generate signature using WeChat's algorithm
const signature = await generateWeChatSignature(url)
res.json({
appId: 'your-app-id',
timestamp: signature.timestamp,
nonceStr: signature.nonceStr,
signature: signature.signature,
})
})
```
Refer to [WeChat JS-SDK Documentation](https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html) for signature generation details.
## TypeScript Support
Full TypeScript definitions are included:
```typescript
import type {
GlobalConfig,
SignatureResult,
ShareOptions
} from '@sohu-bpd/wechat'
const config: GlobalConfig = {
sdkUrl: '...',
getSignature: async (url: string): Promise<SignatureResult> => {
// ...
}
}
```
## Bundle Formats
- **ESM** (`.mjs`) - Modern JavaScript modules
- **CommonJS** (`.js`) - Node.js and bundlers
- **IIFE** (`.global.js`) - Browser `<script>` tag with global `SohuWechat`
## Changelog
### 0.0.2 (2026-01-29)
- Extract WeChat JS-SDK module as standalone package
- High-level `config()` and `share()` APIs
- Automatic SDK loading and initialization
- SPA mode with auto re-initialization on URL changes
- iOS WeChat signature URL handling
- Full TypeScript support
- Comprehensive unit tests
- Multiple bundle formats (ESM, CJS, IIFE)
## License
MIT
+1
-1
{
"name": "@sohu-bpd/wechat",
"version": "0.0.2",
"version": "0.0.3",
"description": "WeChat JS-SDK utility library",

@@ -5,0 +5,0 @@ "main": "./dist/index.js",