首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 微信開發:查詢微信精選文章 (百度 API + 分類/關鍵詞/分頁)

     編輯:PHP 綜合知識

功能設計

  • 用戶回覆「文章」 → 返回文章分類列表 (ID + 名稱)。
  • 用戶回覆 `wz{分類ID},{頁碼},{關鍵詞}` → 返回該分類下匹配關鍵詞的文章 (圖文訊息)。

介面對接:百度 API Store (需申請 API Key)

  • 分類介面:`https://apis.baidu.com/showapi_open_bus/weixin/weixin_article_type`
  • 列表介面:`https://apis.baidu.com/showapi_open_bus/weixin/weixin_article_list?typeId={id}&page={page}&key={keyword}`
  • 請求 Header 必須包含 `apikey: YOUR_KEY`。

核心控制器代碼 (ThinkPHP 風格)

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);
}

關鍵點提醒

  1. **API Key 安全**:勿硬編碼,存入配置檔/環境變數。
  2. **編碼處理**:關鍵詞需 `urlencode`,回覆內容確保 UTF-8。
  3. **錯誤容錯**:API 回傳非 0 狀態碼時,友善提示用戶「暫無法獲取」。
  4. **分頁體驗**:可在圖文最後一條加入「回覆 `wz{id},{page+1},{key}` 看更多」。

擴展:自建文章庫

若需完全控制內容、去除廣告、支援自定義分類,建議自建爬蟲/采集系統,存入本地資料庫,介面改為查詢本地表,邏輯不變。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved