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

PHP cURL 模擬登錄微信公眾平台與新浪微博實戰代碼

     編輯:PHP 綜合知識

前言

部分平台未提供開放 API 或 API 受限,需通過模擬登錄獲取數據。本文提供微信公眾平台、新浪微博兩個經典模擬登錄案例,並分析反爬蟲對策與現代化替代方案。注意: 模擬登錄屬灰色地帶,請遵守平台服務條款,優先使用官方 API。

案例一:微信公眾平台 (mp.weixin.qq.com)

核心流程

  1. POST /cgi-bin/login 提交帳號 + MD5 密碼 + 驗證碼(可選)
  2. 解析 JSON 返回的 redirect_url
  3. 攜帶 Cookie 訪問重定向 URL 進入後台

完整代碼

function wechat_login(string $username, string $password): ?string {
    $cookieFile = sys_get_temp_dir() . '/wechat_' . md5($username) . '.cookie';
    $loginUrl = 'https://mp.weixin.qq.com/cgi-bin/login';
    $postData = [
        'username' => $username,
        'pwd' => md5($password),
        'f' => 'json',
        'imgcode' => '', // 若觸發驗證碼需額外處理
    ];
    $ch = curl_init($loginUrl);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($postData),
        CURLOPT_COOKIEJAR => $cookieFile,
        CURLOPT_COOKIEFILE => $cookieFile,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false, // 僅測試環境,生產請配置 CA
        CURLOPT_REFERER => 'https://mp.weixin.qq.com/',
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    ]);
    $resp = json_decode(curl_exec($ch), true);
    curl_close($ch);
    if (empty($resp['redirect_url'])) {
        error_log('微信登錄失敗: ' . json_encode($resp, JSON_UNESCAPED_UNICODE));
        return null;
    }
    // 進入後台首頁
    $ch = curl_init('https://mp.weixin.qq.com' . $resp['redirect_url']);
    curl_setopt_array($ch, [
        CURLOPT_COOKIEFILE => $cookieFile,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $content = curl_exec($ch);
    curl_close($ch);
    return $content; // 返回後台 HTML
}

關鍵點提示

  • 密碼採用 MD5(明文),非標準加密,可能隨時變更。
  • 高頻登錄會觸發 圖形驗證碼 / 短信驗證碼 / 設備鎖,需接入打碼平台或人工干預。
  • Cookie 有效期較短,建議登錄成功後持久化 Cookie 文件,後續請求直接載入 CURLOPT_COOKIEFILE。

案例二:新浪微博 (weibo.com) — 預登錄 + RSA 加密流程

新浪採用 預登錄接口獲取 servertime/nonce/pubkey,然後用 RSA 加密密碼,防止明文傳輸與重放攻擊。

簡化版核心邏輯

class SinaWeiboSimulator {
    private $cookieFile;
    private $ch;

    public function __construct(string $username, string $password) {
        $this->cookieFile = sys_get_temp_dir() . '/sina_' . md5($username) . '.cookie';
        $this->login($username, $password);
    }

    private function http(string $url, array $post = null): string {
        $this->ch = curl_init($url);
        curl_setopt_array($this->ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_COOKIEJAR => $this->cookieFile,
            CURLOPT_COOKIEFILE => $this->cookieFile,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        ]);
        if ($post) {
            curl_setopt($this->ch, CURLOPT_POST, true);
            curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($post));
        }
        return curl_exec($this->ch);
    }

    private function login(string $su, string $sp) {
        // 1. 預登錄獲取 servertime, nonce, pubkey, rsakv
        $suEnc = urlencode(base64_encode($su));
        $prelogin = json_decode($this->http("https://login.sina.com.cn/sso/prelogin.php?entry=weibo&su=$suEnc&rsakt=mod&client=ssologin.js&_=" . time() * 1000), true);
        // 2. RSA 加密密碼 (需 phpseclib 或 openssl)
        // $sp = rsa_encrypt($sp, $prelogin['pubkey'], $prelogin['servertime'], $prelogin['nonce']);
        // 3. 提交登錄
        $post = [
            'su' => $suEnc,
            'service' => 'miniblog',
            'servertime' => $prelogin['servertime'],
            'nonce' => $prelogin['nonce'],
            'pwencode' => 'rsa2',
            'sp' => $sp,
            'encoding' => 'UTF-8',
            'url' => 'https://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
            'returntype' => 'META',
        ];
        $resp = $this->http('https://login.sina.com.cn/sso/login.php?client=ssologin.js', $post);
        // 4. 解析重定向 URL,完成二次跳轉設置 Cookie
        if (preg_match('/location\.replace\([\'"]([^\'"]+)[\'"]\)/', $resp, $m)) {
            $this->http($m[1]);
        }
    }

    public function get(string $url): string {
        return $this->http($url);
    }

    public function __destruct() {
        if ($this->ch) curl_close($this->ch);
    }
}

// 使用
$wb = new SinaWeiboSimulator('your_account', 'your_password');
$home = $wb->get('https://weibo.com/');
echo $home;

關鍵難點:RSA 加密

PHP 端需實現與 JS 端一致的 RSA 加密(sp = sha1(sha1(pass)) + servertime + nonce 再 RSA),建議使用 phpseclib/phpseclib 库:

use phpseclib3\Crypt\RSA;
$rsa = new RSA();
$rsa->loadKey('-----BEGIN PUBLIC KEY-----' . $pubkey . '-----END PUBLIC KEY-----');
$rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
$sp = $rsa->encrypt($sp);

反爬蟲對策與穩健性建議

風險應對
IP 封禁/限流代理池輪換、指數退避重試、分佈式調度
設備指紋識別固定 User-Agent、Canvas 指紋、Header 順序一致性
驗證碼/設備鎖打碼平台 API、人工介入隊列、Cookie 池預熱
前端加密算法變更定期對比登錄頁 JS,維護加密庫版本
法律/合規風險優先使用官方 API、簽訂數據協議、遵守 robots.txt

現代化替代方案

  1. 官方 API: 微信公眾平台開放接口、微博開放平台 OAuth 2.0,功能完整且合規。
  2. Headless 瀏覽器: Puppeteer / Playwright / Selenium 驅動真實 Chrome,自動執行 JS 加密、繞過指紋檢測,維護成本低於手寫 cURL。
  3. 現成庫: wechat/wechat-sdk、overtrue/wechat、guzzlehttp/guzzle + Cookie 插件。

總結

cURL 模擬登錄適合快速驗證、低頻數據抓取、無官方 API 場景。生產系統請優先選擇官方 API 或 Headless 瀏覽器方案,將脆弱的模擬登錄邏輯隔離在可替換的適配器層,降低平台變更帶來的業務風險。

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