Master WeChat Public Account Development: From Access Tokens to Interactive Bots

This guide walks you through the complete process of creating and managing a WeChat public account, covering registration, sandbox testing, access token handling, QR code generation, message verification, chatbot integration, menu creation, media upload, music search, and response handling using PHP.

21CTO
21CTO
21CTO
Master WeChat Public Account Development: From Access Tokens to Interactive Bots

Overview

Many readers have asked for a comprehensive guide on WeChat public account development and WeChat Pay integration. This article provides a complete solution for building and interacting with a WeChat public account using PHP.

Public Account Registration

The registration URL is https://mp.weixin.qq.com . Public accounts are divided into three categories, which differ only in permission levels.

Test Account (Sandbox)

Developers can use the sandbox environment at https://mp.weixin.qq.com/wiki for testing without affecting the production environment.

Access Token

The access_token is a globally unique credential required for all API calls. It can be obtained via the following PHP code:

$curl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=YOUR_APPID&secret=YOUR_SECRET';
$response = $this->_request($curl, true, 'GET');
$token = json_decode($response)->access_token;

Generating QR Codes

Use the ticket API to create a QR code. First generate a ticket, then exchange it for the QR image.

Message Verification

Download the verification sample file, replace the TOKEN constant, and use the provided responseMsg method to interact with users.

Chatbot Integration

Leverage external chatbot services such as Sobot or Microsoft XiaoIce. The data exchange format is demonstrated in the _doText method:

$curl = 'http://www.sobot.com/chat/robot/chat.action';
$data = 'requestText=' . $postObj->Content . '&sysNum=...&uid=...&cid=...';
$content = $this->_request($curl, false, 'POST', $data);
$content = json_decode($content);
$contentStr = $content->answer;

Sending News Messages

Construct an XML template for news messages and populate it with an array of articles. Example code:

private function _sendNews($postObj){
    $newstpl = '<xml>...<Articles>%s</Articles></xml>';
    $news_item_tpl = '<item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item>';
    // build $news_list and echo sprintf($newstpl, ...);
}

Creating Menus

Menus are defined in JSON format and created via the menu/create API:

public function _createMenu($menu){
    $curl = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $this->_getAccessToken();
    $content = json_decode($this->_request($curl, true, 'POST', $menu));
    if($content->errcode == 0) echo 'Menu created successfully';
}

Uploading Media

Upload media files using the following function:

public function _createMedia($type, $file){
    $curl = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $this->_getAccessToken() . '&type=' . $type;
    $data['type'] = $type;
    $data['media'] = '@' . $file;
    file_put_contents('./medialib', $this->_request($curl, true, 'POST', $data));
}

Music Search and Response

Search Baidu music by song name and optional singer, then return a music message XML:

private function _getMusicUrl($song, $singer){
    if($singer == '')
        $curl = 'http://box.zhangmen.baidu.com/x?op=12&count=1&title=' . $song . '$$';
    else
        $curl = 'http://box.zhangmen.baidu.com/x?op=12&count=1&title=' . $song . '$$' . $singer . '$$$$';
    $content = $this->_request($curl, false);
    $content = simplexml_load_string($content, 'SimpleXMLElement', LIBXML_NOCDATA);
    $musicurl = substr($content->url->encode,0,strrpos($content->url->encode,'/')+1) . substr($content->url->decode,0,strrpos($content->url->decode,'&'));
    return $musicurl;
}

private function _sendMusic($postObj){
    $postObj->Content = mb_substr($postObj->Content,2, mb_strlen($postObj->Content,'UTF-8')-2,'UTF-8');
    $songinfo = explode('@',$postObj->Content);
    $song = trim($songinfo[0]);
    $singer = isset($songinfo[1]) ? trim($songinfo[1]) : '';
    $musicUrl = $this->_getMusicUrl($song,$singer);
    $musictpl = '<xml>...<MusicUrl><![CDATA[%s]]></MusicUrl>...</xml>';
    $resultStr = sprintf($musictpl,$postObj->FromUserName,$postObj->ToUserName,time(),$song,$singer,$musicUrl,$musicUrl);
    echo $resultStr;
}

Conclusion

This article covered the full workflow for WeChat public account registration and interactive development. The next article will focus on detailed WeChat Pay integration.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPPublic Account
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.