thinkphp5实现微信公众号模板消息发送

最近想做一个微信消息提示

之前刚好自己申请过一个测试号

于是开始编码

```
setName('runHint')->setDescription("计划任务 runHint");
}
//调用SendMessage 这个类时,会自动运行execute方法
protected function execute(Input $input, Output $output){
$output->writeln('Date Crontab job start...');
$this->run();//执行任务
$output->writeln('Date Crontab job end...');
}
public function run()
{
//查单
$order_num = DB::name('goods_order')->where('goods_id',1)->count();
echo $order_num;
if($order_num >= 8){
$access_token = Cache::store('redis')->get('access_token');
if(!$access_token){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=*******&secret=******";
$content = json_decode(file_get_contents($url),true);
print_r($content);
$access_token = $content['access_token'];
Cache::store('redis')->set('access_token',$access_token,3600);
}
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$access_token";
$data = [
"touser"=>"o7qRAs_Y1a1Weitn10DaKTeWGRhk",
//"template_id"=>"ycdMZ0I91d8pWGxfobagfTFvPeSfNFtevmeOT1S2RPk",
"template_id"=>"1vBVzfj9p7XaXqCM-S0EV5REQfbfrbPiwSvfKcPaJwo",
"url"=>"http://m.baidu.com",
"topcolor"=>"#FF0000",
"data"=>
[
"OrderNum"=>[
"value"=>$order_num,
"color"=>"#00ff00"
],
"SendTime"=>[
"value"=>date("Y-m-d H:i:s"),
"color"=>"#173177"
],
]
];
//print_r($data);
$json_data = json_encode($data);
print_R($json_data);
$result = curl ( $url, $json_data, "POST" );
print_r($result);
}
}

function curl($url, $postDate = "", $method = "PUT") {
$ci = curl_init ();
$headers = array(
"Content-type: application/json;charset='utf-8'",
"Accept: application/json",
"Cache-Control: no-cache",
"Pragma: no-cache",
);
curl_setopt ( $ci, CURLOPT_URL, $url );
curl_setopt ( $ci, CURLOPT_PORT, 443 );
curl_setopt ( $ci, CURLOPT_TIMEOUT, 200 );
curl_setopt ( $ci, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ci, CURLOPT_FORBID_REUSE, 0 );
curl_setopt ( $ci, CURLOPT_CUSTOMREQUEST, $method );
curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
if ($postDate) {
curl_setopt ( $ci, CURLOPT_POSTFIELDS, $postDate );
}
$response = curl_exec ( $ci );
return $response;
}
}
```

加入crontab每分钟执行一次即可给自己推送微信消息

模板内容为

```
已经有{{OrderNum.DATA}}人下单了{{SendTime.DATA}}
```

    A+
发布日期:2022年02月02日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: