course/app/common/service/WechatSubscriptService.php
2024-09-13 22:18:32 +08:00

58 lines
1.5 KiB
PHP

<?php
namespace app\common\service;
use app\constant\ResponseCode;
use app\utils\WechatUtil;
use GuzzleHttp\Client;
use support\Cache;
use think\Exception;
/**
* 微信公众号
*/
class WechatSubscriptService
{
const SUBSCRIPT_ACCESS_TOKEN = 'subscript_access_token';
protected $client;
public function __construct()
{
$this->client = new Client(['base_uri' => 'https://api.weixin.qq.com']);
}
/**
* @desc 发送公众号消息
* @param $send_data
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function sendMsg($send_data)
{
try {
$access_token = WechatUtil::getAccessToken();
if(isset($access_token['code'])){
throw new Exception('获取access_token失败');
}
$result = $this->client->request('post', 'cgi-bin/message/template/send?access_token=' . $access_token, [
'json' => $send_data,
]);
$result = json_decode($result->getBody()->getContents(), true);
raw_log('wechat/send_msg', ['send_data'=>$send_data, 'result'=>$result]);
if(isset($result['errcode']) && $result['errcode'] != 0){
throw new Exception($result['errmsg']);
}
return [
'code' => ResponseCode::SUCCESS,
'msg'=> $result['errmsg']
];
}catch (Exception $e){
return [
'code' => ResponseCode::FAIL,
'msg' => $e->getMessage()
];
}
}
}