|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Kawankoding\Fcm; |
| 4 | + |
| 5 | +/** |
| 6 | + * Class Fcm |
| 7 | + * @package Kawankoding\Fcm |
| 8 | + */ |
| 9 | +class Fcm |
| 10 | +{ |
| 11 | + protected $recipient; |
| 12 | + protected $data; |
| 13 | + protected $notification; |
| 14 | + |
| 15 | + public function to($recipient) |
| 16 | + { |
| 17 | + $this->recipient = $recipient; |
| 18 | + |
| 19 | + return $this; |
| 20 | + } |
| 21 | + |
| 22 | + public function data(array $data = []) |
| 23 | + { |
| 24 | + $this->data = $data; |
| 25 | + |
| 26 | + return $this; |
| 27 | + } |
| 28 | + |
| 29 | + public function notification(array $notification = []) |
| 30 | + { |
| 31 | + $this->notification = $notification; |
| 32 | + |
| 33 | + return $this; |
| 34 | + } |
| 35 | + |
| 36 | + public function push() |
| 37 | + { |
| 38 | + $fcmEndpoint = 'https://fcm.googleapis.com/fcm/send'; |
| 39 | + |
| 40 | + $fields = [ |
| 41 | + 'registration_ids' => $this->recipient, |
| 42 | + 'content-available' => true, |
| 43 | + 'priority' => 'high', |
| 44 | + 'data' => $this->data, |
| 45 | + 'notification' => $this->notification |
| 46 | + ]; |
| 47 | + |
| 48 | + $serverKey = config('laravel-fcm.server-key'); |
| 49 | + |
| 50 | + $headers = [ |
| 51 | + 'Authorization:key='.$serverKey, |
| 52 | + 'Content-Type:application/json' |
| 53 | + ]; |
| 54 | + |
| 55 | + $ch = curl_init(); |
| 56 | + curl_setopt($ch, CURLOPT_URL, $fcmEndpoint); |
| 57 | + curl_setopt($ch, CURLOPT_POST, true); |
| 58 | + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); |
| 59 | + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
| 60 | + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, CURL_IPRESOLVE_V4); |
| 61 | + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); |
| 62 | + $result = curl_exec($ch); |
| 63 | + |
| 64 | + curl_close($ch); |
| 65 | + } |
| 66 | +} |
0 commit comments