准备工作:
目前最简单最好用的微信推送方式。
企业微信注册免费https://work.weixin.qq.com
注册后,创建个群,然后添加机器人进去,取到webhook地址,然后按文档POST提交要提醒的数据就行了。
官方文档
- https://developer.work.weixin.qq.com/document/path/99110
查询余额达到设定的阈值后微信通知。
- function sendCurlRequest($url, $headers, $data) {
-
- $ch= curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
- curl_setopt($ch, CURLOPT_POST, true);
- $response = curl_exec($ch);
- curl_close($ch);
- return $response;
- }
-
- $apiKey = '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';
- $headers = array( 'Authorization: Bearer ' . $apiKey, 'Content-Type: application/json');
- $url = "https://api.openai.com/v1/dashboard/billing/usage?start_date=".date('Y-m-01')."&end_date=".date('Y-m-t');
- $response = sendCurlRequest($url, $headers, $data);
- $max_usage =100;//通知触发阈值
- if(strstr($response,'error')){
- echo "invalid_api_key";}else{
- $cost_data=json_decode($response);
- $total_usage=round($cost_data->total_usage/100,2);
- }
- if( $total_usage>$max_usage){
- $url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=693axxx6-7aoc-4bc4-97a0-0ec2sifa5aaa';
- $headers = array('Content-Type: application/json');
- $data = array("msgtype" => "text", "text" => array("content" => "余额不足","mentioned_list" => array("mjj","@all")));
- $response = sendCurlRequest($url, $headers, $data);
- echo "余额不足";
- }
说明:保存为notify.php,每小时访问一次,mentioned_list为通知的微信ID列表。
-
- 使用以下命令编辑cron任务列表:
-
- crontab -e
- 在打开的文件中,添加以下行来设置每小时执行的cron任务:
-
- 0 * * * * curl http://127.0.0.1/notify.php