PHP快速推送微信模板訊息
阿新 • • 發佈:2019-01-23
需要給關注使用者傳送模板訊息,由於公眾號關注使用者比較多,所以採用普通的curl等方式太慢。由於模板訊息傳送不需要等待微信的結果,所以利用php的fsockopen()函式可以達到快速傳送的效果。程式碼如下:
$data = [
'touser' => '11111111111111111',
'template_id' => '111111111111111111',
'url' => '11111111111111111111',
'data' => [
'first' => [
'value' => '1111111111111111111',
'color' => '#173177',
],
'keyword1' => [
'value' => '111111111111111111',
'color' => '#173177',
],
'keyword2' => [
'value' => date('Y年m月d日 H:i'),
'color' => '#173177' ,
],
'remark' => [
'value' => '1111111111111111111111111',
'color' => '#173177',
]
]
];
$access_token = '此處填寫自己公眾號的access_token';
$params = json_encode($data,JSON_UNESCAPED_UNICODE);
$start_time = microtime(true);
for ($i = 0; $i < 50; $i ++) {
$fp = fsockopen('api.weixin.qq.com', 80, $error, $errstr, 1);
$http = "POST /cgi-bin/message/template/send?access_token={$access_token} HTTP/1.1\r\nHost: api.weixin.qq.com\r\nContent-type: application/x-www-form-urlencoded\r\nContent-Length: " . strlen($params) . "\r\nConnection:close\r\n\r\n$params\r\n\r\n";
fwrite($fp, $http);
fclose($fp);
}
print_r(microtime(true) - $start_time);
上面的程式碼傳送了50條模板訊息,所用時間請看執行結果:
0.83637619018555