Firebase WordPress Integration Release 2.12.0

Sep 26, 2021

First steps

1 Products 3

2 First steps 5 2.1 Introductions...... 5 2.2 IF-PRO Plugin Configuration...... 6 2.3 Firebase Cloud Functions Deployment...... 7 2.4 List of Current Shortcodes...... 12 2.5 Update the Plugin...... 17

3 Authentication 19 3.1 Enable FirebaseUI Web...... 19 3.2 Register & Login Form...... 20 3.3 Custom Registration Form (Contact 7)...... 22 3.4 One Tap Sign Up & Email Link Sign In...... 23 3.5 WordPress User Integration...... 24 3.6 Firebase User Profile on WordPress...... 32 3.7 Manage Firebase Users in WordPress Dashboard...... 34

4 Database 39 4.1 Retrieve Data from Firestore and Display on WordPress...... 39 4.2 Dynamically Display Firestore Data on WordPress...... 40 4.3 Save Data from WordPress to Firebase (Realtime + Firestore)...... 41 4.4 How to Work With Firebase Custom Claims in WordPress...... 46

5 Cloud Storage 49 5.1 Cloud Storage Integration...... 49

6 Analytics 53 6.1 Configure Analytics...... 53

7 Firebase Features 55 7.1 Sync Post Data from WordPress to Firebase...... 55 7.2 Sync User Data From WordPress to Firebase...... 57 7.3 Firebase Cloud Message Integration...... 60

8 Hooks 65 8.1 Integrate Firebase PRO Filter Hooks...... 65

i 8.2 Woocommerce Extension Filter Hooks...... 67

9 Developers 69 9.1 Add Custom Scripts...... 69 9.2 Retrieve Data and Display on WordPress...... 71

10 Extensions 75 10.1 Integrate Firebase Template...... 75 10.2 Integrate Firebase Users...... 75 10.3 Woocommerce...... 76 10.4 JWT - Restful API...... 82 10.5 Realtime Google Maps...... 86 10.6 BuddyPress...... 86

11 Usecases 87 11.1 WordPress CMS for Mobile Apps...... 87

12 Miscellaneous 89 12.1 Troubleshooting...... 89 12.2 Performance - Optmization...... 89 12.3 Internationalization...... 90 12.4 Roadmap...... 90 12.5 CHANGELOG...... 94

ii Firebase WordPress Integration, Release 2.12.0

Last updated: Sep 26, 2021 Follow Twitter for updates. Integrate Firebase PRO is a WordPress plugin that brings Firebase features to WordPress site. E.g. sign in to WordPress and Firebase with one tap / email link or read & write to Firbase from WordPress. Demo site: https://wordpress.dalenguyen.me Download plugin: https://firebase.dalenguyen.me Video Tutorials: Youtube Playlist - Firebase WordPress Integration If you are interested in the development progress, please check the Road map.

First steps 1 Firebase WordPress Integration, Release 2.12.0

2 First steps CHAPTER 1

Products

• Integrate Firebase PRO- v2.18.0 • Firebase WordPress Functions- v1.2.0 (bundle with PRO plugin) • Integrate Firebase Woocommerce- v2.5.0 (Extension) • Integrate Firebase Users- v1.2.0 (Extension) • Integrate Firebase Template- v1.0.0 (Extension)

3 Firebase WordPress Integration, Release 2.12.0

4 Chapter 1. Products CHAPTER 2

First steps

This guide is mostly for the PRO version, if you are using the FREE version, please refer to the WordPress.org Guide • Introductions • IF-PRO Plugin Configuration • Firebase Cloud Functions Deployment • List of Current Shortcodes • Update the Plugin

2.1 Introductions

After downloading the Integrate Firebase PRO plugin, please follow the video in order to have better review of how to install and make use of this plugin in your WordPress site. The current version of the plugin works best in the situation that you want to take advantage of Firebase features without connecting with the default WordPress users database. List of features • Login to WordPress with Firebase Authentication • A headless CMS solution from WordPress • Firebase User Management in WordPress Dashboard • Save data from WordPress to Firebase • Retrieve data from Realtime / Firestore • Dynamically display Realtime / Firestore Data • and more. . .

5 Firebase WordPress Integration, Release 2.12.0

2.2 IF-PRO Plugin Configuration

Please deactivate and remove the Free plugin before installing the Integrate Firebase PRO version.

2.2.1 Download the Integrate Firebase PRO plugin

There is a FREE version of this Firebase WordPress integration plugin that you can find in WordPress plugin site. You can give it a try, however, the application is very limited. If you only want to interact with Firebase through WordPress frontend only, then the free version would be sufficient enough. So, if you want a more secured and advanced feature of the plugin, support the development of Integrate Firebase PRO version.

2.2.2 Prepare Firebase Credentials

Before using the plugin, we need have the credentials from Firebase Console. You can get it by logging into https: //console.firebase.google.com. After signning in, you can navigate to Project Overview > Project Settings.

Fig. 1: General configuration

In General tab, you can get the config at the bottom. If you don’t have any app ready, you can create a new one.

Fig. 2: Create a Web app

6 Chapter 2. First steps Firebase WordPress Integration, Release 2.12.0

After creating a web app for you project, you can save your credentials for later usage.

2.2.3 Installation Process

After you have downloaded the plugin, uncompress the zip file in order to install the plugin file (integrate-firebase- PRO.zip). You can use default installation process in order to install the plugin. Otherwise, you can always manually upload the plugin to your plugin folder through FTP client. After you activate the plugin, you need to enter the Firebase credentials in the Dashboard > Firebase. After that, you can create login form, show data, show logout button. . . on WordPress frontend.

2.2.4 Select Firebase Services - Optimization

With the new update since v1.1.0 you have to pick the services (General Tab) for optimization purposes. I have choose either Realtime / Firestore or both of them in order to interact with Firebase Database on the frontend.

2.3 Firebase Cloud Functions Deployment

If you are using PRO version, there is another folder named firebase--functions. If you want to manage database, Firebase users and custom functions, you should deploy the functions together with the plugin. Make sure that you have Nodejs installed on your machine. The cloud functions is only Admin Dashboard tasks, you don’t have to deploy the cloud functions for frontend inter- actions such as login, display or retrieve data. If you want a hands-on guide, you can watch this tutorial: How to Deploy Cloud Functions

2.3.1 Prerequisite

In order to deploy cloud functions, you need to have Nodejs v12 installed on your machine. On Google Cloud Platform, go to your project and make sure Cloud Buid API and Cloud Functions are enabled. And the account that you use to deploy has Service Account User Role in order to deploy cloud functions to Firebase. Then install firebase-tools packaged

npm install -g firebase-tools

SignIn and test firebase cli

firebase login

Since version 0.6.0, before deploying any functions, you should create two tokens for security purpose. One for Wordpress dashboard usage, the other is for Wordress frontend.

// Generate random token node -e "console.log(require('crypto').randomBytes(20).toString('hex'))"

// Set your token to firebase configuration(dashboard token) firebase functions:config:set api.dashboard_token=your-secret-key --project project-id

// Set your token to firebase configuration(frontend token) (continues on next page)

2.3. Firebase Cloud Functions Deployment 7 Firebase WordPress Integration, Release 2.12.0

Fig. 3: Firebase Credentials

8 Chapter 2. First steps Firebase WordPress Integration, Release 2.12.0

Fig. 4: General configuration

Fig. 5: Firebase Optimization

2.3. Firebase Cloud Functions Deployment 9 Firebase WordPress Integration, Release 2.12.0

(continued from previous page) firebase functions:config:set api.frontend_token=your-secret-key --project project-id

// Check your api token firebase functions:config:get api --project project-id

2.3.2 Change Your Plan to Blaze

Why will I need a billing account to use the Node.js 10 runtime for Cloud Functions for Firebase? Because of updates to its underlying architecture planned for August 17, 2020, Cloud Functions for Firebase will rely on some additional paid Google services: Cloud Build, Container Registry, and Cloud Storage. These architecture updates will apply for functions deployed to the Node.js 10 runtime. Usage of these services will be billed in addition to existing pricing.

Fig. 6: Firebase pricing plans

10 Chapter 2. First steps Firebase WordPress Integration, Release 2.12.0

