MarketingController.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\Marketing;
  5. use DB;
  6. use Exception;
  7. use Http;
  8. use Illuminate\Http\Request;
  9. use Log;
  10. use Response;
  11. use RuntimeException;
  12. class MarketingController extends Controller
  13. {
  14. // 邮件群发消息列表
  15. public function emailList(Request $request)
  16. {
  17. $status = $request->input('status');
  18. $query = Marketing::whereType(1);
  19. if (isset($status)) {
  20. $query->whereStatus($status);
  21. }
  22. return view('admin.marketing.emailList', ['emails' => $query->paginate(15)->appends($request->except('page'))]);
  23. }
  24. // 消息通道群发列表
  25. public function pushList(Request $request)
  26. {
  27. $status = $request->input('status');
  28. $query = Marketing::whereType(2);
  29. if (isset($status)) {
  30. $query->whereStatus($status);
  31. }
  32. return view('admin.marketing.pushList', ['pushes' => $query->paginate(15)->appends($request->except('page'))]);
  33. }
  34. // 添加推送消息
  35. public function addPushMarketing(Request $request)
  36. {
  37. $title = $request->input('title');
  38. $content = $request->input('content');
  39. if (! sysConfig('is_push_bear')) {
  40. return Response::json(['status' => 'fail', 'message' => '推送失败:请先启用并配置PushBear']);
  41. }
  42. try {
  43. DB::beginTransaction();
  44. $response = Http::timeout(15)->get('https://pushbear.ftqq.com/sub', [
  45. 'sendkey' => sysConfig('push_bear_send_key'),
  46. 'text' => $title,
  47. 'desp' => $content,
  48. ]);
  49. $message = $response->json();
  50. if (! $message || ! $message['code'] === 0 || $response->failed()) { // 失败
  51. $this->addMarketing(2, $title, $content, -1, $message['message']);
  52. throw new RuntimeException($message['message']);
  53. }
  54. $this->addMarketing(2, $title, $content);
  55. DB::commit();
  56. return Response::json(['status' => 'success', 'message' => '推送成功']);
  57. } catch (Exception $e) {
  58. Log::error('PushBear消息推送失败:'.$e->getMessage());
  59. DB::rollBack();
  60. return Response::json(['status' => 'fail', 'message' => '推送失败:'.$e->getMessage()]);
  61. }
  62. }
  63. private function addMarketing($type = 1, $title = '', $content = '', $status = 1, $error = '', $receiver = ''): bool
  64. {
  65. $marketing = new Marketing();
  66. $marketing->type = $type;
  67. $marketing->receiver = $receiver;
  68. $marketing->title = $title;
  69. $marketing->content = $content;
  70. $marketing->error = $error;
  71. $marketing->status = $status;
  72. return $marketing->save();
  73. }
  74. }