You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

116 lines
2.9 KiB

  1. <?php
  2. namespace App\Channels;
  3. use App\Channels\Messages\SmsMessage;
  4. use Illuminate\Notifications\Notification;
  5. use GuzzleHttp\Client as HttpClient;
  6. class SmsChannel
  7. {
  8. /**
  9. * The API URL for Socket.
  10. *
  11. * @var string
  12. */
  13. protected $sms_url;
  14. /**
  15. * The HTTP client instance.
  16. *
  17. * @var \GuzzleHttp\Client
  18. */
  19. protected $http;
  20. /**
  21. * Create a new Socket channel instance.
  22. *
  23. * @param \GuzzleHttp\Client $http
  24. * @return void
  25. */
  26. public function __construct(HttpClient $http, string $sms_url)
  27. {
  28. $this->http = $http;
  29. $this->sms_url = $sms_url;
  30. }
  31. /**
  32. * Send the given notification.
  33. *
  34. * @param mixed $notifiable
  35. * @param \Illuminate\Notifications\Notification $notification
  36. * @return void
  37. */
  38. public function send($notifiable, Notification $notification)
  39. {
  40. $message = $notification->toSms($notifiable);
  41. $type = $notification->getType();
  42. $message->to($notifiable->routeNotificationFor('sms', $notification));
  43. if (! $message->to || ! ($message->params && $message->template_id) || ! $message->verification_code) {
  44. return;
  45. }
  46. try {
  47. $this->http->post($this->sms_url . 'api/' . $type , [
  48. 'headers' => [
  49. 'x-sms-ir-secure-token'=> $this->getToken()
  50. ],
  51. 'connect_timeout' => 30,
  52. 'json' => $this->buildJsonPayload($message, $type),
  53. ]);
  54. } catch (\GuzzleHttp\Exception\ConnectException $e) {
  55. report($e);
  56. }
  57. }
  58. /**
  59. * This method used in every request to get the token at first.
  60. *
  61. * @return mixed - the Token for use api
  62. */
  63. protected function getToken()
  64. {
  65. $body = [
  66. 'UserApiKey' => config('smsirlaravel.api-key'),
  67. 'SecretKey' => config('smsirlaravel.secret-key'),
  68. 'System' => 'laravel_v_1_4'
  69. ];
  70. try {
  71. $result = $this->http->post( $this->sms_url . 'api/Token',['json'=>$body,'connect_timeout'=>30]);
  72. } catch (\GuzzleHttp\Exception\ConnectException $e) {
  73. report($e);
  74. return;
  75. }
  76. return json_decode($result->getBody(),true)['TokenKey'];
  77. }
  78. /**
  79. * Create sms json payload based on type
  80. *
  81. * @param SmsMessage $message
  82. * @param $type
  83. * @return array
  84. */
  85. protected function buildJsonPayload(SmsMessage $message, $type) {
  86. if ($type === 'UltraFastSend') {
  87. return[
  88. 'ParameterArray' => $message->params,
  89. 'TemplateId' => $message->template_id,
  90. 'Mobile' => $message->to
  91. ];
  92. }
  93. if ($type === 'VerificationCode') {
  94. return[
  95. 'Code' => $message->data,
  96. 'MobileNumber' => $message->to
  97. ];
  98. }
  99. }
  100. }