2.3.3 Change Cloud Functions Regions

Default functions will be deployed to us-central1. If you don’t want to change the regions, please skip this part. In case you want to change the deploy regions to asia-east2, you can set a regions configuration for the firebase.

// Set deploy regions for `asia-east2` firebase functions:config:set regions.0=asia-east2 --project project-id

// Set deploy regions for `asia-east2` and`us-central1` firebase functions:config:set regions.0=asia-east2 regions.1=us-central1 --project

˓→project-id

After configuration, please check your environment to make sure that you have the region in the functions config. firebase functions:config:get regions --project project-id

// The result should looks like this for two regions(asia-east2 & us-central1) [ "asia-east2", "us-central1" ]

2.3.4 Install Packages & Deploy Cloud Functions

Install packages and build functions. I’m using Yarn, you can use npm if you want. cd functions/ yarn OR npm install

The code will go to functions folder, then installs packages with yarn / npm. Start deploying firebase functions cd functions yarn deploy --project project-id // OR firebase deploy --only functions --project project-id

The deployment result should look like this

X functions: Finished running predeploy script. i functions: ensuring necessary APIs are enabled... X functions: all necessary APIs are enabled i functions: preparing functions directory for uploading... i functions: packaged functions(103.29 KB) for uploading X functions: functions folder uploaded successfully i functions: updating Node.js 10(Beta) function api-user(us-central1)... i functions: updating Node.js 10(Beta) function api-database(us-central1)... X functions[api-user(us-central1)]: Successful update operation. X functions[api-database(us-central1)]: Successful update operation.

X Deploy complete!

Project Console: https://console.firebase.google.com/project/project-id/overview Done in 77.56s.

2.3. Firebase Cloud Functions Deployment 11 Firebase WordPress Integration, Release 2.12.0

