api code global jain
This commit is contained in:
89
app/Traits/PushNotificationTraits.php
Normal file
89
app/Traits/PushNotificationTraits.php
Normal file
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace App\Traits;
|
||||
|
||||
use App\Models\Notifications;
|
||||
use Google\Client;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
trait PushNotificationTraits
|
||||
{
|
||||
public function pushNotification($request, $extraFields = [])
|
||||
{
|
||||
$fcmUrl = 'https://fcm.googleapis.com/v1/projects/global-jain-dev/messages:send';
|
||||
$token = $request['userToken'];
|
||||
|
||||
$notification = [
|
||||
"title" => $request['title'],
|
||||
"body" => $request['body'],
|
||||
"image" => $request['image'] ?? ''
|
||||
];
|
||||
$extraNotificationData = ["message" => $request['body']];
|
||||
$data = array_map('strval', array_merge($extraFields, $extraNotificationData));
|
||||
|
||||
$fcmNotification = [
|
||||
"message" => [
|
||||
"token" => $token,
|
||||
"notification" => $notification,
|
||||
"data" => $data
|
||||
]
|
||||
];
|
||||
|
||||
$headers = [
|
||||
'Authorization: Bearer ' . $this->getAccessToken(),
|
||||
'Content-Type: application/json'
|
||||
];
|
||||
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, $fcmUrl);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
|
||||
|
||||
if (curl_exec($ch)) {
|
||||
curl_close($ch);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function storeNotification($request)
|
||||
{
|
||||
$response = [];
|
||||
|
||||
try {
|
||||
$notification = new Notifications();
|
||||
$notification->user_id = $request['user_id'];
|
||||
$notification->message = $request['body'];
|
||||
$notification->extra_fields = $request['extraNotificationData'];
|
||||
$notification->type = $request['type'];
|
||||
$notification->title = $request['title'];
|
||||
$notification->save();
|
||||
|
||||
$response['message'] = trans('auth.notification.update');
|
||||
$response['status'] = 200;
|
||||
|
||||
}catch (\Exception $ex) {
|
||||
Log::error($ex);
|
||||
$response['message'] = trans('auth.something_went_wrong');
|
||||
$response['status'] = 401;
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
/**
|
||||
* Summary of getAccessToken
|
||||
* @return mixed
|
||||
*/
|
||||
public function getAccessToken()
|
||||
{
|
||||
$client = new Client();
|
||||
$client->setAuthConfig(public_path('/.well-known/server_key.json'));
|
||||
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
|
||||
$token = $client->fetchAccessTokenWithAssertion();
|
||||
return $token['access_token'];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user