PushMessageService.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. if (empty($regId)) {
  32. Utils::throwError(ErrorConst::PUSH_TOKEN_INVALID);
  33. }
  34. // 获取push app信息
  35. $pushAppId = getProp($pushUser, 'app_id');
  36. $pushApp = QappPushApp::getPushAppByAppId($pushAppId);
  37. $package = getProp($pushApp, 'package');
  38. $appId = getProp($pushApp, 'app_id');
  39. $provider = getProp($pushApp, 'provider');
  40. $appSecret = getProp($pushApp, 'app_secret');
  41. $appKey = getProp($pushApp, 'app_key');
  42. $masterSecret = getProp($pushApp, 'master_secret');
  43. $result = [];
  44. try {
  45. switch ($provider) {
  46. // 华为
  47. case PushConst::PROVIDER_HW:
  48. // 初始化huawei推送
  49. $client = new HwPushCommon($appId, $appSecret);
  50. // 循环推送
  51. $client->setToken($regIdList);
  52. $result = $client->sendPushMessage($title, $content, $url);
  53. break;
  54. // 小米
  55. case PushConst::PROVIDER_MI:
  56. // 初始化小米推送
  57. $client = new MiPushCommon($package, $appSecret);
  58. // 循环推送
  59. $client->setRegArr($regIdList);
  60. $result = $client->sendMessage($title, $content, $url);
  61. break;
  62. // OPPO
  63. case PushConst::PROVIDER_OPPO:
  64. // 初始化oppo推送
  65. $client = new OPPOPushCommon($appKey, $masterSecret);
  66. $messageId = $client->getMessageId($title, $content, $url);
  67. // 循环推送
  68. $client->setRegArr($regIdList);
  69. $result = $client->broadCastRegIds($messageId);
  70. break;
  71. }
  72. } catch (Exception $e) {
  73. $message = $e->getMessage();
  74. myLog('push')->info('Exception', compact('result', 'message'));
  75. Utils::throwError(ErrorConst::PUSH_FAIELD);
  76. }
  77. return $result;
  78. }
  79. }