Setup¶
Google Service Account¶
In order to access a Firebase project using a server SDK, you must authenticate your requests to Firebase with a Service Account.
Follow the steps described in the official Firebase documentation to create a Service Account for your Firebase application (see Add the Firebase Admin SDK to your Server) and make sure the Service Account has the Project -> Editor or Project -> Owner role.
With autodiscovery¶
By default, the SDK is able to autodiscover the Service Account for your project in the following conditions:
- The path to the JSON key file is defined in one of the following environment variables
FIREBASE_CREDENTIALS
GOOGLE_APPLICATION_CREDENTIALS
- The JSON Key file is located in Google’s “well known path”
- on Linux/MacOS:
$HOME/.config/gcloud/application_default_credentials.json
- on Windows:
$APPDATA/gcloud/application_default_credentials.json
- on Linux/MacOS:
If one of the conditions above is met, creating a new Firebase instance is as easy as this:
use Kreait\Firebase\Factory;
$firebase = (new Factory)->create();
A more explicit alternative:
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
$serviceAccount = ServiceAccount::discover();
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();
Manually¶
You can also pass the path to the Service Account JSON file explicitly:
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/firebase_credentials.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();
Use your own autodiscovery¶
You can use your own, custom autodiscovery methods as well:
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount\Discoverer
$discoverer = new Discoverer([
function () {
$serviceAccount = ...; // Instance of Kreait\Firebase\ServiceAccount
return $serviceAccount;
}
]);
$firebase = (new Factory)
->withServiceAccountDiscoverer($myDiscoverer)
->create();
Custom Database URI¶
If the project ID in the JSON file does not match the URL of your Firebase application, or if you want to be explicit, you can configure the Factory like this:
use Kreait\Firebase\Factory;
$firebase = (new Factory)
->withDatabaseUri('https://my-project.firebaseio.com')
->create();
Enable user management features¶
To be able to use user management features, you have to provide the Firebase Web API key to the factory. You can find the key in the settings area of your Firebase project.
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/google-service-account.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();