hejunjie / wechat-clawbot
WeChat ClawBot API client for PHP — QR-code login, long-polling messages, send/receive text & media. Zero dependencies. | 微信 ClawBot 的 PHP 客户端:扫码登录、长轮询收消息、文本与媒体收发,零第三方依赖
Requires
- php: ^8.0
- ext-curl: *
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A dependency-free PHP client for the WeChat iLink ClawBot API. Log in by QR code, receive messages through long polling, and reply with text, images, files or videos.
Features
- QR-code login — request a login QR code and poll its scan status with configurable long-poll windows.
- Long-polling receive loop —
getUpdates()manages the cursor for you and treats local timeouts as empty polls. - Send text and media — text, images, files and videos. Media upload (request upload URL → AES-128-ECB encryption → CDN upload → send) is handled internally.
- Receive and decrypt media — inbound images, voice, video and files are downloaded, decrypted and saved with automatic extension detection.
- Typing indicator — start and cancel the "typing" state with a ticket fetched on demand.
- Typed data objects — every message item (text / image / voice / file / video / quote) has a dedicated class with typed properties.
- Configurable storage — media output directory, temporary cache directory and request timeout are all configurable.
- Zero dependencies — only
ext-curl(andext-opensslfor media) is required.
Requirements
- PHP >= 8.0
ext-curlext-openssl(only if you send or download media)
Installation
composer require hejunjie/wechat-clawbot
How it works
sequenceDiagram
participant U as WeChat user
participant W as iLink server
participant B as Your PHP program
U->>W: Send a message (text / image / voice / file / video)
B->>W: POST /ilink/bot/getupdates (get_updates_buf)
W-->>B: ret=0, msgs[], context_token, get_updates_buf'
B->>B: Persist the new cursor
opt Typing indicator
B->>W: POST /ilink/bot/getconfig
W-->>B: typing_ticket
B->>W: POST /ilink/bot/sendtyping (status=1)
end
alt Reply with text
B->>W: POST /ilink/bot/sendmessage (context_token + TEXT)
else Reply with media
B->>W: POST /ilink/bot/getuploadurl
W-->>B: upload_param
B->>W: POST CDN /upload (AES-128-ECB ciphertext)
W-->>B: x-encrypted-param
B->>W: POST /ilink/bot/sendmessage (context_token + CDN media)
end
opt End typing
B->>W: POST /ilink/bot/sendtyping (status=2)
end
W-->>U: User sees the reply
Loading
A typical integration has four stages:
- Login — call
getQrCode(), showqrcodeImgContentto the user as a QR code, then pollgetQrCodeStatus()untilstatus === 'confirmed'. PersistbotToken,baseUrl,ilinkBotIdandilinkUserId. - Authenticate — pass the saved credentials to
setCredentials()on every start-up. - Receive — run a loop over
getUpdates(), feeding back thegetUpdatesBufcursor and handlingmsgs. - Reply — send back with
sendText()/sendImage()/sendFile()/sendVideo(), passing the inboundfromUserIdandcontextTokenunchanged.
Important
context_token is the conversation anchor, not an optional field. Every reply must echo the token from the inbound message. Keep a (botId, userId) → contextToken cache and refresh it on each incoming message; without it the server cannot route the reply to the right conversation.
Quick start
<?php use Hejunjie\WechatClawbot\ClawBot; require __DIR__ . '/vendor/autoload.php'; $bot = new ClawBot([ // 'skRouteTag' => '1001', // Optional routing tag, only when your deployment requires it ]); // 1. Get a login QR code $qr = $bot->getQrCode(); if (!$qr->success) { throw new RuntimeException($qr->error); } // Render $qr->qrcodeImgContent as a QR code and let the user scan it. echo "Scan this URL with WeChat: {$qr->qrcodeImgContent}\n"; // 2. Poll until confirmed (status: wait | scaned | confirmed | expired) while (true) { $status = $bot->getQrCodeStatus($qr->qrcode, 30); if (!$status->success) { throw new RuntimeException($status->error); } if ($status->timedOut || $status->status === 'wait' || $status->status === 'scaned') { continue; } if ($status->status === 'expired') { throw new RuntimeException('QR code expired, request a new one'); } break; } // 3. Store the credentials, then hand them to the client // $botToken = $status->botToken; // $baseUrl = $status->baseUrl; // $ilinkUserId = $status->ilinkUserId; // Needed later for typing indicators $bot->setCredentials($status->botToken, $status->baseUrl); // 4. Receive and reply $getUpdatesBuf = null; while (true) { $updates = $bot->getUpdates($getUpdatesBuf); if (!$updates->success) { fwrite(STDERR, 'Poll failed: ' . ($updates->error ?? $updates->errmsg) . PHP_EOL); if ($updates->sessionExpired) { // Session expired: clear stored credentials, run the login flow again exit(1); } sleep(2); continue; } // A local long-poll timeout is an empty poll: keep the old cursor and poll again if ($updates->timedOut) { continue; } $getUpdatesBuf = $updates->getUpdatesBuf; foreach ($updates->msgs as $message) { foreach ($message->itemList as $item) { if ($item->type === 1 && $item->textItem !== null) { echo "Text: {$item->textItem->text}\n"; } } if ($message->contextToken === null || $message->contextToken === '') { continue; } $bot->sendText($message->fromUserId, $message->contextToken, 'Message received'); } }
Configuration
All options can be passed to the ClawBot constructor, either as an array or as a Config object. Both camelCase and snake_case keys are accepted.
$bot = new ClawBot([ 'baseUrl' => 'https://ilinkai.weixin.qq.com', 'skRouteTag' => null, 'channelVersion' => '1.0.0', 'timeout' => 40, 'botType' => 3, 'cacheDir' => sys_get_temp_dir() . '/wechat-clawbot/cache', 'mediaDir' => getcwd() . '/file', ]);
| Key (camelCase / snake_case) | Type | Default | Description |
|---|---|---|---|
baseUrl / base_url |
string |
https://ilinkai.weixin.qq.com |
Business API base URL. Overwritten by the baseUrl returned at login. |
skRouteTag / sk_route_tag |
string|null |
null |
Optional SKRouteTag header for deployments that require routing. |
channelVersion / channel_version |
string |
1.0.0 |
Reported as base_info.channel_version. |
timeout |
int |
40 |
Request timeout in seconds; also the default long-poll window. |
botType / bot_type |
int |
3 |
bot_type sent when requesting the login QR code. |
cacheDir / cache_dir |
string |
sys_get_temp_dir()/wechat-clawbot/cache |
Directory for temporary encrypted media while downloading. |
mediaDir / media_dir |
string |
getcwd()/file |
Root directory for downloaded media; image/, voice/, video/, file/ subdirectories are created automatically. |
API Reference
Login
getQrCode(): QrCode
Requests a login QR code. No parameters.
| Result field | Type | Description |
|---|---|---|
success |
bool |
Whether the request succeeded. |
qrcode |
string|null |
Polling token, pass it to getQrCodeStatus(). |
qrcodeImgContent |
string|null |
URL payload to encode as a QR code for the user to scan. |
getQrCodeStatus(string $qrcode, ?int $timeout = null): QrCodeStatus
Polls the scan status of a QR code.
| Parameter | Type | Description |
|---|---|---|
$qrcode |
string |
Token returned by getQrCode(). |
$timeout |
int|null |
Long-poll window in seconds. null uses the configured timeout. A local timeout is not an error. |
| Result field | Type | Description |
|---|---|---|
success |
bool |
Whether the request succeeded. |
status |
string|null |
wait (not scanned / still waiting), scaned (scanned, waiting for confirmation), confirmed (logged in), expired (request a new QR code). |
baseUrl |
string|null |
Business API base URL. Only present when confirmed. |
botToken |
string|null |
Bearer token. Only present when confirmed. |
ilinkBotId |
string|null |
Bot account ID. Only present when confirmed. |
ilinkUserId |
string|null |
ID of the WeChat user who scanned the code. Only present when confirmed; needed for typing indicators. |
timedOut |
bool |
true when the local long-poll timed out; status is then wait. |
setCredentials(string $botToken, ?string $baseUrl = null): void
Writes the credentials used by all subsequent business requests.
| Parameter | Type | Description |
|---|---|---|
$botToken |
string |
Token returned by getQrCodeStatus(). |
$baseUrl |
string|null |
Business API base URL. When omitted, the configured or current base URL is kept. |
Receiving
getUpdates(?string $getUpdatesBuf = null): Updates
Long-polls for new messages.
| Parameter | Type | Description |
|---|---|---|
$getUpdatesBuf |
string|null |
Cursor returned by the previous call. Pass null on the first poll. |
| Result field | Type | Description |
|---|---|---|
success |
bool |
Whether the request succeeded. |
msgs |
Message[] |
New messages in this poll. |
getUpdatesBuf |
string|null |
Cursor to pass to the next poll. On a local timeout the previous cursor is returned unchanged. |
longpollingTimeoutMs |
int|null |
Server-suggested long-poll window in milliseconds. |
timedOut |
bool |
true when the local long-poll timed out. This is an empty poll: continue immediately with the same cursor. |
Note
Persist getUpdatesBuf between process restarts. Reusing an old cursor may replay messages; discarding it may skip messages.
Sending
sendText(string $toUserId, string $contextToken, string $text, ?string $clientId = null): SendResult
Sends a text message.
| Parameter | Type | Description |
|---|---|---|
$toUserId |
string |
Recipient, i.e. the inbound message's fromUserId. |
$contextToken |
string |
Conversation token from the inbound message. |
$text |
string |
Message body. Long text is not split automatically; keep each message within roughly 2000 characters. |
$clientId |
string|null |
Unique message ID. Generated automatically when omitted. |
sendImage(string $toUserId, string $contextToken, string $filePath, ?string $clientId = null): SendResult
Uploads a local image to the CDN and sends it as an image message.
| Parameter | Type | Description |
|---|---|---|
$toUserId |
string |
Recipient user ID. |
$contextToken |
string |
Conversation token from the inbound message. |
$filePath |
string |
Local path of the image. Any format the CDN accepts (jpg / png / gif / webp / bmp) works. |
$clientId |
string|null |
Unique message ID. Generated automatically when omitted. |
sendFile(string $toUserId, string $contextToken, string $filePath, ?string $clientId = null): SendResult
Uploads a local file and sends it as a file message. The receiver sees the original basename of $filePath as the file name.
| Parameter | Type | Description |
|---|---|---|
$toUserId |
string |
Recipient user ID. |
$contextToken |
string |
Conversation token from the inbound message. |
$filePath |
string |
Local path of the file. |
$clientId |
string|null |
Unique message ID. Generated automatically when omitted. |
sendVideo(string $toUserId, string $contextToken, string $filePath, ?string $clientId = null): SendResult
Uploads a local video and sends it as a video message.
| Parameter | Type | Description |
|---|---|---|
$toUserId |
string |
Recipient user ID. |
$contextToken |
string |
Conversation token from the inbound message. |
$filePath |
string |
Local path of the video (typically mp4). |
$clientId |
string|null |
Unique message ID. Generated automatically when omitted. |
Note
The three media senders return a failed SendResult instead of throwing when the file is missing, the upload URL cannot be obtained, or the CDN upload fails. Inspect success and error.
Typing indicator
getTypingTicket(string $ilinkUserId, string $contextToken): TypingTicket
Fetches the ticket required by sendTyping().
| Parameter | Type | Description |
|---|---|---|
$ilinkUserId |
string |
The scanning user's ID, from the login result ($status->ilinkUserId). |
$contextToken |
string |
Conversation token from the inbound message. |
| Result field | Type | Description |
|---|---|---|
success |
bool |
Whether the request succeeded. |
typingTicket |
string|null |
Ticket to pass to sendTyping(). |
sendTyping(string $ilinkUserId, string $typingTicket, int $status): SendResult
Starts or cancels the "typing" state.
| Parameter | Type | Description |
|---|---|---|
$ilinkUserId |
string |
The scanning user's ID. |
$typingTicket |
string |
Ticket from getTypingTicket(). |
$status |
int |
ClawBot::TYPING_START (1) or ClawBot::TYPING_CANCEL (2). |
Downloading media
All four download methods behave the same way: they fetch the encrypted payload from the CDN, decrypt it with AES-128-ECB, detect the file extension from the magic number, write the file with a random 32-character hex name, and return the absolute path.
| Method | Item parameter | Default subdirectory |
|---|---|---|
downloadImage(ImageItem $item, ?string $saveDir = null): string |
MessageItem::$imageItem |
mediaDir/image |
downloadVoice(VoiceItem $item, ?string $saveDir = null): string |
MessageItem::$voiceItem |
mediaDir/voice |
downloadVideo(VideoItem $item, ?string $saveDir = null): string |
MessageItem::$videoItem |
mediaDir/video |
downloadFile(FileItem $item, ?string $saveDir = null): string |
MessageItem::$fileItem |
mediaDir/file |
| Parameter | Type | Description |
|---|---|---|
$item |
item object | The parsed item from an inbound message. |
$saveDir |
string|null |
Optional target directory. Created recursively if missing. Falls back to the configured mediaDir plus the type subdirectory. |
foreach ($message->itemList as $item) { try { $path = match ($item->type) { 2 => $bot->downloadImage($item->imageItem), 3 => $bot->downloadVoice($item->voiceItem), 4 => $bot->downloadFile($item->fileItem), 5 => $bot->downloadVideo($item->videoItem), }; echo "Saved to {$path}\n"; } catch (Throwable $e) { echo "Download failed: {$e->getMessage()}\n"; } }
Warning
Download methods throw exceptions instead of returning a result object: InvalidArgumentException when the item lacks a media reference or AES key, RuntimeException when downloading, decrypting or writing fails. Wrap them in try/catch so one bad message does not break the polling loop.
Result objects
Every returned object extends Result:
| Field | Type | Description |
|---|---|---|
success |
bool |
Whether the call succeeded. |
error |
string|null |
Transport / HTTP level error message. |
errcode |
int|null |
Business error code when non-zero. |
errmsg |
string|null |
Business error description. |
sessionExpired |
bool |
true when the error code is -14: clear local state and log in again. |
Protocol-level failures are reported through these fields rather than exceptions. The only methods that throw are the four media downloaders.
Message data structures
Message
| Property | Type | Description |
|---|---|---|
seq |
int|null |
Message sequence number. |
messageId |
int|null |
Message ID. |
fromUserId |
string|null |
Sender ID; use it as the recipient when replying. |
toUserId |
string|null |
Recipient ID. |
clientId |
string|null |
Client-generated message ID. |
createTimeMs |
int|null |
Created at, milliseconds. |
updateTimeMs |
int|null |
Updated at, milliseconds. |
deleteTimeMs |
int|null |
Deleted at, milliseconds. |
sessionId |
string|null |
Session ID. |
groupId |
string|null |
Group ID, if any. |
messageType |
int|null |
1 = USER, 2 = BOT. |
messageState |
int|null |
0 = NEW, 1 = GENERATING, 2 = FINISH. |
itemList |
MessageItem[] |
Message content items. |
contextToken |
string|null |
Conversation token. Echo it back when replying. |
MessageItem
| Property | Type | Description |
|---|---|---|
type |
int|null |
1 = TEXT, 2 = IMAGE, 3 = VOICE, 4 = FILE, 5 = VIDEO. |
createTimeMs |
int|null |
Created at, milliseconds. |
updateTimeMs |
int|null |
Updated at, milliseconds. |
isCompleted |
bool|null |
Whether the item finished uploading / generating. |
msgId |
string|null |
Item-level message ID. |
refMsg |
RefMessage|null |
Quoted message, if any. |
textItem |
TextItem|null |
Present when type === 1. |
imageItem |
ImageItem|null |
Present when type === 2. |
voiceItem |
VoiceItem|null |
Present when type === 3. |
fileItem |
FileItem|null |
Present when type === 4. |
videoItem |
VideoItem|null |
Present when type === 5. |
TextItem
| Property | Type | Description |
|---|---|---|
text |
string|null |
Text body. |
ImageItem
| Property | Type | Description |
|---|---|---|
media |
CdnMedia|null |
Main image reference. |
thumbMedia |
CdnMedia|null |
Thumbnail reference. |
aeskey |
string|null |
32-character hex AES key, if provided by the sender. Used with priority over media.aesKey. |
url |
string|null |
Preview URL, if provided. |
midSize |
int|null |
Main image ciphertext size. |
thumbSize |
int|null |
Thumbnail ciphertext size. |
thumbHeight |
int|null |
Thumbnail height in pixels. |
thumbWidth |
int|null |
Thumbnail width in pixels. |
hdSize |
int|null |
HD image ciphertext size. |
VoiceItem
| Property | Type | Description |
|---|---|---|
media |
CdnMedia|null |
Voice reference. |
encodeType |
int|null |
1 = pcm, 2 = adpcm, 3 = feature, 4 = speex, 5 = amr, 6 = silk, 7 = mp3, 8 = ogg-speex. |
bitsPerSample |
int|null |
Bit depth. |
sampleRate |
int|null |
Sample rate in Hz. |
playtime |
int|null |
Duration in milliseconds. |
text |
string|null |
Speech-to-text result, if the sender's client provided one. |
FileItem
| Property | Type | Description |
|---|---|---|
media |
CdnMedia|null |
File reference. |
fileName |
string|null |
Original file name. |
md5 |
string|null |
File MD5. |
len |
string|null |
Plaintext size in bytes, as a string. |
VideoItem
| Property | Type | Description |
|---|---|---|
media |
CdnMedia|null |
Main video reference. |
videoSize |
int|null |
Video ciphertext size. |
playLength |
int|null |
Duration in milliseconds. |
videoMd5 |
string|null |
Video MD5. |
thumbMedia |
CdnMedia|null |
Thumbnail reference. |
thumbSize |
int|null |
Thumbnail ciphertext size. |
thumbHeight |
int|null |
Thumbnail height in pixels. |
thumbWidth |
int|null |
Thumbnail width in pixels. |
CdnMedia
| Property | Type | Description |
|---|---|---|
encryptQueryParam |
string|null |
Encrypted query parameter used by the CDN download endpoint. |
aesKey |
string|null |
Base64-encoded AES key. Both base64(raw 16 bytes) and base64(hex string) forms are accepted. |
encryptType |
int|null |
0 = file id only, 1 = thumbnail / mid-size info included. |
RefMessage
| Property | Type | Description |
|---|---|---|
title |
string|null |
Quote summary. |
messageItem |
MessageItem|null |
The quoted item. |
Error handling
- Check
successon every result object. Readerrorfor transport failures anderrcode/errmsgfor business failures. - When
sessionExpiredistrue(-14), clear the stored credentials and cursor, then run the login flow again. - A long-poll timeout is normal:
getUpdates()->timedOut === truemeans "no message yet", not an error. - Deduplicate by
messageIdif your program may restart and replay the same cursor.
Notes
context_tokencomes from inbound messages only. You cannot message a user proactively unless you have a valid token for that conversation.- Generate a new
client_idfor every outgoing message. The client does this automatically when you omit it. - Outgoing
message_stateis always2(FINISH); the intermediateGENERATINGstate is not used. - Downloaded files always get a random 32-character hex file name; the original name is preserved only in
FileItem::$fileNameand in the file name shown to recipients ofsendFile(). - Voice sending is not implemented yet.
sendText()does not split long text. Split it yourself if you may exceed roughly 2000 characters.
Project layout
src/
├── ClawBot.php # Public entry point
├── Config.php # Client configuration
├── Endpoint.php # API paths and defaults
├── HttpClient.php # curl transport (JSON, binary, download)
├── Response.php # Normalized transport result
├── Media/ # Upload, download, extension detection
├── Message/ # Typed message data objects
├── Result/ # Typed API result objects
└── Support/ # UIN and AES key helpers