Skip to content

Commit

Permalink
updated
Browse files Browse the repository at this point in the history
  • Loading branch information
Esca6585 committed Dec 28, 2023
1 parent 125ac26 commit 062e493
Show file tree
Hide file tree
Showing 10 changed files with 187 additions and 13 deletions.
5 changes: 5 additions & 0 deletions app/Http/Controllers/Admin/Api/AdminController.php
Original file line number Diff line number Diff line change
Expand Up @@ -283,4 +283,9 @@ public function deleteFolder($tarif)
}
}
}

public function sendNotification(Request $request)
{
return $request;
}
}
2 changes: 1 addition & 1 deletion app/Http/Controllers/HomeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class HomeController extends Controller
*/
public function __construct()
{
$this->middleware(['auth','verified']);
// $this->middleware(['auth','verified']);
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace App\Http\Controllers\User\Notification;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Auth;

class NotificationSendController extends Controller
{
public function updateDeviceToken(Request $request)
{
Auth::user()->device_token = $request->token;

Auth::user()->save();

return response()->json([
'status' => true,
]);
}

public function sendNotification(Request $request)
{
$url = 'https://fcm.googleapis.com/fcm/send';

$FcmToken = User::whereNotNull('device_token')->pluck('device_token')->all();

$serverKey = 'AAAANPt3SJI:APA91bF_gxrIoSlxH6j544E_ZeX71fGd4qgyKuyXN72l44ok_FdxDU32gMK6vLMZoMs0W0cufeS_gJ6O1JwaF5X-aRx8l7fPbIs5KfphbSX6x7-VK-d4wjG8qQ_q3hnh-2eSjLhHI0cu'; // Add Server Key Here Provided By FCM

$data = [
"registration_ids" => $FcmToken,
"notification" => [
"title" => $request->title,
"body" => $request->body,
]
];
$encodedData = json_encode($data);

$headers = [
'Authorization:key=' . $serverKey,
'Content-Type: application/json',
];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTP_VERSION, true);
// Disabling SSL: Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedData);
// Execute post
$result = curl_exec($ch);
if($result === FALSE){
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
// FCM response
dd($result);
}
}
1 change: 1 addition & 0 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class User extends Authenticatable implements MustVerifyEmail
'password',
'status',
'online',
'device_token',
];

/**
Expand Down
2 changes: 2 additions & 0 deletions database/migrations/2019_12_14_000000_create_users_table.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ public function up()
$table->boolean('status');
$table->boolean('online')->default(0);
$table->string('time')->default(0);

$table->text('device_token')->nullable(); // Add device token in users migration file

$table->rememberToken();
$table->timestamps();
Expand Down
32 changes: 32 additions & 0 deletions public/firebase-messaging-sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-messaging.js');
/*
Initialize the Firebase app in the service worker by passing in the messagingSenderId.
*/
firebase.initializeApp({
apiKey: "AIzaSyCb4-gYuRCchkACI-z-H0N3BGZSVE1OPTw",
authDomain: "magnetic-lore-322008.firebaseapp.com",
projectId: "magnetic-lore-322008",
storageBucket: "magnetic-lore-322008.appspot.com",
messagingSenderId: "227557197970",
appId: "1:227557197970:web:aad3453997eb67a7073e4b"
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log("Message received.", payload);
const title = "Hello world is awesome";
const options = {
body: "Your notificaiton message .",
icon: "/firebase-logo.png",
};
return self.registration.showNotification(
title,
options,
);
});
83 changes: 73 additions & 10 deletions resources/views/home.blade.php
Original file line number Diff line number Diff line change
@@ -1,23 +1,86 @@
@extends('layouts.app')

@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dashboard') }}</div>

<button onclick="startFCM()"
class="btn btn-danger btn-flat">Allow notification
</button>
<div class="card mt-3">
<div class="card-body">
@if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
@endif

{{ __('You are logged in!') }}
<form action="{{ route('send.web-notification', app()->getlocale() ) }}" method="POST">
@csrf
<div class="form-group">
<label>Message Title</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label>Message Body</label>
<textarea class="form-control" name="body"></textarea>
</div>
<button type="submit" class="btn btn-success btn-block">Send Notification</button>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.3.2/firebase.js"></script>
<script>
var firebaseConfig = {
apiKey: "AIzaSyCb4-gYuRCchkACI-z-H0N3BGZSVE1OPTw",
authDomain: "magnetic-lore-322008.firebaseapp.com",
projectId: "magnetic-lore-322008",
storageBucket: "magnetic-lore-322008.appspot.com",
messagingSenderId: "227557197970",
appId: "1:227557197970:web:aad3453997eb67a7073e4b"
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
function startFCM() {
messaging
.requestPermission()
.then(function () {
return messaging.getToken()
})
.then(function (response) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ route("store.token", app()->getlocale()) }}',
type: 'POST',
data: {
token: response
},
dataType: 'JSON',
success: function (response) {
alert('Token stored.');
},
error: function (error) {
alert(error);
},
});
}).catch(function (error) {
alert(error);
});
}
messaging.onMessage(function (payload) {
const title = payload.notification.title;
const options = {
body: payload.notification.body,
icon: payload.notification.icon,
};
new Notification(title, options);
});
</script>
@endsection
2 changes: 2 additions & 0 deletions resources/views/layouts/app.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,7 @@

<script src="{{ asset('metronic-template/v7/assets/js/ajax/getdata.js') }}"></script>

<script src="{{ asset('firebase-messaging-sw.js') }}"></script>

</html>

1 change: 1 addition & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,4 @@
Route::post('/tarif/create', [App\Http\Controllers\Admin\Api\AdminController::class, 'tarifCreate'])->middleware('auth:sanctum');
Route::post('/tarif-update', [App\Http\Controllers\Admin\Api\AdminController::class, 'tarifUpdate'])->middleware('auth:sanctum');

Route::post('/send-notification', [App\Http\Controllers\Admin\Api\AdminController::class, 'sendNotification'])->middleware('auth:sanctum');
6 changes: 4 additions & 2 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

});
Route::post('/store-token', [App\Http\Controllers\User\Notification\NotificationSendController::class, 'updateDeviceToken'])->name('store.token');
Route::post('/send-web-notification', [App\Http\Controllers\User\Notification\NotificationSendController::class, 'sendNotification'])->name('send.web-notification');

});

require __DIR__ . '/admin-routes/auth/admin-auth-route.php';
require __DIR__ . '/admin-routes/panel/admin-panel-route.php';
require __DIR__ . '/admin-routes/panel/admin-panel-route.php';

0 comments on commit 062e493

Please sign in to comment.