Code Monkey home page Code Monkey logo

edparsons / cordova-ionic-phonegap-deferred-deep-linking-sdk Goto Github PK

View Code? Open in Web Editor NEW

This project forked from branchmetrics/cordova-ionic-phonegap-branch-deep-linking-attribution

0.0 1.0 0.0 2.66 MB

The Cordova SDK for deferred deep linking shares the same code base as the Branch Web SDK, and includes functions to call all of the same API endpoints. Branch helps mobile apps grow with deep links / deeplinks that power referral systems, sharing links and invites with full attribution and analytics.

Home Page: https://dev.branch.io/references/cordova_phonegap_sdk/

License: MIT License

Makefile 2.15% Java 16.26% Objective-C 11.23% Shell 2.15% CSS 0.61% HTML 3.61% JavaScript 64.00%

cordova-ionic-phonegap-deferred-deep-linking-sdk's Introduction

Branch Cordova/Phonegap/Ionic SDK

This documentation outlines the functionality of the Branch Metrics Cordova SDK, and how to easily incorporate it into a Cordova app. The Cordova SDK shares the same code base as the Branch Web SDK, and includes functions to call all of the same API endpoints.


Demo App

This repo includes a sample app, that demonstrates all of the available methods in the Branch Cordova SDK. Building this app is very simple:

  1. Switch to the Cordova dir: $ cd cordova-testbed
  2. Run the init script to install all the required plugins
  3. $ ./init.sh
  4. Build the Cordova app and launch in the iOS emulator
  5. $ cordova emulate ios

Quick Install of Cordova/Phonegap SDK

The plugin can be added in a number of ways. You can grab that latest version on the master Branch by using this call.

cordova plugin add https://github.com/BranchMetrics/Cordova-Ionic-PhoneGap-Deferred-Deep-Linking-SDK.git

If you want to use NPM to manage your packages, the Branch Cordova SDK is also an NPM module.

npm install branch-cordova-sdk

Configure your app for deep linking

Android: Register a URI Scheme and add your Branch key

In your project's manifest file, you can register your app to respond to direct deep links (yourapp:// in a mobile browser) by adding the second intent filter block. Also, make sure to change yourapp to a unique string that represents your app name.

Secondly, make sure that this activity is launched as a singleTask. This is important to handle proper deep linking from other apps like Facebook.

<activity
    android:name=".TestbedActivity"
    android:label="@string/app_name"
    <!-- Make sure the activity is launched as "singleTask" -->
    android:launchMode="singleTask">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <!-- Add this intent filter below, and change yourapp to your app name -->
    <intent-filter>
        <data android:scheme="yourapp" android:host="open" />
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
    </intent-filter>
</activity>

After you register your app, your Branch key can be retrieved on the Settings page of the dashboard. Add it (them, if you want to do it for both your live and test apps) to your project's manifest file as a meta data.

Edit your manifest file to have the following items:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="io.branch.sample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application>
        <!-- Other existing entries -->

        <!-- Add this meta-data below, and change "key_live_xxxxxxx" to your actual live Branch key -->
        <meta-data android:name="io.branch.sdk.BranchKey" android:value="key_live_xxxxxxx" />

        <!-- For your test app, if you have one; Again, use your actual test Branch key -->
        <meta-data android:name="io.branch.sdk.BranchKey.test" android:value="key_test_yyyyyyy" />
    </application>
</manifest>

iOS: Register a URI Scheme and add your Branch key

