PushMessageService.php 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace App\Modules\Push\Services;
  3. use App\Consts\ErrorConst;
  4. use App\Consts\PushConst;
  5. use App\Libs\Push\HuaWei\HwPushCommon;
  6. use App\Libs\Push\OPPOPush\OPPOPushCommon;
  7. use App\Libs\Push\XMPush\MiPushCommon;
  8. use App\Libs\Utils;
  9. use App\Modules\Push\Models\QappPushApp;
  10. use App\Modules\Push\Models\QappPushUser;
  11. use Exception;
  12. use GuzzleHttp\Exception\GuzzleException;
  13. use App\Exceptions\ApiException;
  14. class PushMessageService
  15. {
  16. /**
  17. * @param $uid
  18. * @param $title
  19. * @param $content
  20. * @param $url
  21. * @return array|bool|mixed|string|null
  22. * @throws ApiException
  23. * @throws GuzzleException
  24. */
  25. public static function pushMessageToUser($uid, $title, $content, $url)
  26. {
  27. // 获取用户push信息
  28. $pushUser = QappPushUser::getPushUserByUid($uid);
  29. $regId = getProp($pushUser, 'reg_id');
  30. $regIdList = [$regId];
  31. myLog('push')->info('pushMessageToUser', compact('uid', 'title', 'content', 'url', 'pushUser'));
  32. if (empty($regId)) {
  33. Utils::throwError(ErrorConst::PUSH_TOKEN_INVALID);
  34. }
  35. // 获取push app信息
  36. $pushAppId = getProp($pushUser, 'app_id');
  37. $pushApp = QappPushApp::getPushAppByAppId($pushAppId);
  38. $package = getProp($pushApp, 'package');
  39. $appId = getProp($pushApp, 'app_id');
  40. $provider = getProp($pushApp, 'provider');
  41. $appSecret = getProp($pushApp, 'app_secret');
  42. $appKey = getProp($pushApp, 'app_key');
  43. $masterSecret = getProp($pushApp, 'master_secret');
  44. $result = [];
  45. try {
  46. switch ($provider) {
  47. // 华为
  48. case PushConst::PROVIDER_HW:
  49. // 初始化huawei推送
  50. $client = new HwPushCommon($appId, $appSecret);
  51. // 循环推送
  52. $client->setToken($regIdList);
  53. $result = $client->sendPushMessage($title, $content, $url);
  54. break;
  55. // 小米
  56. case PushConst::PROVIDER_MI:
  57. // 初始化小米推送
  58. $client = new MiPushCommon($package, $appSecret);
  59. // 循环推送
  60. $client->setRegArr($regIdList);
  61. $result = $client->sendMessage($title, $content, $url);
  62. break;
  63. // OPPO
  64. case PushConst::PROVIDER_OPPO:
  65. // 初始化oppo推送
  66. $client = new OPPOPushCommon($appKey, $masterSecret);
  67. $messageId = $client->getMessageId($title, $content, $url);
  68. // 循环推送
  69. $client->setRegArr($regIdList);
  70. $result = $client->broadCastRegIds($messageId);
  71. break;
  72. }
  73. } catch (Exception $e) {
  74. $message = $e->getMessage();
  75. myLog('push')->info('Exception', compact('result', 'message'));
  76. Utils::throwError(ErrorConst::PUSH_FAIELD);
  77. }
  78. return $result;
  79. }
  80. }