本文演示如何調用百度 API Store 的「微信精選文章」接口,構建一個「回復『文章』獲取分類,回復『wz 分類ID 頁碼 關鍵詞』獲取文章列表」的內容聚合機器人。
https://apis.baidu.com/showapi_open_bus/weixin/weixin_article_typeweixin_article_list?typeId=分類ID&page=頁碼&key=關鍵詞// 在 responseMsg() 中
$keyword = trim($postObj->Content);
$prefix = mb_substr($keyword, 0, 2, 'UTF-8');
// 1. 用戶回復「文章」 -> 返回所有分類
if ($prefix == "文章") {
$url = 'https://apis.baidu.com/showapi_open_bus/weixin/weixin_article_type';
$header = ['apikey: YOUR_KEY'];
$ch = curl_init($url);
curl_setopt_array($ch, [CURLOPT_HTTPHEADER=>$header, CURLOPT_RETURNTRANSFER=>1]);
$res = json_decode(curl_exec($ch), true);
curl_close($ch);
$types = [];
foreach ($res['showapi_res_body']['typeList'] as $v) {
$types[] = "{$v['id']}、{$v['name']}";
}
sort($types, SORT_NUMERIC);
$content = "請回復以下格式查看文章:\nwz 分類ID 頁碼 關鍵詞\n\n" . implode("\n", $types);
echo sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $content);
exit;
}
// 2. 用戶回復「wz 19 1 籃球」 -> 返回體育類第1頁關鍵詞「籃球」的文章
if ($prefix == "wz") {
// 解析參數:wz 分類ID 頁碼 關鍵詞 (中文逗號分隔)
$parts = explode(',', $keyword); // 注意:原文用中文逗號
if (count($parts) != 3) {
$content = "格式錯誤,請使用:wz 分類ID,頁碼,關鍵詞";
echo sprintf($textTpl, ...); exit;
}
list($typeIdStr, $page, $key) = $parts;
$typeId = str_replace('wz', '', $typeIdStr);
$url = "https://apis.baidu.com/showapi_open_bus/weixin/weixin_article_list?typeId={$typeId}&page={$page}&key=" . urlencode($key);
$header = ['apikey: YOUR_KEY'];
$ch = curl_init($url);
curl_setopt_array($ch, [CURLOPT_HTTPHEADER=>$header, CURLOPT_RETURNTRANSFER=>1]);
$res = json_decode(curl_exec($ch), true);
curl_close($ch);
$articles = [];
foreach ($res['showapi_res_body']['pagebean']['contentlist'] as $k => $v) {
if ($k >= 7) break; // 微信圖文消息最多 10 條,這裡取 7
$articles[] = [
'title' => $v['title'],
'description' => $v['title'], // 或摘要
'picurl' => $v['contentImg'],
'url' => $v['url'],
];
}
// 組裝圖文消息 XML
$itemsXml = '';
foreach ($articles as $a) {
$itemsXml .= "-
";
}
$newsTpl = "
%s
" . count($articles) . "
{$itemsXml}
";
echo sprintf($newsTpl, $fromUsername, $toUsername, $time);
exit;
}
用戶:文章 公眾號: 1、新聞 2、娛樂 3、體育 ... 19、科技 ... 請回復:wz 19,1,騰訊 用戶:wz 19,1,騰訊 公眾號:[圖文消息] 1. 騰訊發布新版 QQ... 2. 騰訊雲雙十一大促... ... (共 7 條)
這種「分類導航 + 關鍵詞搜索 + 圖文回復」模式,是構建垂直領域資訊訂閱號的經典交互範式。