$ch = curl_init();curl_setopt($ch, CURLOPT_..., $value);$result = curl_exec($ch);curl_close($ch);$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch);
curl_close($ch);
微信公眾平台採用 HTTPS + AJAX 登錄,密碼經 MD5 加密,無驗證碼。關鍵點:
CURLOPT_SSL_VERIFYPEER => false)。Referer 與 Content-Type。token,需解析提取。CURLOPT_COOKIEJAR),後續請求攜帶(CURLOPT_COOKIEFILE)。function wechatLogin($username, $password) {
$password = md5($password); // 密碼預加密
$post = "username={$username}&pwd={$password}&f=json&imgcode=";
$loginUrl = "https://mp.weixin.qq.com/cgi-bin/login?";
$headers = [
'Accept: application/json, text/javascript, */*',
'Content-Type: application/x-www-form-urlencoded',
'Referer: https://mp.weixin.qq.com/'
];
$cookieFile = sys_get_temp_dir() . '/wechat_cookie_' . md5($username) . '.txt';
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $loginUrl,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $post,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_COOKIEJAR => $cookieFile,
CURLOPT_COOKIEFILE => $cookieFile,
CURLOPT_TIMEOUT => 30
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (isset($data['ErrMsg'])) {
// ErrMsg 格式通常為 "redirect_url=xxx&token=yyy"
parse_str($data['ErrMsg'], $params);
return $params['token'] ?? null;
}
return null;
}
// 使用
$token = wechatLogin('your_account', 'your_password');
if ($token) {
echo "登錄成功,Token: $token";
} else {
echo "登錄失敗";
}
| 選項 | 說明 | 典型值 |
|---|---|---|
| CURLOPT_URL | 請求地址 | 字串 |
| CURLOPT_RETURNTRANSFER | 返回字串而非直接輸出 | 1/0 |
| CURLOPT_POST | 啟用 POST | 1 |
| CURLOPT_POSTFIELDS | POST 數據(字串或陣列) | mixed |
| CURLOPT_HTTPHEADER | 自定義請求標頭 | 陣列 |
| CURLOPT_COOKIEJAR | Cookie 保存文件 | 路徑字串 |
| CURLOPT_COOKIEFILE | Cookie 讀取文件 | 路徑字串 |
| CURLOPT_REFERER | 偽裝來源頁面 | URL 字串 |
| CURLOPT_USERAGENT | 瀏覽器標識 | 字串 |
| CURLOPT_TIMEOUT | 最大執行秒數 | 整數 |
| CURLOPT_SSL_VERIFYPEER | 驗證 SSL 證書 | false (開發/測試) |
| CURLOPT_FOLLOWLOCATION | 自動追蹤重定向 | 1 |
| CURLOPT_MAXREDIRS | 最大重定向次數 | 10 |
| CURLOPT_HEADER | 包含響應頭 | 1/0 |
| CURLOPT_CUSTOMREQUEST | 自定義請求方法 | 'DELETE', 'PUT' 等 |
token,後續所有接口請求均需攜帶該 token(通常作為 URL 參數或標頭)。sleep(rand(1,3))。CURLOPT_CAINFO 指定 CA 證書路徑。