TABLE OF CONTENTS

Pre Requisites

Flutter v1.10.0 and above will be supported from Freshchat SDK.


Get your APP ID, APP Key and Domain

Your Freshchat account is associated with a unique APP ID and APP key which is used to integrate your mobile SDK with Freshchat.


Login to your Freshchat account as Account Owner/Admin. 

Go to Admin > Mobile SDK. You can find your APP ID, APP Key and Domain here. 



1. Add Freshchat SDK to your project

  1. Freshchat plugin name is ‘freshchat_sdk’.

  2. In your flutter project’s pubspec.yaml file, under dependencies add 

    freshchat_sdk: "{{latest-version}}"


For latest SDK version please refer the following link: 

https://pub.dev/packages/freshchat_sdk


1.1. iOS Setup

Run below command to autolink the SDK 

cd ios 
pod install

1.2. Android Setup

When app targets Android 7.0+ and Image attachment is enabled, FileProvider needs to be configured.

Include the provider in the AndroidManifest.xml as below.

AndroidManifest.xml

<provider
   android:name="androidx.core.content.FileProvider"
    android:authorities="com.example.demoapp.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/freshchat_file_provider_paths" />
</provider>


Strings.xml

<string name="freshchat_file_provider_authority">com.example.demoapp.provider
</string>


2. Initialization of SDK

Invoke Freshchat.init() with your app id, app key and domain before invoking/ attempting to use any other features of Freshchat SDK.  


We highly recommend invoking init() from your app's launcher / support screen launch. Freshchat SDK checks for presence of its components during init() and will warn about missing components when it detects the components are missing or their manifest entries are missing. 


Replace the YOUR-APP-ID, YOUR-APP-KEY and YOUR-DOMAIN in the following code snippet with the actual app ID and app key.

Freshchat.init(YOUR-APP-ID, YOUR-APP-KEY,YOUR-DOMAIN);


2.1 Config Options for Initialization

Enable or disable features like camera capture by adding the optional parameters for the specific config


Freshchat.init(YOUR-APP-ID, YOUR-APP-KEY,YOUR-DOMAIN,
          teamMemberInfoVisible:true,
          cameraCaptureEnabled:true,
          gallerySelectionEnabled:true,
          responseExpectationEnabled:true,
          showNotificationBanner:true,
                                       notificationSoundEnabled: true);


3. User Information


3.1 Updating User Information

You can send basic user information at any point to give you more context on the user when your support agents are messaging back and forth with them. 

import 'package:freshchat_sdk/freshchat_user.dart';
FreshchatUser freshchatUser;
freshchatUser.setFirstName("John");
freshchatUser.setLastName("Doe");
freshchatUser.setEmail("johndoe@dead.man");
freshchatUser.setPhone("+91","1234234123");
Freshchat.setUser(freshchatUser);


3.2 Updating User Properties (Meta Data)

You can capture and send additional metadata about the user and the events in the app, all of which also becomes a way to segment your users to later push messages to them. 

 

var userPropertiesJson = {
   "user_type": "Paid",
   "plan": "Gold"
}
Freshchat.setUserProperties(userPropertiesJson);



3.3 Log User Events in Timeline

Tracking user events provides more insight and context about the user(s) in your application. Events like user actions, failure/error cases can be tracked using this API. Tracked events are listed under Events Timeline on the agent side.

var eventName = "Visited Order Details page";
var eventProperties = {"Order Id": 3223232332,
                       "Order Date": "24 Jan 2020",
                       "Order Status ": "In-Transit"};
Freshchat.trackEvent(eventName,
                    properties: eventProperties);


3.4 Reset User Data

Reset user data at logout or when deemed appropriate based on user action in the app by invoking the resetUser API. 


Freshchat.resetUser();


3.4 Restore user

For retaining the chat messages across devices/sessions/platforms, the mobile app needs to pass the same external id and restore id combination for the user. This will allow users to seamlessly pick up the conversation from any of the supported platforms - Android, iOS and Web.


  • External Id - This should (ideally) be a unique identifier for the user from your system like a user id or email id etc and is set using the Freshchat.identifyUser() API. This cannot be changed once set for the user

  • Restore Id - This is generated by Freshchat for the current user, given an external id was set and can be retrieved anytime using the user = Freshchat.getUser() and user.getRestoreId() API. The app is responsible for storing and later present the combination of external id and restore id to the Freshchat SDK to continue the chat conversations across sessions on same device or across devices and platforms.


Note

  • Restore Id for a user is typically generated only when user has sent a message.

  • Notifications are supported in only one mobile device at any point in time and is currently the last restored device or device with last updated push token


To set external id 


Freshchat.identifyUser(externalId:"EXTERNAL_ID");


To retrieve the restore id


FreshchatUser user = Freshchat.getUser();
var restoreId = user.getRestoreId();


To lookup and restore user by external id and restore id


Freshchat.identifyUser(externalId:"EXTERNAL_ID",restoreId:"RESTORE_ID");


To listen to restore id generated event

Restore Id generation is an asynchronous process. So you need to open a stream to onRestoreIdGenerated to get notified when restore id is generated. This stream can be listened at listen and unregistered at cancel of your restore stream and stream subscription of the listener respectively.


