🙂 İNSANLARIN EN HAYIRLISI INSANLARA FAYDALI OLANDIR 🙂

Ramazan HABER / FLUTTER / Firebase Cloud Messaging API V1 ile access token oluşturarak mesaj gönderme

1-) FLUTTER - Firebase Cloud Messaging API V1 ile access token oluşturarak mesaj gönderme

1

 

 

import 'package:googleapis_auth/auth_io.dart'; // access token almak için

import 'package:http/http.dart' as http;

 

Future<void> bildirimGonder(String title, String body, String toToken) async {

      // 1. Service account dosyasını oku

      String jsonString = await rootBundle.loadString('assets/ayar/firebaseprojeid.json');

      Map<String, dynamic> serviceAccount = json.decode(jsonString);

 

      // 2. JSON içinden bilgiler

      String clientEmail = serviceAccount['client_email'];

      String privateKey = serviceAccount['private_key'];

 

      final accountCredentials = ServiceAccountCredentials(

        clientEmail,

        ClientId("", ""), // boş bırak, sadece ServiceAccount kullanıyoruz

        privateKey,

      );

 

      final scopes = ['https://www.googleapis.com/auth/firebase.messaging'];

 

      final authClient = await clientViaServiceAccount(accountCredentials, scopes);

 

      final accessToken = authClient.credentials.accessToken.data;

 

      print('Access Token: $accessToken');

 

      // 3. Bildirimi gönder

      await http.post(

        Uri.parse('https://fcm.googleapis.com/v1/projects/${serviceAccount["project_id"]}/messages:send'),

        headers: {

          'Authorization': 'Bearer $accessToken',

          'Content-Type': 'application/json; charset=UTF-8',

        },

        body: jsonEncode({

          "message": {

            "token": toToken,

            "notification": {

              "title": title,

              "body": body,

            }

          }

        }),

      );

    }

 

 

 

 

 

 

AÇIKLAMA :

 

1 Gerekli Paketler

Öncelikle pubspec.yaml dosyasına şu paketleri ekleyelim:

dependencies:

  flutter:

    sdk: flutter

  http: ^1.2.0

  googleapis_auth: ^1.4.0

 

Terminalden şu komutu çalıştırarak paketleri yükleyebilirsiniz:

flutter pub get

 


2 Service Account JSON Dosyası

  • Firebase Console → Project Settings → Service Accounts sekmesine gidin.
  • "New private key" diyerek yeni bir Service Account anahtarı oluşturun.
  • Dosyayı indirin ve proje içerisine assets/ayar/firebaseprojeid.json olarak kaydedin.

Ardından pubspec.yaml dosyasına şu satırı ekleyin:

flutter:

  assets:

    - assets/ayar/

 2025 Haziran 22 Pazar
 225