2024-08-04 22:28:52 +08:00
|
|
|
<?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)
|
|
|
|
{
|
2024-08-04 23:31:50 +08:00
|
|
|
try {
|
|
|
|
$access_token = WechatUtil::getAccessToken();
|
2024-09-13 22:18:32 +08:00
|
|
|
if(isset($access_token['code'])){
|
|
|
|
throw new Exception('获取access_token失败');
|
|
|
|
}
|
2024-08-04 23:31:50 +08:00
|
|
|
$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()
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
2024-08-04 22:28:52 +08:00
|
|
|
}
|
|
|
|
}
|