Register for restore id generated event


var restoreStream = Freshchat.onRestoreIdGenerated;
var restoreStreamSubscription = restoreStream.listen((event){
    FreshchatUser user = Freshchat.getUser();
    var restoreId = user.getRestoreId();
    var externalId = user.getExternalId();
});


3.5 Get Freshchat User ID

You can get your user's unique identifier using getUserAlias API.


Freshchat.getUserAlias();


4. Launching the Support Solution

Use the snippets below to launch into the FAQ or Conversation based support experience from a call to action in your app. Your call to action or entry point could be an on-screen button or a menu item.


4.1 Conversations

In response to a specific UI events like a menu selection or button on click event, invoke the showConversations() API to launch the Conversation Flow. If the app has multiple channels configured, the user will see the channel list. Channel list is ordered as specified in the Dashboard (link to channel list in dashboard) when there are no messages. When messages are present, the order is based on most recently used first 


Note

Only Message Channels with visibility set to "Visible to all users" will be displayed when using showConversations() API

 

Launching Conversation List from click of a button in your app's screen


Freshchat.showConversations();


4.1.1 Filtering Conversation Channels

To filter and display only Message Channels tagged with a specific term, use the optional parameters in the showConversations API

Eg: To link and display only specific Message Channels from say orders page in your app, those specific Message Channels can be tagged with the term "order_queries".


Freshchat.showConversations(filteredViewTitle:"Premium Support",tags:["premium"]);


Note

  • If no matching channel is found, the user will be redirected to default channel. 

  • Message Channels which are normally not visible when using showConversations() API, will also be displayed when tagged and the specific tag is passed to filterByTags API of ConversationOptions instance passed to showConversations() API.


4.1.2 Unread Count

If you would like to obtain the number of unread messages for the user at app launch or any other specific event, use the getUnreadCountAsync API and display the count.

void getUnreadCount async{
    var unreadCount = await Freshchat.getUnreadCountAsync
}


4.2. FAQ

In response to specific UI events like a menu selection or button on click event, invoke the showFAQs() API to launch the FAQ screen.By default the FAQ Categories is displayed as a grid with a “Contact Us” button at the bottom. For customising this, check the FAQ Options.

Freshchat.showFAQ();


4.2.1 FAQs Options

Customizations to the FAQ Flow can be achieved by specifying the relevant options in the optional parameters for customization passed to the showFAQs() API.


Freshchat.showFAQ(faqTitle:"Tags", faqTags:["premium"],faqFilterType: FaqFilterType.Article );


faqTitle - title given to the result list page of the filter applied. 

faqTags - name of the tags based on which filter gets applied. 

faqFilterType - Category/Article. Category - combination of articles and sub categories. Article - contains only articles.


Note

When there is no match on the filter applied, it will display all the FAQ categories by default.


4.2.2 Filtering FAQ categories by tags

To filter and display only FAQ Categories tagged with a specific term, use the faqFilterType parameter with value as enum FaqFilterType.Category passed to showFAQs() API as below.


Eg: To display FAQ Categories related to specific user type, those specific FAQ Categories can be tagged with the term "premium".


Freshchat.showFAQs(faqTags:["premium"],faqFilterType: FaqFilterType.Category );


4.2.3 Filtering FAQ articles by tags

To filter and display only FAQs tagged with a specific term, use the faqFilterType parameter with value as enum FaqFilterType.Article passed to showFAQs() API as below.


Note

FAQs also inherit the tags from the parent FAQ Category.


Eg: To link to FAQs related to payment failure, those specific FAQs can be tagged with the term "payment_failure" and can be linked to from Payments page in the app.


Freshchat.showFAQs(faqTags:["payment_failure"],faqFilterType: FaqFilterType.Article);


4.2.4 Filter Message Channels displayed on clicking "Contact Us" in FAQs by tags

To filter and display only Message Channels tagged with a specific term when user clicks "Contact Us"in FAQ screens,  use the contactUsTags parameter with value as List of tags passed to showFAQs() API as below.


Note

The default behaviour for "Contact Us" from within FAQ flow is same as invoking showConversations() i.e it will display all channels that are marked "Visible to all users", except when filtering of channels is enabled by passing tags to filterContactUsByTags API.


Eg: To display Message Channels related to specific section of FAQ show, those specific Message Channels can be tagged with the term "payment_failure".

Freshchat.showFAQs(faqTitle:"Payments",
                   faqTags:["payment_failure"],
                   faqFilterType:FaqFilterType.Article,
                   showFaqCategoriesAsGrid:true,
                   showContactUsOnFaqScreens:true,
                   showContactUsOnFaqNotHelpful:true,
                   contactUsTags:["payments"]);


5. Send message API

The app can send a message on behalf of the user using the sendMessage() API. 


Note

This API would silently send a message and not launch the Freshchat SDK UI


Eg: To send a message on a channel tagged "premium", the API can be invoked as below.

String tag = "premium";
String message = "text message";
Freshchat.sendMessage(tag,message);


6. Push Notifications

