Google Dynamic Links
Hello guys, After a long time we are back with another useful blog. As you guys see in the banner image and title, in this blog we are going to learn about Dynamic Links. How dynamic links work, advantage of dynamic links, implementation of dynamic links and finally how we can easily implement the dynamic links for facebook and other ads. So let’s get started….
1. Introduction
Dynamic links is a very hot topic nowadays. Dynamic links provide support to open mobile applications directly from a web link. Yes, you can open your mobile application directly through a simple link. Very cool isn’t it ? Google Firebase introduced this kind of mainstream in early 2012 and gave it the name “Deep Links”. This is the same mechanism introduced by Apple and they call it “Universal Links”. Universal links will open the application installed in apple devices like iPhone, iPad.
Now, how can I use a single link for android users and iOS users ? What if we have an android and iOS application and we need to redirect into the respective apps. This blog will help you to implement this…so keep reading ?
2. Why we need dynamic links
Dynamic links are very useful for marketing and advertising as best practices. You can use the same mechanism as a sharing feature. Let’s take an example of a coupon app where customers can see the list of coupons and share coupons with their friends. So here one customer will share a coupon link over WhatsApp and his friend will click on the link and that link directly opens the coupon app with the exact same coupon. So no need to search for that particular coupon. This is how you can use the dynamic links.
You can do email marketing and place the link which opens the application and directly redirect users to the specific coupon.
Now you must be thinking what if I run a marketing campaign and some customer didn’t have a mobile app installed on their devices. So here you can tweak your link in such a way that if a mobile application is installed then open the link otherwise open the App/Play store and ask the customer to install. Once they install the application and click on the “Open” button that button will redirect your customer to the same screen where he/she can see the coupon.
Now again you think like what if I open the link into a laptop not on mobile. Here again dynamic link helps us, first it will check whether the link is open into mobile device or laptop. If a customer opens the link into the laptop, you can redirect the customer to your webpage. Yes ? the perfect marketing solution. I hope now we are excited about how we can implement this so let’s check how we can implement this cool feature….
3. Implementation
For implementation purposes I’ll use Laravel (PHP) as my backend for generating the dynamic links using Firebase REST API. After that I’ll add code for handling the android and iOS application when a customer clicks on the link.
For generating the Dynamic Link you need a firebase console account. From the firebase console firstly you need to create a project. You need to add your application details like package name, SHA Keys and other related stuff. Once you create the project and add your application into the same project, you need a web API key and you can get that from the Authentication section and save that key into your environment (.env) file.
Now you can go dynamic link section where you found that one default domain was create named codezma.page.link you can add your custom domain here but for you need to verify your domain with a keys provided by google and need to set A Records as per given instruction by firebase console. After that you can set base URL like share.codezma.com (which looks slightly professional as per my thought). Here you can add multiple like offers.codezma.com or invite.codezma.com based on your requirement.
Till here you have your application ready with your custom domain now you need to add code to generate the dynamic link.
<?php $dynamicLinkData = [ 'dynamicLinkInfo' => [ 'domainUriPrefix' => "https://share.codezma.com", 'link' => "https://www.codezma.com/share/pizza/pz-50/buy-one-get-one-free", 'androidInfo' => [ 'androidPackageName' => "com.codezma.app", 'androidFallbackLink' => "https://www.codezma.com/share/pizza/pz-50/buy-one-get-one-free", ], 'iosInfo' => [ 'iosBundleId' => "app.codezma.com", 'iosAppStoreId' => "YOUR-APP-STORE-ID", 'iosCustomScheme' => "codezma.firebase.schema", 'iosFallbackLink' => "https://www.codezma.com/share/pizza/pz-50/buy-one-get-one-free", ], 'navigationInfo' => [ 'enableForcedRedirect' => "TRUE" ], 'socialMetaTagInfo' => [ 'socialTitle' => "Get 50% Off", 'socialDescription' => "Are you hungry? Get second pizza absolutely free by using this link" 'socialImageLink' => "https://www.codezma.com/wp-content/uploads/2022/03/Pizza-scaled.jpeg" ] ], 'suffix' => [ 'option' => "SHORT" ] ]; $url = "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=<YOUR-API-KEY-FROM-FIREBASE-CONSOLE>"; $headers[] = "Content-Type:application/json"; $response = fireCURL( $url, "POST", json_encode($dynamicLinkData), $headers ); return $response; /** * ------------------------------------ * Expected Response * ------------------------------------ * You will get a short link and a debug link in response. * Debug link will help you to debug the firebase redirection * Short link will the actual dynamic link */
By implementing the above code you will get your dynamic link ready. (If you performed the proper steps). As you see in the code you need to pass a link for where you want your user to get redirected, you need to pass android & iOS package name and iOS application also. One more thing you need to set up the iOS is custom scheme. You need to add the custom scheme into your plist file in iOS and for android you need to add the scheme information into schema.
Now here we have our domain ready, we have our dynamic link ready and we have our application ready. Now when we create the dynamic link it’s necessary to add fallbackUrl for android and iOS because that will help if someone directly opens the link from the browser. Here firebase will identify the browser and OS details and based on that open the application or respective app/play store. Fallback URL will work when Firebase is not able to open the application.
We created the link now to handle that link into the iOS, android & web. So let’s start with a very simple web application. In the Laravel application I’ll add a route where I can open the weblink. For example I’ve created one dynamic link for pizza-offer then by requested URL would be “https://www.codezma.com/pizza/pz-50/buy-one-get-one-free” and for this base URL by dynamic maybe like “https://offers.codezma/k319r”. So when any customer click on the link first firebase will open the application if user is one andoird/iOS if application was not installed then customer will redirected to the app/play store and install the app and from that app/play store customer open clicks on open then it’ll show a dedicated page in application will all details. Here you might think how will the application know which API it needs to call and fetch the record ?.
No need to get confused, codezma will help you to sort these details as well. When a customer clicks on the link and our application will open you get the completed base (requested) URL from delegating methods which are mentioned in the code. So the base(requested) URL structure will be link domain / category / id / text. So the app team will easily get the ID from the requested URL, in our example pz-50 was the ID of offer. Now they pass the ID in API and get all the information easily ?.
Now, If a customer opens the same link into a laptop or computer then it’ll redirect to my based(requested) URL and be able to see a dedicated web page with all details.
I hope you guys can understand the working and implementation of firebase dynamic link. You can also track the details in firebase analytic if you added the code for the same.
Here is not the actual end ❌ if you want to share the dynamic link WhatsApp, Mail, Text then this flow will work but if you want to share the dynamic link on Facebook or Instagram through post or through marketing campaign then this will not work properly. So to make things happen you need to read the last step for implementing dynamic links with Facebook AD.
4. Dynamic links with Facebook AD
If you didn’t add this kind of tick then Facebook will not open your application, it might open the app/play store or open the fallback URL which is not a proper way because you can easily get your targeted audience from Facebook or Instagram. So let’s update the code for social media ADs.
Step#1 ➡️ You need to keep your base(requested) URL and fallback URL the same.
Step#2 ➡️ You need to define the proper and universal schema for your application. For example I can add “codezma” as my schema.
Step#3 ➡️ Need to add a few lines of code in your base(requested) URL. For example I would like to open the app or respective store & if a customer opens the link from the computer then I will redirect the customer to the homepage. (Here I’ll use Laravel for the routing and redirection part).
<?php Route::get('share/pizza/{id}/{title}', function ($title, $id) { $type = 'pizza'; $title = $title; $id = $id; return view('facebook-page', compact('type', 'title','id')); })->name('share.blog'); /** * facebook-page has below mentioned code (THE HTML CODE) * $title would be the page title * $id would be the unique ID of a particular post */
<!DOCTYPE html> <html> <head> <title>Home | Codezma</title> <script type="text/javascript"> var hidden, visibilityChange; if (typeof document.hidden !== "undefined") { hidden = "hidden"; visibilityChange = "visibilitychange"; } else if (typeof document.msHidden !== "undefined") { hidden = "msHidden"; visibilityChange = "msvisibilitychange"; } else if (typeof document.webkitHidden !== "undefined") { hidden = "webkitHidden"; visibilityChange = "webkitvisibilitychange"; } function handleVisibilityChange() { if( hidden !== undefined ) if (document[hidden]) window.close(); } if (typeof document.addEventListener === "undefined" || hidden === undefined) { redirectToStore(); } else { document.addEventListener(visibilityChange, handleVisibilityChange, false); window.location.replace("codezma://{{ $type }}/{{ $id }}/{{ $title }}"); /** * Final universal link will looks like * --------------------------------------------------------------- * $type = "pizza"; * $title = "buy-one-get-one-free"; * $id = "pz-50" * --------------------------------------------------------------- * codezma://share/pizza/pz-50/buy-one-get-one-free * application-schema://host */ setTimeout(function () { redirectToStore(); }, 500) } function redirectToStore() { if( (/iphone|ipod/i.test(navigator.userAgent.toLowerCase())) ) { window.location.replace("<YOUR-APP-STORE-LINK>"); } else if( (/android/i.test(navigator.userAgent.toLowerCase())) ) { window.location.replace("<YOUR-PLAY-STORE-LINK>"); } else { hidden = undefined; window.location.replace("https://www.codezma.com"); } } </script> </head> <body></body> </html>
⚠️ How this code will work ?
I hope you guys have implemented the “mailto:” or “tel:” in your website. This is the custom schema who will open the application respective mail or phone application. So like the same we have created our schema called “codezma://“ and this will open our app. Now we can set the same structure as we set for our base(requested) URL. Like “codezma://share/pizza/pz-50/buy-one-get-one-free” and app team will get find the "pz-50" from the URL. After that call the API and show all details regarding the offer. You just need to paste above code in your JS file, replace the URL details that’s it. This will first open the and if the app was not installed then it will open the app/play store. JS code was done so that it’ll automatically close the Facebook browser.
Step#4 ➡️ Handle the schema in a mobile application.
// iOS Swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { if let userActivityDictionary = launchOptions?[UIApplication.LaunchOptionsKey.userActivityDictionary] as? [UIApplication.LaunchOptionsKey: Any], let userActivity = userActivityDictionary.values.map({ $0 as? NSUserActivity }).compactMap({$0}).first, let webpageURL = userActivity.webpageURL { self.prepareToHandleUniversalLink(url: webpageURL) }else if let url = launchOptions?[UIApplication.LaunchOptionsKey.url] as? URL { //Your redirection logic } return true } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool { //Your redirection logic return true } //MARK:- Dynamic linking extension AppDelegate { func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { //Your redirection logic return true } } // MARK: Universal Link extension AppDelegate { func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { if let url = userActivity.webpageURL { //Your redirection logic } return true }
// Android // intent filter in AndroidManifest.xml <intent-filter android:autoVerify="true"> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.OPENABLE"/> <category android:name="android.intent.category.BROWSABLE"/> <data android:host="codezma.page.link" android:scheme="https"/> <data android:host="share" android:scheme="codezma"/> </intent-filter> // After fetching the data from intent intent?.dataString?.split("/") returns a List<String> codezma://share/pizza/pz-50/buy-one-get-one-free /** * Here you get list of all keys in array. * You will get data like below * [ * 0 => share * 1 => pizza * 2 => pz-50 <------- This is your ID of Offer * 3 => buy-one-get-one-free * ] */
Step#5 ➡️ That’s it ?. If you like this blog in that case share this blog with your colleagues and friends.