# How WeChat API Credentials (uin, key, pass_ticket) Are Parsed and Validated in the Exporter

> Learn how the WeChat Article Exporter parses and validates uin, key, and pass_ticket API credentials from localStorage. Discover the validation steps for secure API access.

- Repository: [公众号文章工具箱/wechat-article-exporter](https://github.com/wechat-article/wechat-article-exporter)
- Tags: internals
- Published: 2026-05-26

---

**WeChat API credentials—including `uin`, `key`, and `pass_ticket`—are parsed from JSON strings stored in browser `localStorage`, validated for required field presence, and verified through lightweight HTTP requests before being injected into WeChat MP API query parameters.**

The `wechat-article-exporter` works with the official WeChat MP (公众号) web API, requiring a structured **Credential** object to authenticate requests. Understanding how these sensitive tokens are extracted from storage, checked for completeness, and confirmed as active is essential for maintaining reliable article downloads.

## Credential Structure and Storage Locations

The exporter defines the credential schema in **[`types/credential.d.ts`](https://github.com/wechat-article/wechat-article-exporter/blob/main/types/credential.d.ts)**, which specifies the exact fields required to impersonate a logged-in WeChat session:

```typescript
export interface ParsedCredential {
  nickname?: string;
  avatar?: string;
  biz: string;           // the "fakeid" of the public account
  uin: string;           // user identifier (微信登录后返回)
  key: string;           // "key" parameter from the login response
  pass_ticket: string;   // "pass_ticket" from the login response
  wap_sid2: string;      // auxiliary cookie
  appmsg_token: string;  // token for "appmsg" requests
  cookie?: string;       // whole cookie string (optional)
  timestamp: number;
  valid: boolean;        // set to true after a successful validation test
}

```

The application maintains credentials in two separate storage mechanisms:

- **Auto-detected credentials**: An array of `ParsedCredential` objects persisted in `localStorage` under the key `auto-detect-credentials:credentials`. This is accessed via the VueUse composable in **[`utils/download/BaseDownloader.ts`](https://github.com/wechat-article/wechat-article-exporter/blob/main/utils/download/BaseDownloader.ts)** (lines 11‑14):

```typescript
const credentials = useLocalStorage<ParsedCredential[]>(
  'auto-detect-credentials:credentials', []
);

```

- **Manually entered credentials**: A single JSON object stored under the key `credentials`, parsed in **[`apis/index.ts`](https://github.com/wechat-article/wechat-article-exporter/blob/main/apis/index.ts)** (lines 108‑110) when users input credentials directly.

## Parsing WeChat API Credentials from Storage

When the downloader initializes or an API request requires authentication, the credential string undergoes standard JSON parsing. In **[`apis/index.ts`](https://github.com/wechat-article/wechat-article-exporter/blob/main/apis/index.ts)** (line 109), the raw string is converted to a typed object:

```typescript
const raw = window.localStorage.getItem('credentials');
const parsed = JSON.parse(raw) as ParsedCredential;

```

Similarly, auto-detected credentials are retrieved as reactive arrays from `localStorage`. Before any network call, the code selects the appropriate credential by matching the `biz` (fakeid) field and confirming the `valid` flag:

```typescript
// utils/download/BaseDownloader.ts – line 89
const targetCredential = credentials.value.find(
  item => item.biz === fakeid && item.valid
);

```

## Field Validation Logic

The exporter implements **presence validation** to ensure critical authentication tokens exist before attempting API calls. In **[`apis/index.ts`](https://github.com/wechat-article/wechat-article-exporter/blob/main/apis/index.ts)** (lines 108‑112), the code explicitly guards against missing fields:

```typescript
if (!credentials || !credentials.__biz || !credentials.pass_ticket ||
    !credentials.key || !credentials.uin) {
  console.warn('credentials not set');
  return null;
}

```

This validation step ensures that `uin`, `key`, `pass_ticket`, and the business identifier (`biz` or `__biz`) are all defined. If any required field is absent, the function returns `null` early, preventing malformed requests to WeChat's servers.

## Runtime Validation via Test Requests

Beyond static field checks, the exporter performs **active validation** by issuing lightweight HTTP requests to verify that the credentials remain valid and have not expired. This two-level validation system works as follows:

1. **Initial presence check**: Validates that `biz`, `uin`, `key`, `pass_ticket`, and `wap_sid2` exist in the parsed object.
2. **Live verification**: After auto-detection, the system performs a test request (such as fetching an article list). If the request succeeds, the `valid` property is set to `true`.

The `valid` flag is consumed by the `validateCredential` methods in both `BaseDownloader` (lines 89‑95) and `Downloader` (lines 254, 351). If a credential fails validation or the flag is `false`, the downloader throws an error:

```typescript
// utils/download/BaseDownloader.ts – lines 90-94
if (!targetCredential) {
  throw new Error('目标公众号的 Credential 未设置');
}

```

## Injecting Credentials into API Requests

Once validated, the credential components are URL-encoded and appended to WeChat MP API endpoints as query parameters. In **[`utils/download/Downloader.ts`](https://github.com/wechat-article/wechat-article-exporter/blob/main/utils/download/Downloader.ts)** (lines 479‑486), the code constructs request URLs for comment fetching:

```typescript
const url = `https://mp.weixin.qq.com/mp/appmsg_comment?...&__biz=${targetCredential.biz}` +
            `&uin=${targetCredential.uin}&key=${targetCredential.key}` +
            `&pass_ticket=${encodeURIComponent(targetCredential.pass_ticket)}` +
            `&appmsg_token=${encodeURIComponent(targetCredential.appmsg_token)}`;
// optional raw cookie header
if (targetCredential.cookie) {
  headers.Cookie = targetCredential.cookie;
}

```

The `pass_ticket` and `appmsg_token` values are explicitly URL-encoded to handle special characters, while `uin` and `key` are injected directly into the query string.

## Summary

- **Credential Structure**: Defined in [`types/credential.d.ts`](https://github.com/wechat-article/wechat-article-exporter/blob/main/types/credential.d.ts) with required fields `uin`, `key`, `pass_ticket`, and `biz`.
- **Storage**: Auto-detected credentials live in `localStorage` under `auto-detect-credentials:credentials`; manual entries use the key `credentials`.
- **Parsing**: Raw JSON strings are parsed using `JSON.parse()` and cast to the `ParsedCredential` interface.
- **Validation**: Required fields are checked in [`apis/index.ts`](https://github.com/wechat-article/wechat-article-exporter/blob/main/apis/index.ts), followed by live HTTP validation that sets the `valid` boolean flag.
- **Usage**: Valid credentials are injected into WeChat MP API URLs as query parameters, with `pass_ticket` and `appmsg_token` URL-encoded for safety.

## Frequently Asked Questions

### What happens if the pass_ticket or key values are missing?

If `pass_ticket`, `key`, `uin`, or `biz` are missing when parsed from `localStorage`, the validation logic in [`apis/index.ts`](https://github.com/wechat-article/wechat-article-exporter/blob/main/apis/index.ts) catches the omission and returns `null` before any network request is made. The downloader will subsequently throw an error stating that the target credential is not set.

### How does the exporter know if credentials have expired?

The exporter determines credential freshness through the `valid` boolean flag. After initial detection, a test request validates the session; if it fails, `valid` remains `false`. The `BaseDownloader.validateCredential` method checks this flag before every download operation, rejecting expired sessions early in the process.

### Can I manually input credentials instead of using auto-detection?

Yes. The system supports manual credential entry via `localStorage` key `credentials`. When manually entered, the JSON object is parsed and validated using the same field checks in [`apis/index.ts`](https://github.com/wechat-article/wechat-article-exporter/blob/main/apis/index.ts), though you must ensure the `valid` flag is manually set to `true` or the downloader will reject the credential.

### Where are the credentials actually attached to HTTP requests?

Credential values are appended to request URLs in [`utils/download/Downloader.ts`](https://github.com/wechat-article/wechat-article-exporter/blob/main/utils/download/Downloader.ts) (around line 479). The `uin`, `key`, and `pass_ticket` parameters are added to the query string, while the full `cookie` string is optionally attached to the `Cookie` header for asset download requests.