public function responseMsg() {
$postStr = $GLOBALS['HTTP_RAW_POST_DATA'];
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$from = $postObj->FromUserName; $to = $postObj->ToUserName;
$kw = trim($postObj->Content); $time = time();
$prefix = mb_substr($kw, 0, 2, 'UTF-8');
// 1. 顯示分類
if ($prefix === '文章') {
$url = 'https://apis.baidu.com/showapi_open_bus/weixin/weixin_article_type';
$ret = $this->httpGetWithKey($url);
$types = $ret['showapi_res_body']['typeList'];
$list = [];
foreach ($types as $t) $list[] = "{$t['id']}、{$t['name']}";
sort($list, SORT_NUMERIC);
$this->replyText(implode("\n", $list));
return;
}
// 2. 查詢文章
if ($prefix === 'wz') {
// 格式:wz19,1,籃球
$parts = explode(',', mb_substr($kw, 2, null, 'UTF-8'));
$typeId = $parts[0]; $page = $parts[1] ?? 1; $key = $parts[2] ?? '';
$url = "https://apis.baidu.com/showapi_open_bus/weixin/weixin_article_list?typeId={$typeId}&page={$page}&key=" . urlencode($key);
$ret = $this->httpGetWithKey($url);
$items = $ret['showapi_res_body']['pagebean']['contentlist'];
$articles = [];
foreach (array_slice($items, 0, 7) as $item) { // 最多 7 條
$articles[] = [
'Title' => $item['title'],
'Description' => $item['title'],
'PicUrl' => $item['contentImg'],
'Url' => $item['url'],
];
}
$this->replyNews($articles);
return;
}
}
// 攜帶 apikey 的 GET
private function httpGetWithKey($url) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_HTTPHEADER => ['apikey: ' . $this->baiduApiKey],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
]);
return json_decode(curl_exec($ch), true);
}
若需完全控制內容、去除廣告、支援自定義分類,建議自建爬蟲/采集系統,存入本地資料庫,介面改為查詢本地表,邏輯不變。