API Transactional Track & Engage Push
Javascript

Intro

This document will help the developer/client creating the necessary information to configure certificates and API keys necessary to configure the E-Goi Push Channel.

E-Goi Push Channel is a new communication channel integrated in the E-goi communication mechanism where the client is able to send Push Notification to the devices that are running a given App.

Push Notification is a small message that can contain information and start some activity in the App that is installed in the user device. It’s possible to track some events and present them in statistics to the client.

Integrate the Push Channel into an App it’s quite easy. Just download the Framework, copy to the project and add the credentials given from the E-goi site (explained step-by-step in the documentation).

Before integrate the Frameworks (assuming that will be used in iOS and Android) is necessary to create the iOS certificate and the Google API Key for authentication in their servers, to send the Push Notification.

#Android

Android

Key

To send Push Notifications to an Android device, it’s necessary to have the App registered.

Create new Project

Create project
Project number

Now the GCM is enabled for this project.

Menu

Will be present the next screen:

Options screen
Create new key
Create server key
The API key

Configuration

1 - Download our library and add it to the project.

2 - Add Firebase Messaging to your App

Firebase
Firebase
Firebase

At this moment your App has Firebase configured.

If you want to add manually please follow the official Google Documentation (https://firebase.google.com/docs/android/setup#manually_add_firebase)

3 - Create a Class that extends Application (android.app.Application)

Ensure that you add this class to the Manifest)

public class App extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    try {
      // Setup with your credentials
      EGoiPush.shared().setAppId(0); // Your E-Goi App ID
      EGoiPush.shared().setTwoStepsField("uid"); // The two steps field
      EGoiPush.shared().setApiKey("your_api_key");
      EGoiPush.shared().setContext(this);
      EGoiPush.shared().loadToken();

      /*
      // Only if you added Firebase manually
      FirebaseOptions.Builder options = new FirebaseOptions.Builder();
      options.setApiKey(Your_Firebase_Project_API_KEY);
      options.setApplicationId(Your_Firebase_App_ID);
      FirebaseApp.initializeApp(this, options.build());
      Log.d("Firebase", "Library inited");
      */

    } catch (Exception ex) {
      Log.d(Utils.TAG, ex.getLocalizedMessage());
    }
  }
}

4 - Add permissions to the App’s Manifest

<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" tools:ignore="MockLocation" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />

<!-- Add the info to the application tag -->
<application android:name=".app.App" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme">

<!-- Declare the services in the manifest -->
<activity android:name=".activities.Home">
  <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <action android:name="FIREBASE_ACTIVITY" />
    <category android:name="android.intent.category.LAUNCHER" />
    <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>
</activity>

<activity android:name=".activities.PushWebView" android:screenOrientation="portrait" />
<activity android:name=".activities.PushHandlerActivity" android:screenOrientation="portrait" />

<!-- [START Geofence service] -->
<service android:name=".model.egoipush.geofence.GeoFenceService" android:enabled="true" />
<receiver android:name=".model.egoipush.geofence.ProximityIntentReceiver" android:enabled="true">
  <intent-filter>
    <action android:name="android.location.MODE_CHANGED" />
    <action android:name="android.intent.action.BOOT_COMPLETED" />
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
  </intent-filter>
</receiver>
<!-- [END Geofence service] -->

<!-- [START firebase_service] -->
<service android:name=".model.egoipush.core.PushMessagingService">
  <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT" />
  </intent-filter>
</service>
<!-- [END firebase_service] -->

<!-- [START firebase_iid_service] -->
<service android:name=".model.egoipush.core.TokenManager">
  <intent-filter>
    <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
  </intent-filter>
</service>
<!-- [END firebase_iid_service] -->

<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/icon" />

<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming notification message. See README(https://goo.gl/6BKBk7) for more. -->
<meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/colorAccent" />

5 - In your Main Activity you can request access to location and register the device

Also in the Main Activity you have the methods to handle the push notification and to start the Geofence service (if you want to use that).

Example of the MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_home);
  Button registerButton = findViewById(R.id.registerButton);
  registerButton.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {
      registerDevice();
    }
  });

  Button locationButton = findViewById(R.id.locationButton);
  
  locationButton.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {
      requestLocation();
    }
  });

  startService(new Intent(this, GeoFenceService.class));
}

@Override
protected void onStart() {
  super.onStart();
  Intent intent = getIntent();
  if (null != intent) {
    checkPush(intent);
  }
}

@Override
protected void onRestart() {
  super.onRestart();
  Intent intent = getIntent();
  if (null != intent) {
    checkPush(intent);
  }
}

/**
* Push methods
*/
private void checkPush(Intent intent) {
  if (null == intent) {
    return;
  }

  String data = null;
  if (getIntent().getExtras() != null) {
    for (String key : getIntent().getExtras().keySet()) {
      Object value = getIntent().getExtras().get(key);
      Log.d("MainActivity", "Key: " + key + " Value: " + value);
      if (key.equalsIgnoreCase(Configuration.EGoiDataPushKey)) {
        if (null != value) {
          data = value.toString();
        }
        intent.removeExtra(Configuration.EGoiDataPushKey);
      }
    }
  }

  if (null != data) {
    Intent newIntent = new Intent(Home.this, PushHandlerActivity.class);
    newIntent.putExtra(Configuration.EGoiPushKey, data);
    startActivity(newIntent);
  }
}

