freshchat_sdk 0.1.0 copy "freshchat_sdk: ^0.1.0" to clipboard
freshchat_sdk: ^0.1.0 copied to clipboard

outdated

Freshchat is a modern messaging software for sales and customer engagement teams. freshchat_sdk will help you integrate chat support in your mobile apps.

Freshchat Flutter SDK (BETA) #

Flutter SDK Integration #

Note:

  1. Freshchat flutter SDK helps integrating Freshchat in your flutter mobile applications.
  2. Flutter v1.10.0 and above will be supported from Freshchat SDK.
  3. Please refer the change logs before updating to newer version of the SDK.
  4. Integration document: https://support.freshchat.com/en/support/solutions/articles/50000003343-freshchat-flutter-sdk-integration-steps

Integrate Flutter Freshchat SDK: #

  1. Freshchat pub plugin name is ‘freshchat-sdk’.
  2. In your flutter project’s pubspec.yaml file, under dependencies add ”freshchat_sdk: "{{latest-version}}"”
  3. For latest SDK version please refer the following link: [to be updated]

iOS Setup: #

Steps
Run below command to autolink the SDK
cd ios
pod install

Android Setup: #

  1. 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.

    <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>
    
  2. Add this in strings.xml

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

Steps to integrate Freshchat Flutter SDK: #

1. Initialisation: #

Freshchat SDK can be initialised when the app gets started. You can use the below snippet to initialise SDK.

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

Where APP_ID and APP_KEY are your account’s specific which can be found in Freshchat portal under Settings -> Mobile SDK.

2. Set User Properties: #

setUser API is used to update user details. You can use the below snippet to update user details.

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. Set User Custom Properties: #

You can set or update custom properties of user using setUserProperties API. You can set up to 126 unique properties per account.

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

4. Identify and restore user: #

identifyUser API is used to identify and restore the user’s conversations.

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 identifyUser: API

Note: 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 getRestoreId(); API on the user object obtained by getUser API.

Note: Restore Id should be stored at your backend and you can implement logic to retrieve them to restore conversations back.

Freshchat.identifyUser("EXTERNAL_ID", "RESTORE_ID");

Note: For first time user, you can pass restoreId as null. SDK will generate restoreId for the user. If you are listening to the below event, you will be notified when restoreId is generated.

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

When this event is triggered, you can get current user details and access restoreId from there. Store this identifier in your backend. So when the same user logs back from different device call identifyUser method with the EXTERNAL_ID and RESTORE_ID of the corresponding user.

Note: Restore Id generation is an asynchronous process. You need to listen to this event throughout your application lifecycle. Usually generation happens after user initiates a conversation.

5. Show Conversations: #

Show conversations will display all channels published publicly. To show conversations call the following API,

Freshchat.showConversations();

If there is only a single channel, this API will directly open that channel. If there are multiple channels, this API will open the list of channels

6. Show Conversations with options: #

showConversations API will display channel list with all channel by default. If you want to open a particular channel directly or list a small section of channels, you can use showConversations(option: "value") API. This API accepts conversationOptions where you can specify what channels to open.

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

Tags are used to filter channels belongs to the tag. FilteredViewTitle is the title given to channels list page when there are multiple channel matches found.

Note: If there is no matching channel found for the option applied, SDK will take you to the conversation page of the default channel.

7. Show FAQs: #

showFaq API helps you to display FAQs in your application To show FAQs call the following method,

Freshchat.showFAQ();

8. Show FAQs with options: #

showFAQ API will display all categories and articles by default. If you want to open a particular category/article directly or list a small section of categories/articles, you can use showFAQ(faqOption: "value") 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. FaqFilterType.Category - combination of articles and sub categories. FaqFilterType.Article - contains only articles.

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

9. Reset User: #

Reset user clears the current user details. When user logs out, you can call the below API to reset Freshchat user.

Freshchat.resetUser();

This API will clears user related info from the application.

10. Get User: #

User object will give details about the current user using the chat. To get the user details use the following method,

FreshchatUser freshchatUser = Freshchat.getUser();

User object has following details, firstName, lastName, email, restoreId, externalId, phoneNumber and phoneCountryCode.

11. Send Message: #

Instead of going to Freshchat screen and user initiating a chat, this will help send message instantly from anywhere in the application. To send a message on behalf of a user call the following method,

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

Construct FreshchatMessage with tag and message properties. Pass it to sendMessage method. tag - tag of the channel to which message needs to be sent. message - actual message to be passed to the channel.

Note: When there are multiple matching channels, channel which was created first will get the message. If there is no matching channel found, message will be sent to the default channel.

13. Unread message count: #

This gives the count on number of messages left uread by users. To get unread count immediately add the following code,

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

Note: This works best with Push notification integration.

EVENTS: #

Some of the actions performed in SDK are exposed by SDK. You can listener to them by adding a listener.

1. Adding listener: #

To add callback for any event use the following approach,

var restoreStream = Freshchat.onRestoreIdGenerated;
StreamSubscription restoreStreamSubscription = restoreStream.listen((event) {
      print("Inside Restore stream: Restore Id generated");
    });

2. Supported Events: #

Track detailed Freshchat SDK actions:

It gives a detailed description about the action happened inside Freshchat module.

var freshchatEventStream = Freshchat.onFreshchatEvents;
  StreamSubscription fchatEventStreamSubscription = freshchatEventStream.listen((event) {
      print("Freshchat Event: $event");
    });
  }

More info here

3. Removing listeners: #

To remove any listener from getting callback add the following code,

fchatEventStreamSubscription.cancel();

Push notification integration: #

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 Settings -> Mobile SDK

iOS:

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

2. Client side integration: Android #

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

Steps:

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

    Freshchat.setPushRegistrationToken(token); 
    
  • 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);
    );
    

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:

  • 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.
[[[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.
if([[[FreshchatSdkPlugin alloc]init] isFreshchatNotification:info]) {
    [[FreshchatSdkPlugin alloc]init] handleRemoteNotification:info andAppstate:app.applicationState];
}

3. Set freshchat notification config (Android only) #

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']);
    }
}

Push Notification checklists: #

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 Freschat 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 settings -> under your application, enable push notification.

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

  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.

    [[[FreshchatSdkPlugin alloc]init] setPushRegistrationToken:devToken];
    
  8. Refer the codes here for plugin implementation, confirm you have implemented all the recommendations.

  9. 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(token);
    
  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 still problem persists, check out 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. Please make sure you are logged in as ADMIN when opening this url. It will give you the reason behind the push notification failure.

For More References #

More instructions here: Freshchat for Android

More instructions here: Freshchat for iOS

34
likes
0
pub points
95%
popularity

Publisher

verified publisherfreshworks.com

Freshchat is a modern messaging software for sales and customer engagement teams. freshchat_sdk will help you integrate chat support in your mobile apps.

Homepage

License

unknown (LICENSE)

Dependencies

flutter

More

Packages that depend on freshchat_sdk