In your project's YourProject-Info.plist file:

  1. You can register your app to respond to direct deep links (yourapp:// in a mobile browser) by adding CFBundleURLTypes block. Also, make sure to change yourapp to a unique string that represents your app name. In https://dashboard.branch.io/#/settings/link, tick I have an iOS App checkbox and enter your URI Scheme (e.g.: yourapp://) into the text box.
  2. Add your Branch key found on the settings page here https://dashboard.branch.io/#/settings
<dict>
  
  <!-- Add branch key as key-value pair -->
  <key>branch_key</key>
  <string>key_live_xxxxxxxxxxxxxxx</string>

  <!-- Add unique string for direct deep links -->
  <key>CFBundleURLTypes</key>
  <array>
    <dict>
      <key>CFBundleURLSchemes</key>
      <array>
        <string>yourapp</string>
      </array>
    </dict>
  </array>

  ... other stuff
</dict>

iOS: Enable Universal Links

In iOS 9.2, Apple dropped support for URI scheme redirects. You must enable Universal Links if you want Branch-generated links to work in your iOS app. To do this:

  1. enable Associated Domains capability on the Apple Developer portal when you create your app's bundle identifier.
  2. In https://dashboard.branch.io/#/settings/link, tick the Enable Universal Links checkbox and provide the Bundle Identifier and Apple Team ID in the appropriate boxes.
  3. Finally, create a new file named Entitlements.plist in the root directory of your project with the associated-domains key like below. You may add more entitlement keys if you have any.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.developer.associated-domains</key>
    <array>
        <string>applinks:bnc.lt</string>
    </array>
</dict>
</plist>

Initialization and Session Management

You should initialize the Branch SDK session once the ‘deviceready’ event fires and each time the ‘resume’ event fires. See the example code below. You will need your Branch Key from the Branch dashboard.

  branch.init("YOUR BRANCH KEY HERE", function(err, data) {
    app.initComplete(err, data);
  });

Here's an example of a healthy integration:

onDeviceReady: function() {
    branch.setDebug(true);
    document.addEventListener('resume', app.onResume, false);
    branch.init(app.branch_key, { isReferrable: true }, function(err, data) {
        // call completion handler with data
    });
},

onResume: function() {
    branch.init(app.branch_key, { isReferrable: true }, function(err, data) {
        // call completion handler with data
    });
},

If branch.init() fails, all subsequent branch methods will fail.


API Reference

  1. Branch Session
  1. Event Tracking
  1. Deep Linking
  1. Referrals and Credits

setDebug(debug)

Parameters

debug: boolean, required - Set the SDK debug flag.

Setting the SDK debug flag will generate a new device ID each time the app is installed instead of possibly using the same device id. This is useful when testing.

This needs to be set before the Branch.init call!!!


init(branch_key, options, callback)

Parameters

branch_key: string, required - Your Branch live key, or (depreciated) your app id.

options: Object, optional - { isReferrable: Is this a referrable session }.

callback: function, optional - callback to read the session data.

Usage
branch.init(
    branch_key,
    options,
    callback (err, data),
);
Callback Format
callback(
     "Error message",
     {
          data_parsed:        { },                          // If the user was referred from a link, and the link has associated data, the data is passed in here.
          referring_identity: '12345',                      // If the user was referred from a link, and the link was created by a user with an identity, that identity is here.
          has_app:            true,                         // Does the user have the app installed already?
          identity:           'BranchUser',                 // Unique string that identifies the user
          referring_link:     'https://bnc.lt/c/jgg75-Gjd3' // The referring link click, if available.
     }
);

Note: branch.init must be called prior to calling any other Branch functions.


data(callback)

Parameters

callback: function, optional - callback to read the session data.

Returns the same session information and any referring data, as Branch.init, but does not require the app_id. This is meant to be called after Branch.init has been called if you need the session information at a later point. If the Branch session has already been initialized, the callback will return immediately, otherwise, it will return once Branch has been initialized.


first(callback)

Parameters

callback: function, optional - callback to read the session data.

Returns the same session information and any referring data, as Branch.init did when the app was first installed. This is meant to be called after Branch.init has been called if you need the first session information at a later point. If the Branch session has already been initialized, the callback will return immediately, otherwise, it will return once Branch has been initialized.


setIdentity(identity, callback)

Parameters

identity: string, required - a string uniquely identifying the user - often a user ID or email address.

callback: function, optional - callback that returns the user's Branch identity id and unique link.

Formerly identify()

Sets the identity of a user and returns the data. To use this function, pass a unique string that identifies the user - this could be an email address, UUID, Facebook ID, etc.

Usage
branch.setIdentity(
    identity,
    callback (err, data)
);
Callback Format
callback(
     "Error message",
     {
          identity_id:             '12345', // Server-generated ID of the user identity, stored in `sessionStorage`.
          link:                    'url',   // New link to use (replaces old stored link), stored in `sessionStorage`.
          referring_data_parsed:    { },      // Returns the initial referring data for this identity, if exists, as a parsed object.
          referring_identity:      '12345'  // Returns the initial referring identity for this identity, if exists.
     }
);

logout(callback)

Parameters

callback: function, optional

Logs out the current session, replaces session IDs and identity IDs.

Usage
branch.logout(
    callback (err)
);
Callback Format
callback(
     "Error message"
);

close(callback)

Parameters

callback: function, optional

Close the current session.

Usage
branch.close(
    callback (err)
);
Callback Format
callback(
     "Error message"
);

Tracking events

track(event, metadata, callback)

Parameters

event: string, required - name of the event to be tracked.

metadata: Object, optional - object of event metadata.

callback: function, optional

This function allows you to track any event with supporting metadata. Use the events you track to create funnels in the Branch dashboard. The metadata parameter is a formatted JSON object that can contain any data and has limitless hierarchy.

Usage
branch.track(
    event,
    metadata,
    callback (err)
);
Callback Format
callback("Error message");

Deeplinking Methods

Creating a deep linking link

link(data, callback)

Parameters

data: Object, required - link data and metadata.

callback: function, required - returns a string of the Branch deep linking URL.

Formerly createLink()

Creates and returns a deep linking URL. The data parameter can include an object with optional data you would like to store, including Facebook Open Graph data.

data The dictionary to embed with the link. Accessed as session or install parameters from the SDK.

Note You can customize the Facebook OG tags of each URL if you want to dynamically share content by using the following optional keys in the data dictionary. Please use this Facebook tool to debug your OG tags!

Key Value
"$og_title" The title you'd like to appear for the link in social media
"$og_description" The description you'd like to appear for the link in social media
"$og_image_url" The URL for the image you'd like to appear for the link in social media
"$og_video" The URL for the video
"$og_url" The URL you'd like to appear
"$og_redirect" If you want to bypass our OG tags and use your own, use this key with the URL that contains your site's metadata.

Also, you can set custom redirection by inserting the following optional keys in the dictionary:

Key Value
"$desktop_url" Where to send the user on a desktop or laptop. By default it is the Branch-hosted text-me service
"$android_url" The replacement URL for the Play Store to send the user if they don't have the app. Only necessary if you want a mobile web splash
"$ios_url" The replacement URL for the App Store to send the user if they don't have the app. Only necessary if you want a mobile web splash
"$ipad_url" Same as above but for iPad Store
"$fire_url" Same as above but for Amazon Fire Store
"$blackberry_url" Same as above but for Blackberry Store
"$windows_phone_url" Same as above but for Windows Store
"$after_click_url" When a user returns to the browser after going to the app, take them to this URL. iOS only; Android coming soon

You have the ability to control the direct deep linking of each link as well:

Key Value
"$deeplink_path" The value of the deep link path that you'd like us to append to your URI. For example, you could specify "$deeplink_path": "radio/station/456" and we'll open the app with the URI "yourapp://radio/station/456?link_click_id=branch-identifier". This is primarily for supporting legacy deep linking infrastructure.
"$always_deeplink" true or false. (default is not to deep link first) This key can be specified to have our linking service force try to open the app, even if we're not sure the user has the app installed. If the app is not installed, we fall back to the respective app store or $platform_url key. By default, we only open the app if we've seen a user initiate a session in your app from a Branch link (has been cookied and deep linked by Branch).

Usage

branch.link(
    data,
    callback (err, link)
);

Example

branch.link({
    tags: [ 'tag1', 'tag2' ],
    channel: 'facebook',
    feature: 'dashboard',
    stage: 'new user',
    data: {
        mydata: 'something',
        foo: 'bar',
        '$desktop_url': 'http://myappwebsite.com',
        '$ios_url': 'http://myappwebsite.com/ios',
        '$ipad_url': 'http://myappwebsite.com/ipad',
        '$android_url': 'http://myappwebsite.com/android',
        '$og_app_id': '12345',
        '$og_title': 'My App',
        '$og_description': 'My app\'s description.',
        '$og_image_url': 'http://myappwebsite.com/image.png'
    }
}, function(err, link) {
    console.log(err, link);
});
Callback Format
callback(
    "Error message",
    'https://bnc.lt/l/3HZMytU-BW' // Branch deep linking URL
);

Referral system rewarding functionality

In a standard referral system, you have 2 parties: the original user and the invitee. Our system is flexible enough to handle rewards for all users for any actions. Here are a couple example scenarios:

  1. Reward the original user for taking action (eg. inviting, purchasing, etc)
  2. Reward the invitee for installing the app from the original user's referral link
  3. Reward the original user when the invitee takes action (eg. give the original user credit when their the invitee buys something)

These reward definitions are created on the dashboard, under the 'Reward Rules' section in the 'Referrals' tab on the dashboard.

Warning: For a referral program, you should not use unique awards for custom events and redeem pre-identify call. This can allow users to cheat the system.

Retrieve referrals list

referrals(callback)

Parameters

callback: function, required - returns an object with referral data.

Formerly showReferrals()

Retrieves a complete summary of the referrals the current user has made.

Usage
branch.referrals(
    callback (err, data)
);
Callback Format
callback(
    "Error message",
    {
        'install': {
             total: 5,
             unique: 2
        },
        'open': {
             total: 4,
             unique: 3
        },
        'buy': {
            total: 7,
            unique: 3
        }
    }
);

Referral Codes

getCode(options, callback)

Parameters

options: Object, required - contins options for referral code creation.

callback: function, optional - returns an error if unsuccessful

Create a referral code using the supplied parameters. The code can be given to other users to enter. Applying the code will add credits to the referrer, referree or both. The options object can containt the following properties:

Key Value
amount reqruied - An integer specifying the number of credits added when the code is applied.
calculation_type required - An integer of 1 for unlimited uses, or 0 for one use.
location required - An integer that determines who gets the credits: 0 for the referree, 2 for the referring user or 3 for both.
bucket optional - The bucket to apply the credits to. Defaults to "default".
prefix optional - A string to be prepended to the code.
expiration optional - A date string that if present, determines the date on which the code expires.
Usage

branch.getCode( options, callback(err,data) );

Example
branch.getCode(
    {
      "amount":10,
      "bucket":"party",
      "calculation_type":1,
      "location":2
    },
    callback (err, data)
);
Callback Format
callback(
     "Error message",
     {
       "referral_code":"AB12CD"
     }
);

validateCode(code, callback)

Parameters

code: string, required - the code string to validate.

callback: function, optional - returns an error if unsuccessful

Validate a referral code before using.

Usage
branch.validateCode(
    code, // The code to validate
    callback (err)
);
Example
branch.validateCode(
    "AB12CD",
    function(err) {
        if (err) {
            console.log(err);
        }
        else {
            console.log("Code is valid");
        }
    }
);
Callback Format
callback(
    "Error message",
    callback(err)
);

applyCode(code, callback)

Parameters

code: string, required - the code string to apply.

callback: function, optional - returns an error if unsuccessful

Apply a referral code.

Usage
branch.applyCode(
    code, // The code to apply
    callback (err)
);
Example
branch.applyCode(
    "AB12CD",
    function(err) {
        if (err) {
            console.log(err);
        }
        else {
            console.log("Code applied");
        }
    }
);
Callback Format
callback(
    "Error message",
    callback(err)
);

Credit Functions

credits(callback)

Parameters

callback: function, required - returns an object with credit data.

Formerly showCredits()

This call will retrieve the entire history of credits and redemptions from the individual user.

Usage
branch.credits(
    callback (err, data)
);
Callback Format
callback(
    "Error message",
    {
        'default': 15,
        'other bucket': 9
    }
);

creditHistory(options, callback)

Parameters

options: Object, optional - options controlling the returned history.

callback: function, required - returns an array with credit history data.

This call will retrieve the entire history of credits and redemptions from the individual user. Properties available in the options object:

Key Value
bucket optional (max 63 characters) - The bucket from which to retrieve credit transactions.
begin_after_id optional - The credit transaction id of the last item in the previous retrieval. Retrieval will start from the transaction next to it. If none is specified, retrieval starts from the very beginning in the transaction history, depending on the order.
length optional - The number of credit transactions to retrieve. If none is specified, up to 100 credit transactions will be retrieved.
direction optional - The order of credit transactions to retrieve. If direction is 1, retrieval is in least recent first order; If direction is 0, or if none is specified, retrieval is in most recent first order.
Usage
branch.creditHistory(
     options,
     callback(err, data)
);
Example
branch.creditHistory(
    {
      "length":50,
      "direction":0,
      "begin_after_id":"123456789012345",
      "bucket":"default"
    }
    callback (err, data)
);
Callback Format
callback(
    "Error message",
[
    {
        "transaction": {
                           "date": "2014-10-14T01:54:40.425Z",
                           "id": "50388077461373184",
                           "bucket": "default",
                           "type": 0,
                           "amount": 5
                       },
        "referrer": "12345678",
        "referree": null
    },
    {
        "transaction": {
                           "date": "2014-10-14T01:55:09.474Z",
                           "id": "50388199301710081",
                           "bucket": "default",
                           "type": 2,
                           "amount": -3
                       },
        "referrer": null,
        "referree": "12345678"
    }
]
);

Credit redemption

redeem(amount, bucket, callback)

Parameters

amount: number, required - an amount (int) of number of credits to redeem

bucket: string, required - the name of the bucket (string) of which bucket to redeem the credits from

callback: function, optional - returns an error if unsuccessful

Formerly redeemCredits()

Credits are stored in buckets, which you can define as points, currency, whatever makes sense for your app. When you want to redeem credits, call this method with the number of points to be redeemed, and the bucket to redeem them from.

branch.redeem(
    amount, // Amount of credits to be redeemed
    bucket,  // String of bucket name to redeem credits from
    callback (err)
);
Example
branch.redeem(
    5,
    "Rubies",
    function(err) {
        console.log(err);
    }
);
Callback Format
callback("Error message");

Bugs / Help / Support

Feel free to report any bugs you might encounter in the repo's issues. Any support inquiries outside of bugs please send to [email protected].

cordova-ionic-phonegap-deferred-deep-linking-sdk's People

Contributors

aaustin avatar austinhay avatar csolallo avatar jakecadams avatar jasondavis25 avatar jsaleigh avatar kirkkt avatar scotthasbrouck avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.