private void requestLocation() {
  EGoiPush.shared().requestLocationAuthorization(Home.this);
}

private void registerDevice() {
  AlertDialog.Builder alertDialog = new AlertDialog.Builder(Home.this);
  alertDialog.setTitle("Registar");
  alertDialog.setMessage("Insira o seu email");
  final EditText input = new EditText(Home.this);
  LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
  LinearLayout.LayoutParams.MATCH_PARENT,
  LinearLayout.LayoutParams.MATCH_PARENT);
  input.setLayoutParams(lp);
  alertDialog.setView(input);
  alertDialog.setPositiveButton("Registar",
  
  new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
      String email = input.getText().toString();
      registerInServer(email.equalsIgnoreCase("") ? null : email);
    }
  });
  alertDialog.setNegativeButton("Cancelar",
  
  new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
      dialog.cancel();
    }
  });
  alertDialog.show();
}

private void registerInServer(String value) {
  EGoiPush.shared().registerDevice(value, new Interfaces.RegisterDeviceInterface() {
    @Override
    public void callback(Boolean success) {
      if (success) {
        showSuccessMessage("Device registered");
      } else {
        showErrorAlert("Error registering device");
      }
    }
  });
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
  if (requestCode == EGoiPush.MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
      EGoiPush.shared().requestLocationAuthorization(Home.this);
    } else {
      showErrorAlert("Permition to use location services not granted!");
    }
  }
}

6 - Your App is ready to receive push notifications

Please ensure you request access to user location and register the device in the E-Goi platform.

SDK

Download Android SDK

iOS

Configuration

1 - Download our library.

2 - Add the library to your iOS project

Library overview

3 - Add the Push Notification Capability in the Capabilities Tab

Capabilities Tab

4 - If you want to use the Geolocation feature ensure that:

4.1 - You enabled the background modes in the project

background modes

4.2 - Add to your info.plist the next keys (because the App needs to ask permissions to the user to user his location):

plist overview

5 - In the AppDelegate file, init the Library with your information (App Id, EGoi Api Key and two steps field name, case exists)

Init the Library with your information

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  // Configure framework with app id and field
  EGoiPush.shared.appId = 255
  EGoiPush.shared.twoStepsField = "uid"
  EGoiPush.shared.apiKey = "your_egoi_api_key"
  application.applicationIconBadgeNumber = 0
  return true
}

6 - Call the library functions to handle the Push Notifications events

Call the library functions to handle the Push Notifications events

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  EGoiPush.shared.didRegisterForRemoteNotificationsWithDeviceToken(token: deviceToken)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
  EGoiPush.shared.didReceiveRemoteNotification(userInfo: userInfo) {
    Log.d("Received push notification")
  }
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  EGoiPush.shared.didReceiveRemoteNotification(userInfo: userInfo) {
    completionHandler(.newData)
    Log.d("Received push notification with completion")
  }
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  EGoiPush.shared.didFailToRegisterForRemoteNotificationsWithError(error: error)
}

func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
  EGoiPush.shared.didReceiveLocalNotification(notification: notification) {
    Log.d("Received push notification with completion")
  }
}

7 - In your, when you decide that it’s fine to ask for notifications and location updates, just call:

Ask for notifications and location updates

// Request authorization for access location
EGoiPush.shared.requestLocationAuthorization {
  Log.d("Finished requesting location authorization")
}

// Request authorization for push notification
EGoiPush.shared.requestAuthorization { (success, error) in
  Log.d("Finished requesting push notification authorization")
}

8 - Your iOS App is ready to receive Push Notifications from E-Goi :)

Certificate

To use the APNs (Apple Push Notification Server) it’s necessary to generate a certificate request that will be used to create the development SSL certificate.

1 - Generating a Certificate Request

To create this certificate do the next steps:

Request Certificate
Save to disk

2 - Create an App ID

The App ID it’s the identifier used by your App, that is unique. Every App has it’s own App ID. It’s impossible that two different apps use the same App ID. To create the App ID log in into the iOS Dev Center (https://developer.apple.com/devcenter/ios/index.action) and choose the option “Certificates, Identifiers and Profiles”:

iOS Dev Center
Select identifiers
Add new app
Enter informations

3 - Configure Push Notifications for the App

Now, with the App ID, we can proceed to the Push Notification configuration.

Edit Push
Edit Information
Creating a certificate
Choose file
The certificate

4 - Create the Provisioning Profile

To test the Push Channel in a real device it’s necessary to configure an Provisioning Profile (push notifications don’t work in the simulator).

Provisioning profile menu

Add a new Provisioning Profile selecting “iOS App Development” (if release mode you should create the production certificate, App Store):

Create PP
Select App ID
Select devices were you can test
Name PP and save it

SDK

Download iOS SDK