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); } }