# Firebase導入メモ

**URL:** https://forum.ficusonline.com/t/topic/499
**Category:** Programming
**Created:** [2023 年 10 月 31 日午前 5:53 UTC](https://forum.ficusonline.com/t/topic/499 "2023-10-31T05:53:39Z")
**Posts on this page:** 8
**Page:** 1

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2023 年 10 月 31 日午前 5:53 UTC](https://forum.ficusonline.com/t/topic/499/1 "2023-10-31T05:53:39Z")

</div>

## Firebase

Google が提供するクラウドベースの開発プラットフォーム

> **[Firebase | Google's Mobile and Web App Development Platform](https://firebase.google.com/?hl=ja)**
>
> Firebase は、デベロッパーがユーザーに人気のアプリやゲームを開発できるよう支援する Google のモバイルおよびウェブアプリ開発プラットフォームです。

以下Firebase提供のサービスの一つである **Firebase Authentication** サービスを利用することで、AndroidやiOS向けなど各種アプリに、SMSやメール認証によるユーザ登録プロセスを導入することが出来ます。

> **[Firebase Authentication | Simple, multi-platform sign-in](https://firebase.google.com/products/auth?hl=ja)**
>
> Firebase は、デベロッパーがユーザーに人気のアプリやゲームを開発できるよう支援する Google のモバイルおよびウェブアプリ開発プラットフォームです。

料金体系については以下を参照願います。

- **フリーのSparkプラン**

- **従量課金制のBlazeプラン**

SparkプランでのSMS送信数には以下制限はありますが、通信費は発生しません。

電話認証 - すべての地域：1 日あたり 10 件の SMS を送信

> **[Firebase Pricing](https://firebase.google.com/pricing?hl=ja)**
>
> Firebase を無料で開始し、世界中の何百万人ものユーザーに向けてスケールアップしましょう。発生する費用は使用した分のみです。

* * *

> **[Firebase Authentication](https://firebase.google.com/docs/auth?authuser=3&hl=ja)**
>
> Firebase Authentication を使用すると、アプリにエンドツーエンドの ID ソリューションを追加することにより、ユーザー認証、ログイン、オンボーディングをわずか数行のコードで簡単に行えます。

**電話番号認証** スマートフォンに SMS メッセージを送信してユーザーを認証します。

[iOS](https://firebase.google.com/docs/auth/ios/phone-auth?authuser=3&hl=ja) [Android](https://firebase.google.com/docs/auth/android/phone-auth?authuser=3&hl=ja) [ウェブ](https://firebase.google.com/docs/auth/web/phone-auth?authuser=3&hl=ja) [C++](https://firebase.google.com/docs/auth/cpp/phone-auth?authuser=3&hl=ja) [Unity](https://firebase.google.com/docs/auth/unity/phone-auth?authuser=3&hl=ja)

#### [Android で電話番号を使用して Firebase 認証を行う &nbsp;|&nbsp; Firebase Authentication](https://firebase.google.com/docs/auth/android/phone-auth?hl=ja&authuser=3)

> **[Firebase](https://github.com/firebase)**
>
> Firebase has 102 repositories available. Follow their code on GitHub.

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2023 年 10 月 31 日午前 9:12 UTC](https://forum.ficusonline.com/t/topic/499/2 "2023-10-31T09:12:13Z")

</div>

## Android Studioでの操作

### debug.keystoreの作成

> <https://stackoverflow.com/questions/8576732/there-is-no-debug-keystore-in-android-folder>

```auto
$ keytool -genkey -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=Android Debug,O=Android,C=US"

```

* * *

### 自己署名アプリ

> **[クライアント認証  |  Google Play services  |  Google for Developers](https://developers.google.com/android/guides/client-auth?hl=ja)**

キーストアのパスワードの入力を求めるプロンプトが表示されます。デバッグ キーストアのデフォルト パスワードは **`android`** です。Keytool はフィンガープリントをターミナルに出力します。

```auto
$ keytool -list -v -alias androiddebugkey -keystore ~/.android/debug.keystore
Enter keystore password:  
Alias name: androiddebugkey
Creation date: Oct 31, 2023
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: xxxxxxxxxxxxxxxxxxxxx
Valid from: Tue Oct 31 17:21:41 JST 2023 until: Sat Mar 18 17:21:41 JST 2051
Certificate fingerprints:
	 SHA1: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
	 SHA256: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Signature algorithm name: SHA256withRSA
Subject Public Key Algorithm: 2048-bit RSA key
Version: 3
......
......

```

Javaバージョンエラー

```auto
* What went wrong:
An exception occurred applying plugin request [id: 'com.android.application']
> Failed to apply plugin 'com.android.internal.application'.
   > Android Gradle plugin requires Java 17 to run. You are currently using Java 11.

```

上記エラーからJava 17のインストール

```auto
$ sudo apt install openjdk-17-jdk
$ sudo update-java-alternatives --list
$ java -version

```

* * *

> **[ハードウェア デバイス上でアプリを実行する  |  Android Studio  |  Android Developers](https://developer.android.com/studio/run/device?utm_source=android-studio-2021-1-1&authuser=3&hl=ja)**
>
> Android Debug Bridge（adb）接続を介したテストやデバッグを実施するための開発環境と Android デバイスのセットアップ方法を学びます。

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2023 年 11 月 8 日午後 2:21 UTC](https://forum.ficusonline.com/t/topic/499/3 "2023-11-08T14:21:37Z")

</div>

## [Android で電話番号を使用して Firebase 認証を行う &nbsp;|&nbsp; Firebase Authentication](https://firebase.google.com/docs/auth/android/phone-auth?hl=ja&authuser=3#kotlin+ktx_3)

Firebase Authentication を使用して、ユーザーのスマートフォンに SMS メッセージを送信することで、ユーザーの登録認証を行うための参照コード。

登録ユーザーは SMS メッセージに記載された6桁のトークンを使用してアカウントをアクティベートします。

### 電話認証のActivityクラス

`auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/PhoneAuthActivity.kt`

> <https://github.com/firebase/snippets-android/blob/b8f65e9150fe927a5f0473e15e16fa5803189b60/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/PhoneAuthActivity.kt>

### 依存関係の確認

`auth/app/build.gradle.kts`

> <https://github.com/firebase/snippets-android/blob/master/auth/app/build.gradle.kts>

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2023 年 11 月 23 日午前 2:09 UTC](https://forum.ficusonline.com/t/topic/499/4 "2023-11-23T02:09:11Z")

</div>

## Bardへの質問

Android-Studioによるアプリの開発の場合、コーディングに関しての疑問は、Bardを利用することで生産性が大幅に向上します。ChatGPTでも同じことが言えますが、Google提供の各種APIサービスを導入する場合にはBardを活用した方が良いでしょう。

**注）** トークンとは、あるサービスに登録しているユーザやデバイスを区別するために利用される、暗号化された一時的なIDとして捉えましょう。

> #### firebase対応のアプリがインストールされたデバイスのFCMトークンを取得するのにFirebaseMessagingServiceクラスまたはFirebaseMessagingクラスのどちらを使用するのが望ましいですか？

FirebaseMessagingServiceクラスとFirebaseMessagingクラスのどちらを使用するかは、アプリの要件に応じて異なります。

FirebaseMessagingServiceクラスは、Firebase Cloud Messaging サービスからの通知を受信するために使用されるクラスです。このクラスには、トークンを取得するためのメソッドがいくつか用意されています。

トークンを取得するためのメソッドは、次のとおりです。

- `onNewToken()`：デバイスのトークンが変更されたときに呼び出されるコールバック メソッドです。このメソッドは、新しいトークンを取得するために使用できます。
- `getToken()`：デバイスに割り当てられているデフォルトの FCM トークンを取得します。このトークンは、アプリがバックグラウンドで実行されている場合でも、アプリのライフサイクル全体を通じて有効です。

FirebaseMessagingクラスは、Firebase Cloud Messaging サービスを操作するために使用されるクラスです。このクラスには、トークンを取得するためのメソッドも用意されています。

トークンを取得するためのメソッドは、次のとおりです。

- `getToken()`：デバイスに割り当てられているデフォルトの FCM トークンを取得します。このトークンは、アプリがバックグラウンドで実行されている場合でも、アプリのライフサイクル全体を通じて有効です。

**FirebaseMessagingServiceクラスを使用する場合のメリット**

- Firebase Cloud Messaging サービスからの通知を受信するために使用できるため、アプリの通知機能を実装する場合に便利です。
- `onNewToken()` メソッドを使用することで、常に最新のトークンを取得できます。

**FirebaseMessagingクラスを使用する場合のメリット**

- FirebaseMessagingServiceクラスよりもシンプルなコードで記述できます。
- `getToken()` メソッドを使用することで、アプリのライフサイクル全体を通じて有効なトークンを取得できます。

**結論**

FirebaseMessagingServiceクラスを使用する場合は、Firebase Cloud Messaging サービスからの通知機能を実装する必要がある場合に便利です。FirebaseMessagingクラスを使用する場合は、Firebase Cloud Messaging サービスからの通知機能を実装する必要がない場合に便利です。

具体的には、次の場合にFirebaseMessagingServiceクラスを使用するのが望ましいと言えます。

- アプリでFirebase Cloud Messaging サービスからの通知機能を実装する必要がある場合
- 常に最新のトークンを取得する必要がある場合

具体的には、次の場合にFirebaseMessagingクラスを使用するのが望ましいと言えます。

- アプリでFirebase Cloud Messaging サービスからの通知機能を実装する必要がない場合
- アプリのライフサイクル全体を通じて有効なトークンを取得する必要がある場合

* * *

> #### Firebaseのトークンとは？

Firebase のトークンは、Firebase サービスとの通信に使用される、一意の識別子です。Firebase のトークンは、大きく分けて以下の 2 種類があります。

- **ID トークン**

ID トークンは、ユーザーまたはデバイスを識別するために使用されます。ユーザーがログインすると、Firebase はユーザーに ID トークンを生成します。ID トークンは、Firebase Realtime Database、Cloud Storage、Cloud Functions などのサービスへのアクセスに使用できます。

- **デバイス登録トークン**

デバイス登録トークンは、デバイスを識別するために使用されます。アプリが起動すると、Firebase はデバイスにデバイス登録トークンを生成します。デバイス登録トークンは、Firebase Cloud Messaging (FCM) を使用して、アプリに通知を送信するために使用できます。

Firebase のトークンは、JSON Web Token (JWT) 形式で作成されます。JWT は、署名付きの JSON オブジェクトです。署名は、トークンの改ざんを検出するために使用されます。

Firebase のトークンの有効期限は、トークンの種類によって異なります。ID トークンの有効期限は 1 時間です。デバイス登録トークンの有効期限は 2 か月です。

Firebase のトークンは、アプリのセキュリティを強化するために使用されます。トークンを使用すると、Firebase サービスは、ユーザーまたはデバイスが正当なユーザーであることを確認できます。

> #### 具体的なトークンの例を表示できますか？

はい、Firebase のトークンの例を表示します。

**ID トークンの例**

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbkBnbWFpbC5jb20iLCJyb2xlIjoid2ViYXV0aG9yaXphdGlvbiIsImF1dGhvcl9pZCI6IjEiLCJleHAiOjE2MzY0NjM0MTMsImlzcyI6Imh0dHBzOi8vZXhhbXBsZS5jb20iLCJzdWIiOiIifQ.t12345678901234567890

このトークンは、以下の構成になっています。

- **ヘッダー**

- **ペイロード**

- **署名**

**デバイス登録トークンの例**

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ0ZXN0QGV4YW1wbGUuY29tIiwicm9sZSI6InRlc3RAZXhhbXBsZS5jb20iLCJhZG1pbiI6dHJ1ZSwiZXhwIjoxNjM2NDYyNDAzLCJpc3MiOiJodHRwczovL2V4YW1wbGUuY29tIiwiZXhwIjoxNjM2NDYyNDAzLCJzY29wZXMiOlsiYWNjZXNzIiwiZGF0YSIsImp0aSI6Ijc4Y2FmMjcyLTQ1YTMtNDY0MS1iYjU2LTYzY2U2MTk1ZmE0MCJ9.p98765432109876543210

このトークンは、以下の構成になっています。

- **ヘッダー**

- **ペイロード**

- **署名**

Firebase のトークンは、Firebase サービスとの通信に使用される重要なツールです。トークンの構成を理解しておくことで、Firebase サービスとの通信を安全に行うことができます。

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2023 年 11 月 25 日午前 3:10 UTC](https://forum.ficusonline.com/t/topic/499/6 "2023-11-25T03:10:21Z")

</div>

## 各種キーの役割

ウェブAPIキーは、アプリがFirebaseのAPIにアクセスする際に利用されるキー。  
アプリには `google-service.json` で読み込まれます。

 ![Screenshot from 2023-11-25 11-21-53](https://forum.ficusonline.com/uploads/default/original/2X/b/bcddd482e5cfcc8627856402fc76468c19984a7f.png)

サーバキーは **サーバトークン** としてサーバ側で指定する必要があります。  
**Flexisipサーバ** の **`flexisip.conf`** とアカウントマネージャの **`.env`** ファイルで指定します。

 ![Screenshot from 2023-11-25 11-38-08](https://forum.ficusonline.com/uploads/default/original/2X/4/469d7e493babf558101a82ddd1af70e151d8a222.png)

## FCMメッセージのテスト送信

メッセージタイトル、送信メッセージを入力し **テストメッセージを送信** ボタンをクリック

 ![Screenshot from 2023-11-25 09-32-32](https://forum.ficusonline.com/uploads/default/original/2X/7/7e4de193c7d55e61639cb70aae693498cf28ea5b.png)

### FCM登録トークン（デバイストークン）を追加

Android-Studioの仮想デバイスのデバイストークンをログから取得し追加。  
**テスト** ボタンをクリックするとデバイスにメッセージが表示されます。

 ![Screenshot from 2023-11-25 09-33-05](https://forum.ficusonline.com/uploads/default/original/2X/5/55708847695a04aa31df3dc9d7f1c1405168757a.png)

[FCM 登録トークン管理のベスト プラクティス &nbsp;|&nbsp; Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging/manage-tokens?hl=ja&authuser=3)

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2023 年 12 月 1 日午前 12:45 UTC](https://forum.ficusonline.com/t/topic/499/7 "2023-12-01T00:45:51Z")

</div>

## Conditions for using Firebase SMS OTP

アンドロイドアプリ、ウェブアプリでFirebaseのメッセージ送信機能を利用する場合の条件は以下の通りです。ウェブアプリ上で電話番号により新規にユーザ登録する場合には、電話番号が登録されている **デバイストークン** が取得できないため、SMS(OTP)機能は使用できません（既にFirebaseでユーザ登録されている場合は除く）。

The conditions for utilizing Firebase’s messaging functionality in Android and web applications are as follows:

In the case of registering a new user on a web application with their phone number, SMS (OTP) functionality cannot be used if **the device token** associated with the phone number cannot be obtained (excluding cases where the user is already registered with Firebase).

| | Registration from Android App | Registration from Web App | Login from Android App | Login from Web App |
| --- | --- | --- | --- | --- |
| **Firebase FCM** | O | \*X | O | O |
| **Firebase SMS（OTP）** | O | \*X | O | O |

\***X)** If an user device has been already registered as Firebase user, it will be OK.  
**Android App** : Linphone  
**Web App** : Flexisip (Account Manager API)

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2023 年 12 月 5 日午前 8:37 UTC](https://forum.ficusonline.com/t/topic/499/8 "2023-12-05T08:37:05Z")

</div>

### [Android アプリでメッセージを受信する &nbsp;|&nbsp; Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging/android/receive?authuser=3&hl=ja)

デフォルトではアプリがバックグラウンドで動作している場合に限りシステムトレイにメッセージが表示されます。

| アプリの状態 | 通知 | データ | 両方 |
| --- | --- | --- | --- |
| フォアグラウンド | `onMessageReceived` | `onMessageReceived` | `onMessageReceived` |
| バックグラウンド | システムトレイ | `onMessageReceived` | 通知: システムトレイ、データ: インテントの追加部分内 |

### [https://firebase.google.com/docs/cloud-messaging/concept-options?authuser=3&hl=ja#notifications\_and\_data\_messages](https://firebase.google.com/docs/cloud-messaging/concept-options?authuser=3&hl=ja#notifications_and_data_messages)

| \>\>\>\>\>\> | 使用シナリオ | 送信方法 |
| --- | --- | --- |
| 通知メッセージ | クライアント アプリがバックグラウンドで実行されている場合、FCM SDK は、クライアント アプリに代わってエンドユーザーのデバイスにメッセージを表示します。通知を受信しているときにアプリがフォアグラウンドで実行されている場合、アプリのコードによってアプリの動作が決定されます。通知メッセージでは、いくつかのユーザー表示用キーが事前定義されており、カスタムの Key-Value ペアのデータ ペイロードを任意に指定できます。 | 1. [Cloud Functions](https://firebase.google.com/docs/functions?authuser=3&hl=ja) やアプリサーバーなどの信頼できる環境で、[Admin SDK](https://firebase.google.com/docs/cloud-messaging/admin?authuser=3&hl=ja) または [FCM サーバー プロトコル](https://firebase.google.com/docs/cloud-messaging/server?authuser=3&hl=ja#choose)を使用し、`notification` キーを設定します。オプションのデータ ペイロードを指定できます。常に折りたたみ可能になります。[表示通知の例](https://firebase.google.com/docs/cloud-messaging/send-message?authuser=3&hl=ja#example-notification-message-with-platform-specific-delivery-options)を参照して、リクエストのペイロードを送信します。 2. [Notifications Composer](https://console.firebase.google.com/project/_/notification?authuser=3&hl=ja) を使用し、メッセージのテキストやタイトルなどを入力して送信します。カスタムデータを指定することで、オプションのデータ ペイロードを追加できます。 |
| データ メッセージ | クライアント アプリがデータ メッセージの処理を行います。データ メッセージには、予約済みのキー名のないカスタム Key-Value ペアのみが含まれます（以下を参照）。 | [Cloud Functions](https://firebase.google.com/docs/functions?authuser=3&hl=ja) やアプリサーバーなどの信頼できる環境で、[Admin SDK](https://firebase.google.com/docs/cloud-messaging/admin?authuser=3&hl=ja) または [FCM サーバー プロトコル](https://firebase.google.com/docs/cloud-messaging/server?authuser=3&hl=ja#choose)を使用し、`data` キーのみを設定します。 |

### [REST Resource: projects.messages &nbsp;|&nbsp; Firebase Cloud Messaging REST API](https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages?hl=ja#methods)

#### AndroidConfig

```auto
{
  "collapse_key": string,
  "priority": enum (AndroidMessagePriority),
  "ttl": string,
  "restricted_package_name": string,
  "data": {
    string: string,
    ...
  },
  "notification": {
    object (AndroidNotification)
  },
  "fcm_options": {
    object (AndroidFcmOptions)
  },
  "direct_boot_ok": boolean
}

```

> <https://stackoverflow.com/questions/38451235/how-to-handle-the-firebase-notification-when-app-is-in-foreground>

> <https://stackoverflow.com/questions/37358462/firebase-onmessagereceived-not-called-when-app-in-background>

[https://developer.android.com/training/notify-user/build-notification?hl=ja](https://developer.android.com/training/notify-user/build-notification?hl=ja)

[https://developer.android.com/training/notify-user/channels?hl=ja](https://developer.android.com/training/notify-user/channels?hl=ja)

[https://developer.android.com/reference/kotlin/androidx/core/app/NotificationCompat.Builder](https://developer.android.com/reference/kotlin/androidx/core/app/NotificationCompat.Builder)

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2025 年 4 月 28 日午前 6:18 UTC](https://forum.ficusonline.com/t/topic/499/9 "2025-04-28T06:18:55Z")

</div>

## Firebaseコンソール画面更新

Firebaseで作成したプロジェクトでマイアプリ（Androidプラットホーム）を登録。

アプリのキーと ID が含まれている構成ファイル **`google-services.json`** をダウンロード。

 ![firebase_whole](https://forum.ficusonline.com/uploads/default/original/2X/2/2d6d94aad6aea8ee1d1c8ec9529ed99d59f87f98.png)

構成ファイルを以下の指定ディレクトリへ移動。

 ![firebase_add_to_app](https://forum.ficusonline.com/uploads/default/original/2X/3/3428f77926069c8f0b8d2807a8453d1d76af27fe.png)

Firebase Cloud Messaging API（V1）の確認。  
Cloud Console API管理画面へ（画面マーキング箇所をクリック）

 ![firebase_cloud_messaging](https://forum.ficusonline.com/uploads/default/original/2X/c/cd2650934d80e6eea53e95417866c94e65e4086b.png)

管理をクリック

 ![firebase_fcm_api_manage](https://forum.ficusonline.com/uploads/default/original/2X/5/5a3c971bf05814543eb3c39965fa9da90a1af23a.png)

リクエストステータス

 ![firebase_api_service](https://forum.ficusonline.com/uploads/default/original/2X/8/8936f05ecb5a72bfcbdbbab0bb235bab9664e7b4.png)

サービスアカウントタブで秘密鍵の作成（これはアプリの登録時に自動で作成されます）

 ![firebase_service_account](https://forum.ficusonline.com/uploads/default/original/2X/e/e6f5615eb978c07fbb9d413c6f5e89170532ba8c.png)

メッセージのテスト（デバイストークンが必要です）

 ![firebase_send_notification_message](https://forum.ficusonline.com/uploads/default/original/2X/9/9dd652d2e816b7bbdeafa842f2f1324eb05203e7.png)
