微信公眾平台官方並未提供直接的「主動推送」API(僅有客服消息 48 小時限制)。本文採用「模擬登入 Web 端」的曲線方案:先模擬登入獲取 Cookie 與 Token,再調用內部發送接口實現單發/群發。
⚠️ 風險提示:此屬逆向工程非官方接口,微信隨時可能變更參數或封禁 IP,生產環境請謹慎評估。
封裝為一個類,主要屬性:_account、_password、cookie、token、userFakeid(粉絲列表)。
login())https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CNusername、pwd=md5(password)、f=jsonErrCode 判斷錯誤(-2 帳號密碼錯誤、-6 需驗證碼等),set-cookie 獲取 Cookie,ErrMsg 獲取 TokengetUserFakeid() 緩存所有粉絲 fakeidprivate 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('全體廣播測試');