PHP快速推送微信模板消息

原文地址:https://blog.csdn.net/wanlinzan/article/details/70171782

需要给关注用户发送模板消息,由于公众号关注用户比较多,所以采用普通的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

发送模板消息还可以采用curl,甚至是curl的批量处理方式(多线程),但是相对较快的应该是上述方式。**

猜你喜欢

转载自blog.csdn.net/xiaodong_526/article/details/80052785