123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- <?php
- namespace App\Services;
- use EasyWeChat\Factory;
- use Illuminate\Support\Facades\Log;
- class WechatNotificationService
- {
- protected $app;
- public function __construct()
- {
- $this->app = app('wechat.official_account');
- }
-
- public function sendTemplateMessage(
- string $openid,
- string $templateId,
- array $data,
- ?string $url = null,
- ?array $miniprogram = null
- ): array {
- try {
- $message = [
- 'touser' => $openid,
- 'template_id' => $templateId,
- 'data' => $data,
- ];
-
- if ($url) {
- $message['url'] = $url;
- }
-
- if ($miniprogram) {
- $message['miniprogram'] = $miniprogram;
- }
- $result = $this->app->template_message->send($message);
- if ($result['errcode'] === 0) {
- Log::info('微信模板消息发送成功', [
- 'openid' => $openid,
- 'template_id' => $templateId,
- 'data' => $data,
- ]);
- return [
- 'success' => true,
- 'message' => '发送成功',
- ];
- }
- Log::error('微信模板消息发送失败', [
- 'openid' => $openid,
- 'template_id' => $templateId,
- 'data' => $data,
- 'error' => $result['errmsg'],
- ]);
- return [
- 'success' => false,
- 'message' => $result['errmsg'],
- ];
- } catch (\Exception $e) {
- Log::error('微信模板消息发送异常', [
- 'openid' => $openid,
- 'template_id' => $templateId,
- 'data' => $data,
- 'error' => $e->getMessage(),
- ]);
- return [
- 'success' => false,
- 'message' => '发送失败:' . $e->getMessage(),
- ];
- }
- }
-
- public function sendOrderStatusNotification(string $openid, array $orderInfo): array
- {
- $templateId = env('WECHAT_ORDER_STATUS_TEMPLATE_ID');
- $data = [
- 'first' => ['value' => '您的订单状态有更新'],
- 'keyword1' => ['value' => $orderInfo['order_no']],
- 'keyword2' => ['value' => $orderInfo['status']],
- 'keyword3' => ['value' => $orderInfo['time']],
- 'remark' => ['value' => '感谢您的使用!'],
- ];
- return $this->sendTemplateMessage($openid, $templateId, $data);
- }
- }
|