Integrating Freshchat push notification in your application will help users receive your support messages quicker.


6.1.1 Server side integration


Android

In Firebase Console Under your project go to cloud messaging tab and you will see your Server Key, copy that. If you do not have a Firebase account for your application. Refer https://firebase.google.com/docs/android/setup

Save this FCM server key in Freshchat web portal under Admin -> Mobile SDK


iOS

Refer here for generating .p12 file and uploading it to Freshchat.


6.1.2 Client side integration - Android

Please follow the below steps to integration push notifications in your android version of the mobile app. Below steps are under the assumption that your app is handing other push notifications.


Steps


1. Saving push token: Each application will have a firebase push token. Freshchat needs this token to send push notification to user. You can use below snippet to send firebase token to Freshchat SDK. 

Freshchat.setPushRegistrationToken(token);


2. Passing received push notification payload to Freshchat SDK.

FirebaseMessaging firebaseMessaging = FirebaseMessaging();
firebaseMessaging.configure(
    onMessage: (Map<String,dynamic> message)async{
        if(await Freshchat.isFreshchatNotification(message['data']){
            Freshchat.handlePushNotification(message['data']);
        }
    }
    onBackgroundMessage: myBackgroundMessageHandler);
);


3. To handle freshchat notifications in background or killed state - Follow this documentation to setup background FCM notification support for your flutter app. Register the Freshchat SDK plugin inside the registerWith method by adding this line inside it.

import com.freshchat.consumer.sdk.flutter.FreshchatSdkPlugin;
public void registerWith(PluginRegistry registry){
  // Register FCM plugin 
  FreshchatSdkPlugin.register(registry)
}


Handle background notification from your flutter app by adding a static method or top-level function

Future<dynamic> myBackgroundMessageHandler(Map<String,dynamic> message) async{
	if(await Freshchat.isFreshchatNotification(message['data'])){
        Freshchat.handlePushNotification(message['data']);
    }
}


6.1.3 Client side integration - iOS

Please follow the below steps to integration push notifications in your iOS version of the mobile app. Below steps are under the assumption that your app is handing other push notifications.


Steps

1. In the AppDelegate.m file, add the following lines of code 


#import "FreshchatSdkPlugin.h"


Freshchat SDK is capable of getting push notifications for all user conversations. To enable it, add setPushRegistrationToke API into your app delegate’s didRegisterForRemoteNotificationsWithDeviceToken method as follows.

 

Objective C

[[[FreshchatSdkPlugin alloc]init] setPushRegistrationToken:devToken];


To handle push notification messages in active or background state add following method in didReceiveRemoteNotification or didFinishLaunchingWithOptions delegate method respectively.

 

Objective C

 

if([[[FreshchatSdkPlugin alloc]init] isFreshchatNotification:info]) {
    [[FreshchatSdkPlugin alloc]init] handleRemoteNotification:info andAppstate:app.applicationState];
}


6.2 Customising Notifications (Android only)

Add the below code in your dart file


Freshchat.setNotificationConfig(priority: Priority.PRIORITY_HIGH,
                                importance: Importance.IMPORTANCE_DEFAULT,
                                notificationSoundEnabled:true,
                                largeIcon:"notif"// Drawable name,
                                smallIcon:"notif"// Drawable name);


6.3 Push Notification Checklist

We have identified some potential areas where problem happens. So we consolidated those into checklists, check if you have done everything.


iOS

1. Make sure you have uploaded correct push certificate in Freschat portal.


2. Make sure that you are checking in development or production environment and upload the respective certificate in Freshchat portal.


3.Don’t check in iOS simulator, since it did not have push notification capability. Check in real device.


4.Push notification capability should be enabled in your Xcode project.


5.Make sure you gave permission to push notification for your application. If not go to Admin -> under your application, enable push notification.


6.Confirm you are passing on device token to the Freshchat using the following method,


[[[FreshchatSdkPlugin alloc]init] setPushRegistrationToken:devToken];


7. Under Appdelegate class make sure you have either UNUserNotificationCenter delegate methods or [UIApplicationDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:] is implemented. And if UNUserNotificationCenter framework is being used, make sure delegate has been set for that.


8. Add respective flutter bridging codes on the push notification delegate methods.


9. Refer the codes here for plugin implementation, confirm you have implemented all the recommendations.


10. If you have Notification extension in your app, make sure its not blocking the notification.


Android

1. Make sure you have added correct FCM key of your application in Freshchat portal


2. Don’t check in emulator, which don’t have google play service enabled. Check in real device.


3. Confirm you are passing on device token to the Freshchat using the following method,

Freshchat.setPushRegistrationToken(fcmToken);

4. Make sure you are receiving notification from FCM.


5. Refer the codes here for plugin implementation, confirm you have implemented all the recommendations


If the problem persists, try the following URL,

https://web.freshchat.com/app/api/notif_debug?convId=CONV_ID 
where, CONV_ID is the conversation id of the conversation for which you did not receive notification. CONV_ID is the last numeric part of the url when you open the conversation in the browser. 

Ensure that you are logged in as Admin while opening this url. It will give you the reason behind the push notification failure.