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');
- }
- /**
- * 发送模板消息
- *
- *
- * @param string $openid 接收者openid
- * @param string $templateId 模板ID
- * @param array $data 模板数据
- * @param string|null $url 点击跳转链接
- * @param array|null $miniprogram 跳小程序配置
- * @return array
- */
- 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(),
- ];
- }
- }
- /**
- * 发送订单状态变更通知
- *
- * $result = $this->wechatService->sendOrderStatusNotification(
- * $order->user->wechat_openid,
- * [
- * 'order_no' => $order->order_no,
- * 'status' => $order->status_text,
- * 'time' => now()->format('Y-m-d H:i:s')
- * ]
- * );
- *
- * @param string $openid
- * @param array $orderInfo
- * @return array
- */
- 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);
- }
- }
|