Extend Google Analytics with Cloud Functions
Stay organized with collections
Save and categorize content based on your preferences.
Google Analytics provides event reports that help you understand how users interact with your app. With Cloud Functions (1st gen), you can access conversion events you have logged from Apple and Android devices and trigger functions based on those events.
Trigger a Google Analytics function
Cloud Functions supports the Google Analytics
AnalyticsEvent.
This event is triggered whenever user activity generates a conversion event.
For example, you could write a function that
triggers when the in_app_purchase event is generated, indicating that an
in-app purchase has occurred.
You must specify the Analytics event that
you want to trigger your function using the
functions.analytics.event()
method, and handle the event within the
onLog()
event handler:
exports.sendCouponOnPurchase=functions.analytics.event('in_app_purchase').onLog((event)=>{
//...
});
Access event attributes
With each Analytics event, you have access to all relevant
parameters and user properties. These include information about the user, the
device, the app, and geographical information for the event.
For the complete list of parameters and user properties, see the
functions.analytics reference.
For a purchase-triggered function as illustrated in
this sample,
you might want to access user attributes such as the user's language and the
event's value (valueInUSD).
This second attribute allows the sample function to test whether this is a
high-value conversion event, in order to send a higher-value coupon to valuable customers.
/**
*Afterauserhascompletedapurchase,sendthemacouponviaFCMvalidontheirnextpurchase.
*/
exports.sendCouponOnPurchase=functions.analytics.event('in_app_purchase').onLog((event)=>{
constuser=event.user;
constuid=user.userId;//TheuserIDsetviathesetUserIdAPI.
constpurchaseValue=event.valueInUSD;//AmountofthepurchaseinUSD.
constuserLanguage=user.deviceInfo.userDefaultLanguage;//Theuserlanguageinlanguage-countryformat.
//Forpurchasesabove500USD,wesendacouponofhighervalue.
if(purchaseValue > 500){
returnsendHighValueCouponViaFCM(uid,userLanguage);
}
returnsendCouponViaFCM(uid,userLanguage);
});
Next steps
To learn more about handling Analytics events in Cloud Functions,
see the Google Analytics documentation and the
functions.analytics reference,
and try running the code sample
coupon-on-purchase.