JPushService.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace services\extend\push;
  3. use Yii;
  4. use common\components\Service;
  5. use common\helpers\FileHelper;
  6. use JPush\Client as JPush;
  7. /**
  8. * Class JPushService
  9. * @package services\extend\push
  10. * @author jianyan74 <751393839@qq.com>
  11. */
  12. class JPushService extends Service
  13. {
  14. /**
  15. * @var \JPush\Client
  16. */
  17. protected $client;
  18. /**
  19. * @return $this
  20. */
  21. public function client($config = [])
  22. {
  23. $logPath = Yii::getAlias('@runtime') . '/logs/j-push/' . date('Y-m') . '/';
  24. FileHelper::mkdirs($logPath);
  25. $this->client = new JPush(
  26. Yii::$app->services->config->backendConfig('push_jpush_appid'),
  27. Yii::$app->services->config->backendConfig('push_jpush_app_secret'),
  28. $logPath . date('d') . '.log'
  29. );
  30. return $this;
  31. }
  32. /**
  33. * @param $title
  34. * @param $content
  35. * @param $clientId
  36. * @param array $transmissionContent
  37. * @throws \yii\base\InvalidConfigException
  38. */
  39. public function send($title, $content, $clientId, $transmissionContent = [])
  40. {
  41. $pusher = $this->client->push();
  42. $pusher->setPlatform($clientId ?? 'all');
  43. $pusher->addAllAudience();
  44. $pusher->setNotificationAlert($title);
  45. try {
  46. $pusher->send();
  47. } catch (\JPush\Exceptions\JPushException $e) {
  48. Yii::$app->services->log->push(500, 'JPush', Yii::$app->services->base->getErrorInfo($e));
  49. }
  50. }
  51. /**
  52. * 推送指定ID
  53. *
  54. * @param string $content 推送内容
  55. * @param array $ids 推送的id
  56. * @param string $info 业务内容
  57. * @param string $title 推送标题 定向的简单推送 不填
  58. * @throws \yii\base\InvalidConfigException
  59. */
  60. public function sendToCourier($content, $ids = [], $info = '', $title = '')
  61. {
  62. try {
  63. $this->client->push()
  64. ->setPlatform(['ios', 'android'])
  65. ->addRegistrationId($ids)
  66. ->iosNotification([
  67. "title" => $title,
  68. "body" => $content
  69. ], [
  70. 'sound' => 'sound.caf',
  71. 'badge' => '+1',
  72. 'content-available' => true,
  73. 'mutable-content' => true,
  74. 'category' => 'jiguang',
  75. 'extras' => [
  76. 'info' => $info,
  77. ],
  78. ])
  79. ->androidNotification($content, [
  80. 'title' => $title,
  81. 'extras' => [
  82. 'info' => $info,
  83. ],
  84. ])
  85. ->options([
  86. // True 表示推送生产环境,False 表示要推送开发环境;如果不指定则默认为推送开发环境
  87. 'apns_production' => false,
  88. ])
  89. ->send();
  90. } catch (\Exception $e) {
  91. Yii::$app->services->log->push(500, 'JPush', Yii::$app->services->base->getErrorInfo($e));
  92. }
  93. }
  94. }
粤ICP备19079148号