After that, you should update your Firebase setting with the dashboad token and frontend token and firebase functions url (e.g. https://us-central1-project-id.cloudfunctions.net)

Fig. 7: Firebase setting

Just to verify that everything works, you can find three cloud functions in your firebase console after the deployment.

2.4 List of Current Shortcodes

Shortcodes are mostly used on WordPress frontend, when you create a page or a post in WordPress dashboard, you can embeded in the content.

// Page or Post

[firebaseui_web][/firebaseui_web]

If you are a developer who knows PHP, you can use it anywhere you want.

// files do_shortcode("[firebaseui_web][/firebaseui_web]");

12 Chapter 2. First steps Firebase WordPress Integration, Release 2.12.0

Fig. 8: Firebase cloud functions

2.4.1 Authentication

Demo: https://wordpress.dalenguyen.me/register-login-form/

// Add this shortcode in order show error message to the front end

[firebase_error class='your-class-name'][/firebase_error]

// Login, Register through FirebaseUI Web // redirect parameter is optional

[firebaseui_web redirect="link-to-page"][/firebaseui_web]

// After logging in, you will be redirect to the homepage. The redirect is optional.

˓→Default button text is "Login"

[firebase_login button_text='Signin' redirect='/']

// Registration wilh extra fields: first name, last name and phone number. The

˓→redirect, extra fields and requried fields are optional. Without those, it will

˓→only show email and password fields.

[firebase_register required_fields='firstName,lastName,phoneNumber' extra_fields=

˓→'firstName,lastName,phoneNumber' redirect='/']

// Greetings Logged in User

[firebase_greetings][/firebase_greetings]

// Logout Button // redirect after logging out and button_text are optional

[firebase_logout redirect="/" button_text="Sign Out"][/firebase_logout]

2.4. List of Current Shortcodes 13 Firebase WordPress Integration, Release 2.12.0

2.4.2 Content

// Show custom message for NOT Logged in Users

[firebase_show_not_login class='your-class-name']YOUR HTML CODE[/firebase_show_not_

˓→login]

// Show custom message for Logged in Users

[firebase_show class='your-class-name']YOUR HTML CODE[/firebase_show]

2.4.3 Realtime Database & Firestore

Note: You can add html string to the field in the database in order to have an interactive field when displaying on WordPress. Dynamically dispaly data from document: • https://wordpress.dalenguyen.me/display-realtime-document-dynamically/ • https://wordpress.dalenguyen.me/display-firestore-document-dynamically/ In order to get data that relates to Firebase User Id, you can replace document_name=’some-string’ by docu- ment_name=’getFirebaseUid’. After user logs in, getFirebaseUid will be replaced by their user id.

Realime collection as table

Demo: https://wordpress.dalenguyen.me/display-realtime-collection-data/

// show realtime collection data basing on collection name & display fields

[realtime_col class='your-class-name' collection_name='users' display_fields='email,

˓→firstName,gender,food,hobbies,phone']

Realime collection as blocks

Demo: https://wordpress.dalenguyen.me/display-realtime-collection-as-bocks/

// show realtime collection data basing on collection name & display fields // display fields or images is required

[realtime_blocks class='your-class-name' collection_name='blog' display_fields='title,

˓→description,more' images='url']

// In order to sort the data, you can add order_by, the order bases on orderByChild()

[realtime_blocks class='your-class-name' collection_name='blog' display_fields='title,

˓→description,more' images='url' order_by='title']

Realime Document as table

Demo: https://wordpress.dalenguyen.me/display-realtime-document-data/

14 Chapter 2. First steps Firebase WordPress Integration, Release 2.12.0

// show realtime document data basing on collection name & document id as table // Collection & Document will be come path of the Realtime database --> /users/123456 // display fields or images is required

[realtime class='your-class-name' collection_name='string' document_name='string'

˓→display_fields='email,displayName,role,uid' images='imageUrl']

Realime Document as blocks

Demo: https://wordpress.dalenguyen.me/display-realtime-document-data/

// show realtime document data basing on collection name & document id as blocks // Collection & Document will be come path of the Realtime database --> /users/123456 // display fields or images is required

[realtime class='your-class-name' collection_name='string' document_name='string'

˓→display_fields='email,displayName,role,uid' images='imageUrl' display_type='blocks']

Firestore collection as table

Demo: https://wordpress.dalenguyen.me/display-firestore-collection-data/

// show firestore collection data basing on collection name & display fields // display fields or images is required // if you want to display document id, add `id` to display_fields

[firestore_col class='your-class-name' collection_name='users' display_fields='email,

˓→firstName,gender,food,hobbies,phone']

Firestore collection as blocks

Demo: https://wordpress.dalenguyen.me/display-firestore-collection-as-bocks/

// show firestore collection data basing on collection name & display fields // display fields or images is required // nested object key is also supported by using dot notation (e.g. author.fullName)

// if you want to display document id, add `id` to display_fields

[firestore_blocks class='your-class-name' collection_name='blog' display_fields=

˓→'title,author.fullName,description,more' images='image.url']

// In order to sort the data, you can add order_by. For example, this will order by

˓→title - descendant. You can also combine the orders: `order_by='title|asc,

˓→description|desc'` // You can also limit the data by adding a `limit` parameters (optional)

[firestore_blocks class='your-class-name' collection_name='blog' display_fields=

˓→'title,description,more' images='url' order_by='title|DESC' limit=10]

2.4. List of Current Shortcodes 15 Firebase WordPress Integration, Release 2.12.0

Firestore collection through queries

Demo: https://wordpress.dalenguyen.me/display-firestore-with-queries/ In some cases, you have to open your console log and create an index for your queries.

// Operation list eq: '==', ne: '!=', gt: '>', ge: '>=', lt: '<', le: '<=', in: 'in', ni: 'not-in', ac: 'array-contains', aca: 'array-contains-any',

Sample Queries

// Query 'users' collection // email == [email protected] // age > 20 // display fields: email,firstName,lastName,age,gender // display as 'blocks' | 'table'

[firestore_search class='your-class-name' search_fields='email|age' search_operators=

˓→'eq|gt' search_conditions='[email protected]|20' collection_name='users' display_

˓→fields='email,firstName,lastName,age,gender' display_type='blocks']

// In order to sort the data, you can add order_by. For example, this will order by

˓→title - descendant. You can also combine the orders: `order_by='firstName|asc,

˓→lastName|desc'`

In search_conditions, if you added getFirebaseUid, it will be replaced by Firebase UID after user logs in.

Firestore Document as table

Demo: https://wordpress.dalenguyen.me/display-firestore-document-data/

// show firestore data basing on collection name & document id // display fields or images is required // if you want to display document id, add `id` to display_fields

[firestore class='your-class-name' collection_name='string' document_name='string'

˓→display_fields='email,displayName,role,uid' images='imageUrl']

Firestore Document as blocks

Demo: https://wordpress.dalenguyen.me/display-firestore-document-data/

// show firestore data basing on collection name & document id // display fields or images is required // if you want to display document id, add `id` to display_fields (continues on next page)

16 Chapter 2. First steps Firebase WordPress Integration, Release 2.12.0

(continued from previous page)

[firestore class='your-class-name' collection_name='string' document_name='string'

˓→display_fields='email,displayName,role,uid' images='imageUrl' display_type='blocks']

2.4.4 Custom Claims (User’s roles)

Demo: https://wordpress.dalenguyen.me/show-or-hide-content-for-logged-in-users/

// only user with admin claim will see the content // otherwise they will see a Custom message

[firebase_show_with_claims class='your-class-name' claims='admin' message='Custom

˓→message' ] HTML Data With Tags [/firebase_show_with_claims]

2.5 Update the Plugin

The plugin is not in WordPress.org, you can not update automatically through WordPress dashboard. There are two ways that you can update the plugin to a newer version without losing the current settings. Please don’t delete the plugin and reinstall it, you will have to reconfigure the plugin again if you do that. Before updating, please check the readme.txt for instruction.

Fig. 9: Plugin folder

The readme will let you know if you need to install the cloud functions or not. If it doesn’t mention the plugin in the changelog, you can ignore the cloud functions folder.

2.5.1 1. Update the plugin via WordPress Dashboard

Since WordPress 5.5, you can upload the plugin zip file and update it directly using WordPress Dashboard.

2.5.2 2. Update the plugin via Cpanel

You can login to your Cpanel and override the plugin folder with the newer version.

2.5.3 3. Update the plugin via a Ftp Client

You can use an Ftp client such as FileZilla in order to connect to your hosting, and override the plugin folder with a newer version.

2.5. Update the Plugin 17 Firebase WordPress Integration, Release 2.12.0

Fig. 10: Replace current plugin

18 Chapter 2. First steps CHAPTER 3

Authentication

Even though the plugin allows Firebase users to log in to WordPress at the same time, best scenario is to use WordPress as backend for Firebase without allowing users to login to WordPress. • Enable FirebaseUI Web • Register & Login Form • Custom Registration Form (Contact 7) • One Tap Sign Up & Email Link Sign In • WordPress User Integration • Firebase User Profile on WordPress • Manage Firebase Users in WordPress Dashboard

3.1 Enable FirebaseUI Web

This feature will help to you register, login and logout on WordPress with your Firebase Users. However, this won’t let your users login to WordPress Dashboard. If you want to sync the Users between two systems, please read the WordPress User Integration section in this guide. Go to WordPress User Integration Section. Before showing the FirebaseUI Web on your WordPress, you need to enable sign-in options in Firebase > Authentica- tion Since version 0.5.5, all the authentication methods will be handled through FirebaseUI-Web.

// Deprecated shortcodes [firebase_user_register] and[firebase_login]

You need to update the Auth settings in Firebase, in order to enable this feature. Then you well the login feature on the frontend.

19 Firebase WordPress Integration, Release 2.12.0

Fig. 1: Enable SignIn Options

You can enable the login feature by adding this shorcode a post or a page. If you specify the redirect parameter in the shortcode, it will override the setting in WordPress in order to redirect to desired page after logging in.

// redirect & send_email_confirmation are optional [firebaseui_web redirect="link-to-page" send_email_confirmation=true][/firebaseui_web]

3.2 Register & Login Form

If you don’t want to use FirebaseUI Web, you can create a custom login or registration form in order to authenticate with Firebase & WordPress. Demo: https://wordpress.dalenguyen.me/register-login-form/

3.2.1 Login Form

This form only support log in though email, and you can style it freely.

// After logging in, you will be redirect to the homepage. // The redirect is optional. Default button text is "Login"

[firebase_login button_text='Signin' redirect='/']

3.2.2 Registration Form

With this form, you can customize the registration form that will save extra fields such as phone number.

20 Chapter 3. Authentication Firebase WordPress Integration, Release 2.12.0

Fig. 2: FirebaseUI Web Settings

3.2. Register & Login Form 21 Firebase WordPress Integration, Release 2.12.0

Fig. 3: FirebaseUI Web Frontend

// Registration will extra fields: first name, last name phone number. // The redirect, extra fields and requried fields are optional. // Without those, it will only show email and password fields.

[firebase_register required_fields='firstName,lastName,phoneNumber' extra_fields=

˓→'firstName,lastName,phoneNumber' redirect='/']

If you want to send a verification email after user registers, you can add this

˓→option: send_email_confirmation=true Remember that if user doesn't verify their email, they won't be allowed to login next

˓→time.

3.2.3 Logout Option

This shortcode will show a Logout button after a user signs in.

// Logout Button // redirect after logging out and button_text are optional

[firebase_logout redirect="/" button_text="Sign Out"][/firebase_logout]

3.3 Custom Registration Form (Contact 7)

This feature is added since v2.15.1. The purpose of the feature is to provide a custom registration form for the user. Instead of having email & password only, now you can have extra fields like name, address, phone number, etc. Demo: https://wordpress.dalenguyen.me/custom-registration-c7-form/ Video: https://youtu.be/IzfS0Hok6mg

22 Chapter 3. Authentication Firebase WordPress Integration, Release 2.12.0

3.3.1 Contact 7 Form Creation

Here is a simple example of how to use the custom registration form. These hidden fields are optional.

[hidden sendEmailConfirmation1 "true"] [hidden redirect "/my-account"]

[submit "Register"]

3.3.2 Embed Registration Form in a Page

After you have created the form, you can embed it in a page. Remember to put html_id=”if-c7-registration-form” in the form tag.

[contact-form-7 id="211" title="Registration" html_id="if-c7-registration-form"]

If you want to save extra fields to firebase, please check Sync User Data From WordPress to Firebase

3.4 One Tap Sign Up & Email Link Sign In

This is a new update since v1.3.0. Enable this feature in the plugin is not enough. You also have to configure in (Google Cloud Platform) GCP & Firebase.. Password is becoming obsolete. Remembering username and password in order to login to a website maybe easy, how about 10 websites? So, how about one-click to login & sign up to WordPress & Firebase?

3.4. One Tap Sign Up & Email Link Sign In 23 Firebase WordPress Integration, Release 2.12.0

3.4.1 One-tap Sign-up

This is a feature from Google. Sign up new users with just one tap, without interrupting them with a sign-up screen. Users get a secure, token-based, passwordless account on your site, protected by their Google Account.

Fig. 4: Get Google Client ID

3.4.2 Sigin In Via Email Link

This is straight forward. Users enter their email, and they will get a sign-in link in their inbox. They click on the the link and sign in to WordPress and Firebase at the same time.

3.5 WordPress User Integration

This feature solves the authentication problem. This is an example from one of my potential clients. The client has a mobile app (Firebase users), and they want those users to login to a separate WordPress website without registering again. And this plugin can help you to achieve just that. Authentication also work for WordPress multisite. At this stage, it helps to authenticate to WordPress dashboard with a subscriber or customer role (WooCommerce). And the password will be dominated by Firebase Users. User cannot change password when logging into WordPress dashboard. They have to use forgot password feature in Firebase in order to create a new password. And if the password is different in both systems, the next time user logs in through FirebaseUI Web shortcode, it will change the password in WordPress automatically. Support: Social Logins, Email and Phone Number.

24 Chapter 3. Authentication Firebase WordPress Integration, Release 2.12.0

Fig. 5: Apply Google Client ID

3.5. WordPress User Integration 25 Firebase WordPress Integration, Release 2.12.0

Fig. 6: One-tap Sign-up

Firebase UID will be used as WordPress username. If they have display name from Firebase (e.g. Google login), it will update WordPress display name for a friendly user experience.

3.5.1 Prerequisite

You need to deploy the cloud functions in order to use this feature properly. The cloud functions will help to secure the authentication process between WordPress & Firebase.

3.5.2 Login to WP Dashboard with Firebase Users

Important: Before doing this, you should keep a dashboard open for yourself, and open another private window in order to login with an email from Firebase, then assign the Admin right to that user before you log out of current window - to make sure that you can log in again with your Firebase user (with **admin** rights). In case of logging out without assign another user with admin rights, you can rename the plugin folder, and login as usual. This flow will utilize FirebaseUI Web workflow in order to authenticate users. In order to that, you have to log in to WordPress Dashboard, then Dashboard > Firebase > Auth. Check Allow Login to WP Dashboard and enter you Login Url. It could be your homepage or a separate page just for logging in. From now, everytime users navigate to https://your-webiste.com/wp-admin, it will redirect to your new login page. This page will contain the shortcode for logging in.

// Login, Register through FirebaseUI Web [firebaseui_web redirect='link-to-page'][/firebaseui_web]

26 Chapter 3. Authentication Firebase WordPress Integration, Release 2.12.0

Fig. 7: Allow email link in Firebase

3.5. WordPress User Integration 27 Firebase WordPress Integration, Release 2.12.0

Fig. 8: Allow sign in via email link

28 Chapter 3. Authentication Firebase WordPress Integration, Release 2.12.0

Fig. 9: Sigin In Via Email Link

Fig. 10: User Display Name in WooCommerce

3.5. WordPress User Integration 29 Firebase WordPress Integration, Release 2.12.0

Fig. 11: Firebase Auth Settings

30 Chapter 3. Authentication Firebase WordPress Integration, Release 2.12.0

Fig. 12: New WP Login Page

3.5. WordPress User Integration 31 Firebase WordPress Integration, Release 2.12.0

After users log in, it will create a new user in WordPress if the user doesn’t exist. Then authenticate it to WordPress dashboard automatically. In PRO - v1.17.0, while user logging in, there will be a loading state that prevents users from navigating to other pages until the login process is completed. One thing to notice that, after user logs in via the plugin shortcode, the firebase uid is saved in user metadata, and you can retrive it by using this example.

// This will return an array with firebase uid $firebase_uid = get_user_meta( $user->ID , 'firebase_uid', true ); error_log($firebase_uid);

Notice: the WordPress username defaults to Firebase UID, and their display name will be set as Firebase Display Name or Phone Number (via phone authentication). User can change their display name if they want. This is only affect since v1.4.0 When users log out from dashboard, that means they will also be logged out to Firebase.

3.5.3 Create a new WordPress User through API

The Integrate Firebase PRO has its own Restful API endpoints that help to create a new WordPress user. In this scenario, when you have a mobile app, and you want to duplicate user in WordPress, you can call the API to create a new User after user register on your app.

Endpoint: POST https://example.com/firebase/v2/users/register

Example payload: { username: 'dale', email: '[email protected]', password: 'the-password' }

3.6 Firebase User Profile on WordPress

You have ability to manage Firebase Users account from WordPress. For example, User is managed in Firestore under ‘users‘ collection and the document is the Firebase UID. Then you can create a Contact 7 form with the fields that represent your users information. *Note: the form only supports text, tel, number, date and radio at the moment.

3.6.1 Create User Profile Fields with Contact Form 7

For example, User profile will be saved to Firebase under users collection, the document is the firebase UID. Remember to set the security rule that only allows user to update their own data.

// Example of Firestore security rule match /users/{userId}{ allow read, write: if request.auth.uid== userId; }

Sample Firebase User Profile structure in Firestore Contact 7 form sample for user management

32 Chapter 3. Authentication Firebase WordPress Integration, Release 2.12.0

Fig. 13: User Profile structure

// If you add class "getFirebaseUid" to any inputs, it will return the current user

˓→uid automatically

[hidden databaseType "firestore"] [hidden collectionName "users"] [hidden documentId class:getFirebaseUid "INVALID"] [hidden collectionName "users"] [hidden dateType "dateOfBirth"]

[text* firstName placeholder "First Name"] [text* lastName placeholder "Last Name"] [text* email placeholder "Email"] [tel phone placeholder "+1 647 620 0000"] Age

[number age id:age min:1 max:100] Date of Birth

[date* dateOfBirth id:dateOfBirth] Gender

[radio gender id:gender default:1 "Male" "Female" "Other"]

[submit "Submit"]

3.6.2 Create Firebase User Account Page

This step is easy, you can create a Page on WordPress, then put the following shortcode to the page. Then you will have an account page that users can manage their profile information.

// html_id="ifp-firebase-account" is required

[contact-form-7 id="188" html_id="ifp-firebase-account" title="Firebase Account"]

Demo site: https://wordpress.dalenguyen.me/firebase-account/

3.6. Firebase User Profile on WordPress 33 Firebase WordPress Integration, Release 2.12.0

3.7 Manage Firebase Users in WordPress Dashboard

Google provided a great tool for authentication. However, it is not convenient in terms of user management. As you can see, the options are limited.

Fig. 14: Firebase default options

That is why I want to make it easier for the webmaster if they want to create, read, update and delete (CRUD) a Firebase user directly through WordPress dashboard.

3.7.1 Prerequisite

Before you can achieve this, you have to configure Firebase > Settings with your Base Domain and Dashboard API Secret Token. You can take a look at how to set it up the Integrate Firebase to WordPress section.

Fig. 15: Firebase settings

34 Chapter 3. Authentication Firebase WordPress Integration, Release 2.12.0

3.7.2 Firebase Users Management

User management is under the Firebase > Users tab. You will see a form where you can add a new User to Firebase. Remember that the user will be added to Firebase, not WordPress.

Fig. 16: Add a new Firebase user

If the process is successfull, you will be notified with a message that contains the user id. If you want to read, modify or delete a user, you can press on “Click to load users”. You can find the information about Firebase users where you can update the display name, email, phone number, and even user custom claims. There is an option that you can download entire list of Firebase user to a CSV file. When you delete a user, there will a prompt to confirm if you want to delete it to make sure that you do not accidentally press the delete button.

3.7. Manage Firebase Users in WordPress Dashboard 35 Firebase WordPress Integration, Release 2.12.0

Fig. 17: Firebase user is added

Fig. 18: Load Firebase Users

36 Chapter 3. Authentication Firebase WordPress Integration, Release 2.12.0

Fig. 19: Delete a Firebase User

3.7. Manage Firebase Users in WordPress Dashboard 37 Firebase WordPress Integration, Release 2.12.0

38 Chapter 3. Authentication CHAPTER 4

Database

From WordPress, users can retrieve or write data from Firebase Realtime / Firestore using shortcodes. • Retrieve Data from Firestore and Display on WordPress • Dynamically Display Firestore Data on WordPress • Save Data from WordPress to Firebase (Realtime + Firestore) • How to Work With Firebase Custom Claims in WordPress

4.1 Retrieve Data from Firestore and Display on WordPress

In this tutorial, I will show you how to retrieve the database from your Firestore and display it on the WordPress website. Before that, make sure you have: • Install and active Integrate Firebase plugin • Update the firebase configuration on the Firebase dashboard • Make sure that Firebase security rules allow you to access the document with or without logging in The plugin support getting one document and display on the frontend as a table with the shortcode.

// Get document id '1' from 'users' collection from realtime database [realtime class='your-class-name' collection_name='users' document_name='1' display_

˓→fields='email,displayName,role,uid' ]

// Get document id '1' from 'users' collection from firestore [firestore class='your-class-name' collection_name='users' document_name='1' display_

˓→fields='email,displayName,role,uid']

If the default shortcode doesn’t suite your needs, you can create a custom one. Please follow the guide for developers.

39 Firebase WordPress Integration, Release 2.12.0

Fig. 1: Display data from firebase

4.2 Dynamically Display Firestore Data on WordPress

This tutorial will help to retrieve a list of documents from Firestore, then generate a link that leads to a child page. Just imagine this as an blog page and a post page. Demo: • https://wordpress.dalenguyen.me/display-firestore-collection-data/ • https://wordpress.dalenguyen.me/display-firestore-collection-as-blocks/ You need to create two pages: • Parent page to display a list of documents from Firestore • Child page to display a single document from the parent page The shortcode allows to you to add your custom class for CSS styling. Please add custom CSS in the WordPress for your own styling.

4.2.1 Create the Parent Page

After you create a new WordPress page, use this shortcode to retrieve data from Firestore and display them.

// show firestore data basing on collection name as blocks [firestore_blocks class='your-class-name' collection_name='blog' display_fields=

˓→'title,description,more' images='url']

// In order to sort the data, you can add order_by. For example, this will order by

˓→title - descendant. You can also combine the orders: `order_by='title|asc,

˓→description|desc'`

(continues on next page)

40 Chapter 4. Database Firebase WordPress Integration, Release 2.12.0

(continued from previous page) // If you want to limit amount of data, you can add limit=

// Generate a link to a child page by adding "child_page" & "child_page_target_field"

[firestore_blocks class='your-class-name' collection_name='blog' display_fields=

˓→'title,description,more' images='url' order_by='title|DESC' limit=10 child_page=

˓→'https://wordpress.dalenguyen.me/dynamic-display-firestore-data-from-blocks' child_

˓→page_target_field='title']

I suggest that you also add this shortcode to show any error when retriving data: [firebase_error class='your-class-name'][/firebase_error]

4.2.2 Create the Child Page

This page doesn’t show anything by itself. It will display data from the parent page. You have to put this shortcode to customize the information that need to be displayed. Demo: https://wordpress.dalenguyen.me/dynamic-display-firestore-data-from-blocks?docId= 1prQPhET2etbBRkrF3f8

// Data is generated from https://wordpress.dalenguyen.me/display-firestore-

˓→collection-as-blocks // document_name will be replace by the docId from query params

// E.g. https://wordpress.dalenguyen.me/dynamic-display-firestore-data-from-blocks/?

˓→docId=1prQPhET2etbBRkrF3f8

[firestore class='your-class-name' collection_name='blog' document_name='from-queries

˓→' display_fields='title,description' images='url' display_type='blocks']

After creating two pages, you have a system that can retrieve information from Firestore and display it dynamicly on WordPress.

4.3 Save Data from WordPress to Firebase (Realtime + Firestore)

If your Contact7 is >= v.5.2, please use update this plugin to the latest version (>= v1.5.0). In this guide, I will show you how to add new data to Realtime database Firestore. In this example, I use Contact Form 7, but you feel free to design your own form or use other plugin. The reason that I use Contact Form 7 is because it’s the most popular form in WordPress plugin. It is well supported and highly customisation. You don’t have to worry about form validation or email handling after submitting a form. If you decide to create your own custom form, remember to add “if-create-data-form” as an ID to your form, together with the hidden fields below.

4.3.1 Prerequisite

Since v0.17.0, you only need to update security rules on your database (realtime / firestore), so any can write to your database or they have to log in before saving. It totally depends on the firebase security rules. Note: if you use ‘Contact 7 Redirect’ feature, it may not work properly because the redirect may interfere with the sync process.

4.3. Save Data from WordPress to Firebase (Realtime + Firestore) 41 Firebase WordPress Integration, Release 2.12.0

Fig. 2: Custom Create Form

4.3.2 Getting Firebase UID value

If you want to get the Firebase UID to any inputs as a value. You can add a special class getFirebaseUid to the input fields.

// Sample contact 7 input [hidden documentId class:getFirebaseUid "INVALID"]

// Sample html input

4.3.3 Example of creating new form and writing data to Firestore

Sample of data that I will use to update to Firestore export interface Contact{ firstName: string lastName: string email: string phone: string age: string dateOfBirth: string hobbies: array food: array gender: string }

The createdAt field will be added automatically for sorting purpose. From that you can create a sample form in Contact tab. The hidden fields are important. • [hidden collectionName “users”] -> collection name is users. • [hidden documentId “your-document-name”] -> it will override the document id 1. This field is optional. • [hidden databaseType “firestore”] -> data will be saved in firestore. • [hidden keyId “YOUR-ID-KEY-NAME”] -> data will be saved in firestore together with the document id. • [hidden arrayType “hobbies,food”] -> array data should be added to arrayType field. This field is optional. • [hidden dateType “dateOfBirth”] -> will save as ISO string type. This field is optional. • [hidden mapTypes “contact”] -> will save a map (object) type • [hidden integerTypes “age,phone”] -> will save as integer type • [hidden formAction “UPDATE”] -> This option is DEPRECATED.

42 Chapter 4. Database Firebase WordPress Integration, Release 2.12.0

The default option is to upsert data to firebase. If the node / id does not exist, it will create a new one; otherwise, it it update the existing data.

[hidden collectionName "users"] [hidden documentId "your-document-name"] [hidden databaseType "firestore"] [hidden arrayType "hobbies,food"] [hidden dateType "dateOfBirth"] [hidden mapTypes "contact"] [hidden integerTypes "age"]

[text* firstName placeholder "First Name"] [text* lastName placeholder "Last Name"] [text* email placeholder "Email"] [tel phone placeholder "+1 647 620 0000"]

[number age id:age min:1 max:100]

[date* dateOfBirth id:dateOfBirth]

[text* contact__firstName placeholder "Contact First Name"] [text* contact__lastName placeholder "Contact Last Name"]

[select* contact__sex id:contact__sex "Male" "Female" "Other"]

[select* hobbies id:hobbies multiple "Archery" "Slap Dance" "Rock Climbing"]

[checkbox food id:food "Pho" "Ramen" "Dimsum"]

[radio gender id:gender default:1 "Male" "Female" "Other"]

[submit id:if-data-submit "Submit"]

The shortcode will be added to the WordPress page or post. With the id: “if-create-data-form”. The id is important in order for the plugin to save the data to firebase.

[contact-form-7 id="11" html_id="if-create-data-form" title="Contact form 1"]

After submitting, data will be saved to Firestore

4.3.4 Example of creating new form and writing data to Realtime

If you want to save data to Realtime database, the only thing that you need to change is the databaseType hidden field.

[hidden databaseType "realtime"]

If there form is valid, the data will be saved to realtime database

4.3. Save Data from WordPress to Firebase (Realtime + Firestore) 43 Firebase WordPress Integration, Release 2.12.0

44 Chapter 4. Database

Fig. 3: Sample form on frontend Firebase WordPress Integration, Release 2.12.0

Fig. 4: Data saved to firestore

Fig. 5: Data saved to realtime

4.3. Save Data from WordPress to Firebase (Realtime + Firestore) 45 Firebase WordPress Integration, Release 2.12.0

4.3.5 Addition Settings

Contact form 7 comes with extra configurations. If you don’t want to send a confirmation email to customers, you can this line to the addition settings. skip_mail: on

4.3.6 Reference https://contactform7.com/additional-settings/ https://contactform7.com/hidden-field/

4.4 How to Work With Firebase Custom Claims in WordPress

We already knew how to get and display data to WordPress. What if you want to display data to the user who is admin (through custom claims of course), and display something else to the others or just show nothing.

4.4.1 Using shortcode to display custom data

Since version 0.5.6, I added a shortcode that helps to display data if users log in and have the right custom claims.

[firebase_show_with_claims class='your-class-name' claims='admin' message='Custom message' ] HTML Data With Tags [/firebase_show_with_claims]

• class=’your-class-name’: custom class that you can add style to the element • claims=’admin’: user’s claims • message=’Custom message’: this message will show to invalid user

4.4.2 Using custom code to display custom data

This is the original code to retrieve and display data.

(function ($) { 'use strict'; $(document).ready(function () { const showFirestoreDatabase = () => { const db = firebase.firestore(); const firestoreEl = jQuery('#custom-firebase');

// You can get the collectionName and documentName from the shortcode

˓→attribute const collectionName = 'users'; const documentName = ‘document-1'

if (collectionName && documentName) { const docRef = db.collection(collectionName).doc(documentName); (continues on next page)

46 Chapter 4. Database Firebase WordPress Integration, Release 2.12.0

(continued from previous page)

docRef.get().then(doc => { if (doc.exists) { // console.log('Document data:', doc.data()); let html = '

'; jQuery.each(doc.data(), function (key, value) { // You can put condition to filter your value // and it won't show on the frontend html += ''; html += ``; html += ''; html += ''; }) html += '
${String(key)} ' + value + '
'; firestoreEl.append(html) } else { // doc.data() will be undefined in this case console.error('Please check your collection and document name

˓→in the [custom_firebase] shortcode!'); } }).catch(error => { console.error('Please check your collection and document name in

˓→the [custom_firebase] shortcode!', error); }); } else { console.warn('Please check your collection and document name in the

˓→[custom_firebase] shortcode!'); } }

showFirestoreDatabase() }) })(jQuery)

The showFirestoreDatabase() function will display data on WordPress. Now, we will wrap it under custom claims check.

(function ($) { 'use strict'; $(document).ready(function () { const showFirestoreDatabase= () => { ... } // We won't call the function directly here // showFirestoreDatabase()

const getUserCustomClaims= () => { firebase.auth().onAuthStateChanged(function (user) { if (firebase.auth().currentUser) { firebase.auth().currentUser.getIdTokenResult() .then((idTokenResult) => { // Confirm the user is an Admin. if (!!idTokenResult.claims.admin) { // We will call the function here showFirestoreDatabase() } else { (continues on next page)

4.4. How to Work With Firebase Custom Claims in WordPress 47 Firebase WordPress Integration, Release 2.12.0

(continued from previous page) // Show something else } }) .catch((error) => { console.log(error); }); } }); }

getUserCustomClaims() }) })(jQuery)

After checking the user’s custom claims, and make sure that it’s admin. Then we will call showFirestoreDatabase() function. This tutorial doesn’t limit to retrieve data from Firestore, you can put any functions or features after checking the custom claims.

48 Chapter 4. Database CHAPTER 5

Cloud Storage

Cloud Storage is built for app developers who need to store and serve user-generated content, such as photos or videos. • Cloud Storage Integration

5.1 Cloud Storage Integration

At this stage, cloud storage is added to the plugin. However, in order to use it, you can follow the instruction or create your own scripts. If you can to customize it, please refer to the Developer section. NOTE: Please don’t implelement redirect on your form, it will interfere with file uploading process.

5.1.1 Enable Cloud Storage

In general tab, you have add the Storage Bucket from your firebase project, then check the option for Storage under Firebase Services.

5.1.2 Upload File to Cloud Storage

Upload files to Cloud Storage is similar to Save Data to Firestore Database. First, we need to create a form with the help of Contact Form 7 or you can design your own custom form if you want.

// This form will create a path of the file to "users" collection // If you want to generate a random id, you can leave out the documentId // The file will be uploaded to "wpImages/documentId/timestamp+filename" path under

˓→Storage // Multiple files are separated by a comma ","

[hidden collectionName "users"] [hidden documentId "some-random-id"] (continues on next page)

49 Firebase WordPress Integration, Release 2.12.0

Fig. 1: Configure Cloud Storage

50 Chapter 5. Cloud Storage Firebase WordPress Integration, Release 2.12.0

(continued from previous page) [hidden databaseType "firestore"] [hidden fileType "imageUrl1,imageUrl2"]

[file imageUrl1 limit:1mb filetypes:gif|png|jpg|jpeg] [file imageUrl2 limit:1mb filetypes:gif|png|jpg|jpeg]

[submit "Upload File"]

Please refer to the Contact Form 7 for configuring your file input. Then create a WordPress page / post to serve your form.

// Add shortcode to your WordPress page / post // Don't forget the html_id when you add the shortcode

[contact-form-7 id="{{FORM-ID}}" html_id="if-create-data-form" title="{{FORM-TITLE}}"]

After submiting the file, it will be uploaded to Cloud Storage under wpImages/som-random-id path. The image name will be prefixed with a timestamp. For secuirty purpose, the image will be saved as a path. However, if you want to get the full readable URL, you can change the configuration.

// By adding`__public`, the file will be saved as full URL

[hidden fileType "imageUrl__public"] ...... [file imageUrl limit:1mb filetypes:gif|png|jpg|jpeg]

5.1. Cloud Storage Integration 51 Firebase WordPress Integration, Release 2.12.0

Fig. 2: Image Path in Storage

Fig. 3: Image Path in Firestore

52 Chapter 5. Cloud Storage CHAPTER 6

Analytics

At the heart of Firebase is Google Analytics, a free and unlimited analytics solution. • Configure Analytics

6.1 Configure Analytics

Analytics integrates across Firebase features and provides you with unlimited reporting for up to 500 distinct events that you can define using the Firebase SDK. Firebase Analytics is added since v1.9.0. In order to enable Firebase Analytics, you need to add App Id & Measurement Id to the Firebase > General tab. Then check the Analytics option under Firebase Services

53 Firebase WordPress Integration, Release 2.12.0

Fig. 1: Configure Analytics

54 Chapter 6. Analytics CHAPTER 7

Firebase Features

• Sync Post Data from WordPress to Firebase • Sync User Data From WordPress to Firebase • Firebase Cloud Message Integration

7.1 Sync Post Data from WordPress to Firebase

Since version 0.9.0, I added some event triggers for syncing data from WordPress to Firebase. The plugin now supports syncing Post & Page from WordPress to Firebase. That means when you add or update a new Post or Page. The content will be updated automatically to Firebase (Realtime / Firestore). • For posts, they locate under wpPosts collection name. • For pages, they locate under wpPages collection name. • For custom post types, they will local under wpTypeNames collection name. Youtube Video Tutorial: https://youtu.be/4xQn47dtre8

7.1.1 1. Setting Up

Make sure the version of the plugin is at least: v0.9.0. Then you can choose which type of data to sync to Firebase. In this example, it will choose Firetore as the database, and every new or update posts will be synced to Firestore. You can choose both Post & Page type. If you created custom post types, you can enter them to Custom Post Types field.

7.1.2 2. Create a Sample Post

After that, you can create a new post or update an existing one. After you save, the post will be added to Firestore. The document id of the post is also the post id for query purpose.

55 Firebase WordPress Integration, Release 2.12.0

Fig. 1: Synchronization configuration

Fig. 2: Create a new post

56 Chapter 7. Firebase Features Firebase WordPress Integration, Release 2.12.0

The collection name in Firebase is generated from the plural version fo the post type in WordPress. For example.

Posts -> wpPosts Fancy Cars -> wpFancyCars Fancy_Cars -> wpFancyCars Fancy-Cars -> wpFancyCars

Fig. 3: New post in firestore

For taxonomies, will be saved under a node name taxonomies. For author & custom fields, they will be saved under author and custom_fields node. Author also contains firebase uid and wordpress uid for futher usage. When you update the current post, it will override the data in the firestore to make sure that it always updated.

7.1.3 3. Delete a Post

In order to use this feature, you need to deploy cloud function (v0.19.0). Once you delete a post, it will also delete the post from firebase. This is a permanent process. If you restore the post from the trash bin in WordPress, the post in Firebase is already deleted and cannot be restored.

7.2 Sync User Data From WordPress to Firebase

This is a new feature from v1.14.0 - and please deploy cloud functions for this feature. The User data is synced from WordPress to Firebase is minimal. If you have other requests or cases, please create a ticket in Github.

7.2.1 1. Setting Up

Make sure that you deployed cloud functions and fill the information in Firebase Settings > Settings.

7.2. Sync User Data From WordPress to Firebase 57 Firebase WordPress Integration, Release 2.12.0

Fig. 4: Taxonomies node

58 Chapter 7. Firebase Features Firebase WordPress Integration, Release 2.12.0

Fig. 5: Taxonomies node

7.2. Sync User Data From WordPress to Firebase 59 Firebase WordPress Integration, Release 2.12.0

Fig. 6: Setting Tab Configuration

7.2.2 2. Update Your WordPress Tab

In this example, I want to sync data to Realtime database under users path. If you don’t want to sync User data to Firebase, you can leave it empty.

7.2.3 3. How User Data Is Synced

User data is synced after the login into WordPress using the plugin shortcode: FirebaseUI Web, Login or Register. The plugin will help to UPDATE data from WordPress to Firebase, it doesn’t override your user existing data if the fields are different. This is an example of user data from Google login. If you users register via the login with First Name, Last Name, or Phone Number, those data will also be synced to Firebase.

7.3 Firebase Cloud Message Integration

This feature only helps you to send notification or data to a topic. In order to improve this feature, you can participate in this 3 minutes survey. In order to use this feature, you need to update the plugin’s cloud functions to at least v0.6.0 which comes together with the Integrate Firebase PRO plugin. After that, you can go to WordPress dashboard > Settings > Firebase > Message, prepare your message and send it.

60 Chapter 7. Firebase Features Firebase WordPress Integration, Release 2.12.0

Fig. 7: WordPress Tab Configuration

Fig. 8: User data in Realtime Database

7.3. Firebase Cloud Message Integration 61 Firebase WordPress Integration, Release 2.12.0

There is a sample notification in the Message tab, that will send a notification to “toptic-name” topic. You will have to modify it basing on your needs.

Fig. 9: Sample notification message

This is the structure of the message. You can send a notification or data to a specific topic. Below are samples of the message. If you want to learn more on the message structure, please check the firebase send message documentation. You also can send notification together with data.

// Send notification { "notification":{ "title": "Background Message Title", "body": "Background message body" }, "topic": "topic-name" }

// Send data { "data":{ "score": "850", "time": "2:45" }, (continues on next page)

62 Chapter 7. Firebase Features Firebase WordPress Integration, Release 2.12.0

(continued from previous page) "topic": "topic-name" }

If the message is sent successfully, you will see a messge.

Fig. 10: Successfully sent a message

If you send a notification to a topic, and website is in the background, this is what user will see.

Fig. 11: Background notification

7.3. Firebase Cloud Message Integration 63 Firebase WordPress Integration, Release 2.12.0

64 Chapter 7. Firebase Features CHAPTER 8

Hooks

Actions & Filters that help to communicate with Firebase. • Integrate Firebase PRO Filter Hooks • Woocommerce Extension Filter Hooks

8.1 Integrate Firebase PRO Filter Hooks

Here is the list of filter hooks that help to communicate with Firebase services.

8.1.1 Get data from Firebase (v2.3.0)

This filter hook will help to get data from Firebase (Realtime or Firestore).

/** * Get Data from Firebase Database * * @param [type] $database_type realtime | firestore * @param [type] $collection_name * @param [type] $doc_id * @return data | false */

// start saving data to firebase apply_filters('firebase_get_data_from_database', $database_type, $collection_name,

˓→$doc_id);

8.1.2 Before Saving Post data to Firebase

This filter hook will help to modify post data before saving to Firebase. This will also apply to custom post types. If you want to save user data manually, you can use Save data to Firebase filter hook.

65 Firebase WordPress Integration, Release 2.12.0

add_filter('firebase_before_saving_post_to_database', 'edit_post_data_before_saving'); function edit_post_data_before_saving($post) { // add custom data to post $post->custom_data = 'custom data 123'; return $post; }

8.1.3 Before Saving User data to Firebase

This filter hook will help to modify User data before saving to Firebase. It will happen only once where user first login to the site. If you want to save user data manually, you can use Save data to Firebase filter hook. add_filter('firebase_before_saving_user_to_database', 'edit_user_data_before_saving'); function edit_user_data_before_saving($user) { // add custom data to user $user['custom_data'] = 'custom data 123'; return $user; }

8.1.4 Save data to Firebase

This filter hook will help to save data from WordPress to Firebase (Realtime or Firestore).

/** * Send Data to Firebase Database * * @param [type] $database_type realtime | firestore * @param [type] $collection_name * @param [type] $doc_id * @param [type] $data object * @return boolean */

// start saving data to firebase apply_filters('firebase_save_data_to_database', $database_type, $collection_name,

˓→$doc_id, $data);

8.1.5 Delete data from Firebase

This filter hook will help to delete data from Firebase (Realtime or Firestore).

/** * Delete Data from Firebase Database * * @param [type] $database_type realtime | firestore * @param [type] $collection_name * @param [type] $doc_id * @return boolean */

(continues on next page)

66 Chapter 8. Hooks Firebase WordPress Integration, Release 2.12.0

(continued from previous page) // start delete data from firebase apply_filters('firebase_delete_data_from_database', $database_type, $collection_name,

˓→$doc_id);

8.2 Woocommerce Extension Filter Hooks

Here is the list of filter hooks that help to communicate with Firebase services.

8.2.1 Subscriptions - Before Subscription Status Updated

This filter hook is called when the subscription status is updated (woocommerce_subscription_status_updated), before saving the subscription to the database. add_filter('firebase_before_subscription_status_updated', 'edit_subscription_data_

˓→before_saving'); function edit_subscription_data_before_saving($subscription) { // add custom data to user $subscription['custom_data'] = 'custom data 123'; return $subscription; }

8.2.2 Subscriptions - Before Subscription Renewal Payment is Complete

This filter hook is called when the subscription renewal payment is complete (woocom- merce_subscription_renewal_payment_complete), before saving the subscription to the database. add_filter('firebase_before_subscription_renewal_payment_complete', 'edit_

˓→subscription_data_before_saving'); function edit_subscription_data_before_saving($subscription) { // add custom data to user $subscription['custom_data'] = 'custom data 123'; return $subscription; }

8.2.3 Subscriptions - Before Saving Subscription to the Database

This filter hook is called before saving subscription to firebase. This will call after fire- base_before_subscription_status_updated and firebase_before_subscription_renewal_payment_complete filter hooks. add_filter('firebase_before_save_subscription_to_firebase', 'edit_subscription_data_

˓→before_saving'); function edit_subscription_data_before_saving($subscription) { // add custom data to user $subscription['custom_data'] = 'custom data 123'; return $subscription; }

8.2. Woocommerce Extension Filter Hooks 67 Firebase WordPress Integration, Release 2.12.0

68 Chapter 8. Hooks CHAPTER 9

Developers

If you are a developer, there is no limit that you cannot extend the plugin bases on you needs. Here are some examples. • Add Custom Scripts • Retrieve Data and Display on WordPress

9.1 Add Custom Scripts

This guide will show you how to extend the plugin by adding custom scripts, such as JavaScript. The ability of the plugin doesn’t limit in the plugin itself. You have totally control of the ‘firebase‘ object.

9.1.1 Step 1: Create a custom JavaScript file

In your theme, you can create a JavaScript file named custom-firebase.js, you can the name if you want.

// js/custom-firebase.js console.log(`Custom firebase...`) console.log(firebase) firebase.auth().onAuthStateChanged(user => { if (user) { // User logged in already or has just logged in. console.log(user) } })

This is an example function that listens to firebase authentication event. If user is logged in, you can get the user information / session. Your custom-firebase.js will be under js/ folder

69 Firebase WordPress Integration, Release 2.12.0

Fig. 1: Custom Firebase Location

70 Chapter 9. Developers Firebase WordPress Integration, Release 2.12.0

9.1.2 Step 2: Register your custom script

After that, you need to add the script to your site. The script will be added inside the body tag for better performance.

// functions.php

// Custom JavaScript for Firebase function custom_firebase_scripts_function() { wp_enqueue_script('custom_firebase', get_template_directory_uri() . '/js/custom-

˓→firebase.js', array('firebase_app', 'firebase_auth', 'firebase'), false, true); } add_action('wp_enqueue_scripts', 'custom_firebase_scripts_function');

Verify it on the front-end. You have access to firebase now.

Fig. 2: Verify custom firebase on frontend

9.2 Retrieve Data and Display on WordPress

This guide will help to retrieve the data from Firestore and display on WordPress. I should the same with Realtime Database. Please follow the guide from Firebase official documentation.

9.2.1 Step 1: Create a custom shortcode

You can do this by edit functions.php in your current theme

9.2. Retrieve Data and Display on WordPress 71 Firebase WordPress Integration, Release 2.12.0

// functions.php

// custom firebase short code function custom_firebase_func($atts) { return "

Test
"; } add_shortcode('custom_firebase', 'custom_firebase_func');

Add the shortcode on a page or post

Fig. 3: Custom Firebase Shortcode

9.2.2 Step 2: Retrieve and display data from Firestore

Now, it’s all about JavaScript. You can customize, modify and do whatever you want.

(function ($) { 'use strict'; $(document).ready(function () { const showFirestoreDatabase= () => { const db= firebase.firestore(); const firestoreEl= jQuery('#custom-firebase');

// You can get the collectionName and documentName from the shortcode

˓→attribute const collectionName= 'users'; const documentName= 'document-1'

if (collectionName&& documentName) { (continues on next page)

72 Chapter 9. Developers Firebase WordPress Integration, Release 2.12.0

Fig. 4: Custom Firebase Shortcode Frontend

(continued from previous page) const docRef= db.collection(collectionName).doc(documentName);

docRef.get().then(doc => { if (doc.exists) { // console.log('Document data:', doc.data()); let html= '

'; jQuery.each(doc.data(), function (key, value) { // You can put condition to filter your value // and it won't show on the frontend html += ''; html +=``; html += ''; html += ''; }) html += '
${String(key)} '+ value+ '
'; firestoreEl.append(html) } else { // doc.data() will be undefined in this case console.error('Please check your collection and document name

˓→in the [firestore] shortcode!'); } }).catch(error => { console.error('Please check your collection and document name in

˓→the [firestore] shortcode!', error); }); } else { console.warn('Please check your collection and document name in the

˓→[firestore] shortcode!'); } }

showFirestoreDatabase() })

(continues on next page)

9.2. Retrieve Data and Display on WordPress 73 Firebase WordPress Integration, Release 2.12.0

(continued from previous page) })(jQuery)

Check the code on the WordPress post.

Fig. 5: Firestore data retrieved

Yay, firestore data is retrieved

74 Chapter 9. Developers CHAPTER 10

Extensions

List of plugins that can integrate with Integrate Firebase PRO • Integrate Firebase Template • Integrate Firebase Users • Woocommerce • JWT - Restful API • Realtime Google Maps • BuddyPress

10.1 Integrate Firebase Template

This template is used for extending Integrate Firebase PRO plugin. You can find the plugin in Github. You can download and install as a normal plugin. After that you can modify the plugin as you want. If you have any questions or requests on how to use or modify the it, please create a ticket on Github.

10.2 Integrate Firebase Users

This is not a standalone product. In order to use this extension, you need to install at least Integrate Firebase PRO (v1.21.0) and Firebase WordPress functions (v0.15.0). The sole purpose of this plugin is to help web masters to migrate WordPress users to Firebase.

10.2.1 Install the extension

After downloading the extension, you can install and active the plugin. You will find it under Firebase > Import Users.

75 Firebase WordPress Integration, Release 2.12.0

Fig. 1: Active Firebase Users plugin

As you can see, there is 159 users in WordPress

10.2.2 Import WordPress Users to Firebase

In order to import WordPress users to Firebase, you just need to press the button Import WP Users to Firebase, and the plugin will do its magic. If you have issue with importing more than 10,000 users, please let me know. The Firebase UID will be the WordPress user_login. It’s because if uid is generated randomly, it will create another user with the same email. You can have a look the Firebase Docs. Please note that if users don’t have an email, it will not be imported to Firebase.

Fig. 2: Successfully imported Users from WordPress to Firebase

I recommend that you should try the plugin in your local machine or development environment before moving to production.

10.3 Woocommerce

Authentication will be supported by the main plugin (Integrate Firebase PRO). The other features will come as an extension plugin.

76 Chapter 10. Extensions Firebase WordPress Integration, Release 2.12.0

If you have any requests please create a ticket for it.

10.3.1 Authentication (PRO)

The authentication process from Woocommerce can be overridden by the Integrate Firebase PRO plugin. Below is the example configuration of Woocommerce Account & Privacy.

Fig. 3: Woocommerce Account configuration

From now, if you use the plugin authentication shortcode, users will be created in WordPress & Firebase at the same time. You can try the process at the Demo Shop. You can follow to checkout page, the sample product is an abook that I wrote. You don’t have to purchase it.

10.3.2 Authentication (Extension)

The Woocommerce extension supports replacing the default login / register from the My Account page with the Fire- baseUI Web shortcode. Demo: https://wordpress.dalenguyen.me/my-account

10.3.3 Synchronization (Extension)

The first iteration of the extension is to sync order and product to firebase (realtime / firestore). After successfully purchase, the order will be synced to firebase. The purpose of syncing Orders & Products is to have the flexibility of assigning user roles / permissions based on their purchases - this can be done via custom cloud functions. The configuration is straight forward, after installing the plugin, you will have to pick the right type of database and the name for the database in order to save the Woocommerce’s order.

10.3. Woocommerce 77 Firebase WordPress Integration, Release 2.12.0

Fig. 4: Extension configuration

78 Chapter 10. Extensions Firebase WordPress Integration, Release 2.12.0

Since v2.0.0, when you delete a product in WooCommerce, it will also delete in Firebase. Product data model will also base on WooCommerce Rest API structure. The existing product structure will be Deprecated in the next few releases - please modify your code in order to avoid breaking.

10.3.4 Synced Order -> Firebase (Extension)

After the purchase is success, the order will be saved to firebase. In this example, it will be saved to realtime database.

Fig. 5: Realtime order data

Since v1.8.0, order can be edited directly from WooCommerce and it will be synced to Firebase with line items.

10.3.5 Synced Product -> Firebase (Extension)

Product data structure is based on WooCommerce Product API. If you haven’t updated your code to match with the new Product data structure, please do so. The existing structure will be deprecated in the next release. If you enter the collection name for product in the settings, the WooCommerce product will be synced to Realtime / Firestore. This schema for product is based on WooCommerce Product API.

10.3.6 Synced Membership -> Firebase (Extension)

First, you need to set the collections name for the memberships in Firebase. Then when an order is purchased or somebody edits the membership, it will be updated to firebase.

10.3. Woocommerce 79 Firebase WordPress Integration, Release 2.12.0

Fig. 6: Order line items

80 Chapter 10. Extensions Firebase WordPress Integration, Release 2.12.0

Fig. 7: Membership model

10.3. Woocommerce 81 Firebase WordPress Integration, Release 2.12.0

10.3.7 Synced Subscriptions -> Firebase (Extension - v2.2.0)

Similar to Membership, this extension will sync Woocommerce Subscriptions to Firebase. It happens after a Subscription status is saved / changed.

10.3.8 Synced Product Firebase -> WordPress (Extension)

This ability is in beta, and if you want to test this one out. Please create a ticket or send and email to me for discussing. This is not the end, the extension will continue to grow. So please add your feature request on Github.

10.4 JWT - Restful API

This is NOT available yet. This add-on is still in beta. There is a POC (Proof of Concept), but I’m not promised if it is a good product and there’s a need or it or not. We’ll firgure it out.

10.4.1 Remote Authentication (via URL)

Imagine that you have a Firebase App that users can log in to. However, before they can use your app, users need to purchase a package that will give them permission. And this product will help to auto-login users from your Firebase App to your WooCommerce / WordPress website. This add-on doesn’t care if users exist in WP or not, it just log users in with Firbase credentials. That’s it. If you want to give it a try, please visit: https://dn-wp-autologin.web.app/ Any questions or discussions, please create a ticket at https://github.com/dalenguyen/firebase-wordpress-plugin/ discussions

10.4.2 Prerequisite

• Integrate Firebase PRO users • Firestore service is enabled • Node 12 for deploying cloud functions

10.4.3 Getting Started

Make sure that you have Firestore Database ready. Then apply this security rules for your collection. match /jwtTokens/{token}{ allow read, write: if false; }

If you are PRO users, you can visit My Account page and download the trial version. Then install the add-on as usual. The plugin should appear under Firebase tab.

82 Chapter 10. Extensions Firebase WordPress Integration, Release 2.12.0

10.4.4 Deploy cloud functions

The cloud functions is inside the plugin, so you need to extract the zip file in order to deploy it. Make sure that you are running Node v12. If you don’t have Node on your machine, please visit Node Version Manager. cd functions

// install the package - you can run yarn or npm(pick one only) yarn OR npm install

// deploy functions npm run deploy --project your-project-id

10.4.5 Create Auto-login page (WordPress)

Create a WordPress page with the follow shortcode.

// you can specify the redirect page after the auto-login process // default is home page

[firebase_autologin redirect="redirect-link"]

10.4.6 Create Redirect Page (Firebase App)

This example uses JavaScript. However you can implement it by using the same principal on iOS or Android or Webapp. The key is call the callable functions for logged in users.