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

PHP 模擬登入實現微信公眾號主動推送消息

     編輯:PHP 綜合知識

方案概述

微信公眾平台官方並未提供直接的「主動推送」API(僅有客服消息 48 小時限制)。本文採用「模擬登入 Web 端」的曲線方案:先模擬登入獲取 Cookie 與 Token,再調用內部發送接口實現單發/群發。

⚠️ 風險提示:此屬逆向工程非官方接口,微信隨時可能變更參數或封禁 IP,生產環境請謹慎評估。

核心類結構

封裝為一個類,主要屬性:_account、_password、cookie、token、userFakeid(粉絲列表)。

一、登入接口(login())

  • POST https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN
  • 表單:username、pwd=md5(password)、f=json
  • 解析回應:ErrCode 判斷錯誤(-2 帳號密碼錯誤、-6 需驗證碼等),set-cookie 獲取 Cookie,ErrMsg 獲取 Token
  • 登入成功後調用 getUserFakeid() 緩存所有粉絲 fakeid
private function login(){
    $url = 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN';
    $this->send_data = [
        'username' => $this->_account,
        'pwd'      => md5($this->_password),
        'f'        => 'json'
    ];
    $this->referer = 'https://mp.weixin.qq.com/';
    $this->getHeader = 1;
    $result = explode("\n", $this->curlPost($url));
    foreach ($result as $value) {
        $value = trim($value);
        if (preg_match('/"ErrCode": (.*)/i', $value, $match)) {
            // 根據 ErrCode 判斷錯誤類型,見代碼完整 switch
        }
        if (preg_match('/^set-cookie:[\s]+([^=]+)=([^;]+)/i', $value, $match)) {
            $this->cookie .= $match[1].'='.$match[2].'; ';
        }
        if (preg_match('/"ErrMsg"/i', $value, $match)) {
            $this->token = rtrim(substr($value, strrpos($value, '=')+1), '",');
        }
    }
}

二、單發消息(send())

private function send($fakeid, $content){
    $url = 'https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&lang=zh_CN';
    $this->send_data = [
        'type'     => 1,
        'content'  => $content,
        'error'    => 'false',
        'tofakeid' => $fakeid,
        'token'    => $this->token,
        'ajax'     => 1
    ];
    $this->referer = "https://mp.weixin.qq.com/cgi-bin/singlemsgpage?token={$this->token}&fromfakeid={$fakeid}&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN";
    return $this->curlPost($url);
}

三、群發消息(sendMessage())

遍歷 $this->userFakeid 或指定 $userId 陣列,逐個調用 send(),統計成功/失敗數並返回 JSON。

public function sendMessage($content='', $userId=''){
    // ... 遍歷發送邏輯,詳見原文完整代碼
    return json_encode($data); // 含 status, count, succeCount, errCount, errUser
}

四、獲取粉絲列表(getUserFakeid())

  • 先請求群組列表 /cgi-bin/contactmanage?t=user/index&groupid=0
  • 對每個群組再請求成員 /cgi-bin/contactmanage?t=user/index&groupid={$gid}
  • 正則提取 id 與 nick_name 組合成 ['fakeid'=>..., 'groupid'=>...]

五、完整調用範例

$wx = new WeChatPusher('admin@example.com', 'password123');
$wx->login();
// 單發
$wx->send('oFakeId123', '你好,這是測試消息');
// 群發
$wx->sendMessage('全體廣播測試');

總結與建議

  1. 此方案適合內部工具、測試環境,不建議用於核心業務。
  2. 官方正規途徑:使用「客服消息」(48h 內)或「模板消息」(需審核),穩定且合規。
  3. 若必須用模擬登入,請做好異常重試、IP 池輪換、日誌監控。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved