Implementation Guide
Back

From WeChat Official Account Admin Platform
Jump to: navigation, search

Contents

Function Description

Constructor Function

    /**
    * Constructor Function
    * @param $token string | Token set by the developer on the WeChat Official Account Admin Platform
    * @param $encodingAesKey string | EncodingAESKey set by the developer on the WeChat Official Account Admin Platform
    * @param $appId string | appid of an official account
    */
    public function WXBizMsgCrypt($token, $encodingAesKey, $appId)

Decryption function

    /**
     * Authenticate message validity and obtain decrypted message.
     * <ol>
     *    <li>generate security signature and authenticate signature</li>
     *    <li>If signature authenticated, extract encrypted message from xml.</li>
     *    <li>decrypt message</li>
     * </ol>
     *
     * @param $msgSignature string | signature string, corresponding to msg_signature of a URL
     * @param $timestamp string | time stamp, corresponding to timestamp of a URL
     * @param $nonce string | random string, corresponding to nonce of a URL
     * @param $postData string | encrypted text, corresponding to data of a POST request
     * @param &$msg string | decrypted text. It is valid if 0 is returned
     *
     * @return int |  0 is returned if decryption succeeds; otherwise, an error code is returned.
     */
    public function decryptMsg($msgSignature, $timestamp = null, $nonce, $postData, &$msg)

Encryption Function

    /**
     * Encrypt a reply message from an official account.
     * <ol>
     *    <li>encrypt the message to be sent by using AES-CBC</li>
     *    <li>generate security signature</li>
     *    <li>pack encrypted text and security signature to string in XML format </li>
     * </ol>
     *
     * @param $replyMsg string | message to be replied by an official account. It is a character string in XML format.
     * @param $timeStamp string | time stamp, a regenerated one or the original one on a URL
     * @param $nonce string | random string, a regenerated one or the original one on a URL
     * @param &$encryptMsg string | Encrypted message that can be directly sent to users, a character string containing msg_signature, timestamp, nonce, and encrypt in xml format, valid if 0 is returned
     *
     * @return int, 0 is returned if encryption succeeds; otherwise, an error code is returned
    */
    public function encryptMsg($replyMsg, $timeStamp, $nonce, &$encryptMsg)

How to Use

In security mode or compatibility mode, new parameters encrypt_type and msg_signature will appear on the URL. encrypt_type indicates encryption type and msg_signature indicates message signature. If encrypt_type does not exist or its value is raw, no encryption is implemented; if its value is aes, AES algorithm is used (at present, these are the only two valid values). The developer should determine the encryption status of a message sent from the WeChat Official Account System based on this parameter.

Encryption/decryption method in security mode is the same as that in compatibility mode. The difference is that xml messages in compatibility mode have added plaintext fields not included in security mode. For details, please see Technical Solution.

Instantiation

Use a constructor function to instantiate an object, entering the parameters token, appid, and EncodingAESKey for the official account.

Decryption

In security mode or compatibility mode, the developer's backend system receives the following encrypted text message ("……" indicates plaintext fields in compatibility mode):

encrypt_msg = 
<xml>
	<ToUserName><![CDATA[gh_10f6c3c3ac5a]]></ToUserName>
	……
	<Encrypt><![CDATA[hQM/NS0ujPGbF+/8yVe61E3mUVWVO1izRlZdyv26zrVUSE3zUEBdcXITxjbjiHH38kexVdpQLCnRfbrqny1yGvgqqKTGKxJWWQ9D5WiiUKxavHRNzYVzAjYkp7esNGy7HJcl/P3BGarQF3+AWyNQ5w7xax5GbOwiXD54yri7xmNMHBOHapDzBslbnTFiEy+8sjSl4asNbn2+ZVBpqGsyKDv0ZG+DlSlXlW+gNPVLP+YxeUhJcyfp91qoa0FJagRNlkNul4mGz+sZXJs0WF7lPx6lslDGW3J66crvIIx/klpl0oa/tC6n/9c8OFQ9pp8hrLq7B9EaAGFlIyz5UhVLiWPN97JkL6JCfxVooVMEKcKRrrlRDGe8RWVM3EW/nxk9Ic37lYY5j97YZfq375AoTBdGDtoPFZsvv3Upyut1i6G0JRogUsMPlyZl9B8Pl/wcA7k7i4LYMr2yK4SxNFrBUw==]]></Encrypt>
</xml>

Call the DecryptMsg API and enter the URL parameters received: msg_signature (note that it is msg_signature, not signature), timestamp, and nonce as well as encrypt_msg. If the call is successful, sMsg will be returned, containing the following XML content in plaintext format:

<xml>
	<ToUserName><![CDATA[gh_10f6c3c3ac5a]]></ToUserName>
	<FromUserName><![CDATA[oyORnuP8q7ou2gfYjqLzSIWZf0rs]]></FromUserName>
 	<CreateTime>1411035097</CreateTime>
	<MsgType><![CDATA[text]]></MsgType>
	<Content><![CDATA[this is a test message]]></Content>
	<MsgId>6060349595123187712</MsgId>
</xml>

Official Account Processes Messages

Generate the following XML message to be replied to the WeChat Official Account System:

res_msg = 
<xml>    
	<ToUserName><![CDATA[oyORnuP8q7ou2gfYjqLzSIWZf0rs]]></ToUserName>
	<FromUserName><![CDATA[gh_10f6c3c3ac5a]]></FromUserName>
	<CreateTime>1411034505</CreateTime>
	<MsgType><![CDATA[text]]></MsgType>
	<Content><![CDATA[Welcome to join us!]]></Content>
	<FuncFlag>0</FuncFlag>
</xml>

Encrypting Reply Message

Call the EncryptMsg API and enter the res_msg, timestamp, and nonce to be replied to the WeChat Official Account System. If encryption succeeds, sEncryptMsg is an encrypted message, as shown below:

<xml>
  	<Encrypt><![CDATA[LDFAmKFr7U/RMmwRbsR676wjym90byw7+hhh226e8bu6KVYy00HheIsVER4eMgz/VBtofSaeXXQBz6fVdkN2CzBUaTtjJeTCXEIDfTBNxpw/QRLGLqqMZHA3I+JiBxrrSzd2yXuXst7TdkVgY4lZEHQcWk85x1niT79XLaWQog+OnBV31eZbXGPPv8dZciKqGo0meTYi+fkMEJdyS8OE7NjO79vpIyIw7hMBtEXPBK/tJGN5m5SoAS6I4rRZ8Zl8umKxXqgr7N8ZOs6DB9tokpvSl9wT9T3E62rufaKP5EL1imJUd1pngxy09EP24O8Th4bCrdUcZpJio2l11vE6bWK2s5WrLuO0cKY2GP2unQ4fDxh0L4ePmNOVFJwp9Hyvd0BAsleXA4jWeOMw5nH3Vn49/Q/ZAQ2HN3dB0bMA+6KJYLvIzTz/Iz6vEjk8ZkK+AbhW5eldnyRDXP/OWfZH2P3WQZUwc/G/LGmS3ekqMwQThhS2Eg5t4yHv0mAIei07Lknip8nnwgEeF4R9hOGutE9ETsGG4CP1LHTQ4fgYchOMfB3wANOjIt9xendbhHbu51Z4OKnA0F+MlgZomiqweT1v/+LUxcsFAZ1J+Vtt0FQXElDKg+YyQnRCiLl3I+GJ/cxSj86XwClZC3NNhAkVU11SvxcXEYh9smckV/qRP2Acsvdls0UqZVWnPtzgx8hc8QBZaeH+JeiaPQD88frNvA==]]></Encrypt>
	<MsgSignature><![CDATA[8d9521e63f84b2cd2e0daa124eb7eb0c34b6204a]]></MsgSignature>
	<TimeStamp>1411034505</TimeStamp>
	<Nonce><![CDATA[1351554359]]></Nonce>
</xml>

Precautions

  • EncodingAESKey is 43-characters long(valid characters: a-z, A-Z and 0-9). Developers can change this setting in the server configuration section of the Developer Center on the WeChat Official Account Admin Platform.
  • For safety reasons, the WeChat Official Account Admin Platform allows official accounts to change EncodingAESKey if it becomes insecure. It is recommended that developers save the current and prior EncodingAESKey so that the prior key can be re-used if decryption based on the current key fails. When replying, the key used for encryption must be identical to the one used for decryption.
  • In compatibility mode, the message will be provided as both plaintext and cyphertext, so the message length will be nearly doubled. Developers should check their system to avoid generating errors caused by overly long messages or excessive URL parameters.
  • If an URL does not contain encrypt_type or its value is raw, a plaintext message is returned; otherwise, an encrypted message will be returned. In compatibility mode, the developer's backend system can select to reply with a plaintext message or an encrypted message (choose one only).

Return Codes

Return Code Description
0 Processing successful
-40001 Signature authentication failed
-40002 XML message parsing failed
-40003 Calculating signature failed
-40004 Invalid AESKey
-40005 Verifying AppID failed
-40006 AES encryption failed
-40007 AES decryption failed
-40008 Invalid XML message sent by the WeChat Official Account System
-40009 Base64 encoding failed
-40010 Base64 decoding failed
-40011 The developer's backend system failed to generate an XML reply message

Code Samples

The WeChat Official Account Admin Platform provides developers with code samples in PHP. Click here to download.

Developer Guide
Custom-defined Menu
WeChat JS-SDK