Integrating Android SDK

There are 2 ways of integrating the android SDK:

  • Using pre-built UI. The appearance will follow everything that you set in your dashboard
  • Using your own UI. We provide the core functionalities, you handle the UI yourself.

Integrating Android UI SDK

Download

1. Getting Started

1.1. What is Prism Android UI SDK

It's a variant of Prism Android SDK for merchants who want to integrate Prism chat to buy capabilities easily into their application using provided UI.

1.2. System Requirements

There are some requirements for merchants who want to use this SDK

  • Must be native Android project
  • Minimum supported OS is Android Jelly Bean (Android 4.1)
  • Using gradle as build system

2. Integration

2.1. Register as Prism Merchant

These are some basic requirements to integrate with Prism Android UI SDK:

  1. Prism account. Please register here.
  2. Get your merchant id at Settings -> Account -> Merchant Account.
  3. Android project. Prepare your Android project using Android Studio.

2.2. Add Prism Maven Repository

On your root project's build.gradle please add Prism Maven Repository.

allprojects {
    repositories {
        ... // List of your other repositories
        /** Google Repositories **/
        google() // Use this for gradle 4.1 or above
        maven { url "https://maven.google.com" } // Use this for below gradle 4.1
        // Jitpack
        maven { url "https://jitpack.io" }
        // Prism Maven
        maven { url "https://dl.bintray.com/prism/Prism-SDK" }
    }
}

2.3. Add UI SDK Dependency

On your application module's build.gradle please add Prism UI dependency.

compile 'io.prismapp.sdk:ui:{$latest_version}'

2.4. Build UI SDK

To initilaze the UI SDK, you just need to provide merchant id.

Then you can use PrismUi to build and initialize the SDK.

PrismUi prismUi = PrismUi.builder(APPLICATION_CONTEXT)
                .environment(Environment.SANDBOX|PRODUCTION)
                .merchantId(MERCHANT_ID)
                .build();

Note:

  • You can either manage PrismUi on your own or you can get singleton instance using getInstance() static function on initialized SDK or it will throw RuntimeException which will tell you that you haven't initialized the SDK.
PrismUi prismUi = PrismUi.getInstance();
  • Since version 0.1.5.0, Prism Android SDK supports Sandbox environment for custom integration and testing purpose. For Sandbox account request, please contact Prism integration team.

2.5. Customize Typeface

If you want to use your custom font in Prism chat UI, you just need to put it on assets directory on your Android application project and provide PrismUi builder the relative part of the font path to assets directory.

PrismUi prismUi = PrismUi.builder(CONTEXT)
                .environment(Environment.SANDBOX|PRODUCTION)
                .merchantId(MERCHANT_ID)
                .regularTypeface(REGULAR_FONT_PATH)
                .semiboldTypeface(SEMIBOLD_FONT_PATH)
                .boldTypeface(BOLD_FONT_PATH)
                .build();

2.6. Start Chat UI

2.6.1. Without Credentials

This is the default settings if you don't provide any credentials. It has same capabilities with Prism chat widget.

If you start from activity just provide Context.

PrismUi.getInstance().startChatUi(CONTEXT);

Or if you don't start from activity add newTask boolean parameter.

PrismUi.getInstance().startChatUi(CONTEXT, NEW_TASK);
2.6.2. With Provided Credentials

If you want to use your own visitor credential, you can provide it when starting chat UI.

If you start from activity just provide Context, visitor name and visitor unique identifier.

PrismUi.getInstance().startChatUi(CONTEXT, VISITOR_NAME, VISITOR_UNIQUE_ID);

Or if you don't start from activity add newTask boolean parameter.

PrismUi.getInstance().startChatUi(CONTEXT, VISITOR_NAME, VISITOR_UNIQUE_ID, NEW_TASK);

Note: - VISITOR_UNIQUE_ID can be anything as long as it's unique for each user. Example: email, phone, UUID.

2.7. Handle Push Notifications

Prism provides push notification for merchant who wants to use it via Firebase Cloud Messaging (FCM).

2.7.1. Integrate Firebase to Android Project
  1. Open Firebase website at https://firebase.google.com/
  2. Click go to console to register using google account.
  3. On Firebase console, please create a project.
  4. Fill project name and country.
  5. Wait for a while when the project is created. Then the project page was opened.
  6. Add your Android app by clicking `Add Firebase to your Android app. Only your app's package name is required.
  7. Please download google-services.json and add it to app's module in your Android project.
  8. Follow Firebase instruction to integrate Firebase to Android project.
2.7.2. Obtain Firebase Server Key and Sender Key
  1. Back on Firebase console. Please open settings page.
  2. Go to CLOUD MESSAGING tab. Find your server key and sender id there.
  3. You need to tell our integration team these credentials so we can integrate the push notification service to your application.
2.7.3. Add Firebase Messaging Dependencies to Android Project

On your app's module build.gradle, you need to add these lines.

dependencies {
     compile 'com.google.firebase:firebase-messaging:10.2.4'
}
2.7.4. Send Firebase device token

To identify specific visitor device, merchant need to send their visitor's device token to Prism system.

First, create a class extends from FirebaseInstanceIdService. For example, the class name is MyFirebaseInstanceIdService.

Merchant needs to override onTokenRefresh. It's a callback whenever new token is created or updated by Firebase.

public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String refreshedToken) {
        PrismUi.getInstance().registerUpdatedFcmToken(this, refreshedToken);
    }

}

Second, register created MyFirebaseInstanceIdService to app's manifest.

<service
    android:name=".MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>
2.7.5. Handle received message

To receive message in Firebase, merchant need to add a class extends from FirebaseMessagingService. For example, the class name is MyFirebaseMessagingService.

If merchant want to let Prism UI SDK handle the notification, they need to send the received message to Prism UI SDK using this codes.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        String messagePayload = remoteMessage.getData().get(PrismUi.MESSAGE_PAYLOAD);

        handleIncomingMessage(messagePayload);
    }

    private void handleIncomingMessage(String messagePayload) {
        PrismUi.getInstance().handleIncomingMessage(this, messagePayload);
    }

}

Then register created MyFirebaseMessagingService into app's manifest.

<service
    android:name=".MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>
2.7.6. Notification UI Options
2.7.6.1. Notification Icon

By default, Prism UI SDK will use its notification icon for both large and small icon.

You can change the notification icon by providing the drawable resources id into PrismUi builder.

new PrismUi.Builder(this)
                .merchantId(MERCHANT_ID)
                .notificationIcon(R.drawable.ic_notification_large, R.drawable.ic_notification_small)
                .build();
2.7.6.2. Notification Behavior

Prism UI SDK has 3 options for their notifications:

  • Show all received messages (Inbox style)
  • Show latest message only
  • Show unread count only

By default, if you let Prism UI SDK handle the notification it will use first options.

You can customize the options in PrismUi builder.

2.7.6.2.1. All messages notification
new PrismUi.Builder(this)
                .merchantId(MERCHANT_ID)
                .notificationTypeAllMessage()
                .build();
2.7.6.2.2. Latest message only notification
new PrismUi.Builder(this)
                .merchantId(MERCHANT_ID)
                .notificationTypeLatestMessage()
                .build();
2.7.6.2.3. Unread count only notification
new PrismUi.Builder(this)
                .merchantId(MERCHANT_ID)
                .notificationTypeUnreadCountOnly()
                .build();

2.8. Multidex

You may encounter a problem when building your app after integrating with Prism. It's called DexOverflowException problem that is caused because your application package total method count is over 65k (limitation of Android).

To get rid of this problem, you can enable MultiDex on your build.gradle.

Here is the setup on your build.gradle.

defaultConfig {
        ... // other config
        multiDexEnabled true
    }

dependencies {
    ... // other config
    compile 'com.android.support:multidex:1.0.1'
}

Also you need to initialize the Multidex on your App class.

public class App extends Application {

    @Override
    public void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }
}

Make sure it's used on your AndroidManifest.xml.

<application
    ...//other config
    android:name=".App">

Integrating Android Core SDK

Download

1. Getting Started

1.1. What is Prism Android Core SDK

It's a variant of Prism Android SDK who wants to integrate Prism chat to buy capabilities into their application using their own UI.

1.2. System Requirements

There are some requirements for merchants who want to use this SDK

  • Must be native Android project
  • Minimum supported OS is Android Jelly Bean (Android 4.1)
  • Using gradle as build system

2. Integration

2.1. Register as Prism Merchant

These are some basic requirements to integrate with Prism Android Core SDK:

  1. Prism account. Please register here.
  2. Get your merchant id at Settings -> Account -> Merchant Account.
  3. Android project. Prepare your Android project using Android Studio.

2.2. Add Prism Maven Repository

On your root project's build.gradle please add Prism Maven Repository.

allprojects {
    repositories {
        ... // List of your other repositories
        /** Google Repositories **/
        google() // Use this for gradle 4.1 or above
        maven { url "https://maven.google.com" } // Use this for below gradle 4.1
        // Jitpack
        maven { url "https://jitpack.io" }
        // Prism Maven
        maven { url "https://dl.bintray.com/prism/Prism-SDK" }
    }
}

2.3. Add Core SDK Dependency

On your application module's build.gradle please add Prism Core dependency.

compile 'io.prismapp.sdk:core:{$latest_version}'

2.4. Build Core SDK

To initilaze the Core SDK, you just need to provide merchant id.

Then you can use PrismCore.Builder to build and initialize the SDK.

PrismCore prismCore = PrismCore.builder(APPLICATION_CONTEXT)
                .environment(Environment.SANDBOX|PRODUCTION)
                .merchantId(MERCHANT_ID)
                .build();

Note: - You can either manage PrismCore on your own or you can get singleton instance using getInstance() static function on initialized SDK or it will throw RuntimeException which will tell you that you haven't initialized the SDK.

PrismCore prismCore = PrismCore.getInstance();
  • Since version 0.1.5.0, Prism Android SDK supports Sandbox environment for custom integration and testing purpose. For Sandbox account request, please contact Prism integration team.

2.5. Initialize SDK

To start using SDK after build the SDK, you can initialize the SDK. Initialization means SDK will check your merchant id and return merchant specific settings if it's valid merchant id.

PrismCore
    .getInstance()
    .init(new Callback<Map<String, Object>>() {
        @Override
        public void onSuccess(Map<String, Object> response) {
            // Merchant found
            // Handle success here
        }

        @Override
        public void onFailure(@NotNull PrismCoreException error) {
            // Handle Error
        }
    });

Merchant settings is map of String and Object that represents chat widget settings that you set on Prism Dashboard so it helps you set up your chat to buy behavior.

Here is the example JSON of the merchant settings:

{
    "general_information": {
        "site_name": "Danny's Store",
        "site_url": "https://danny-store.com",
        "phone": "+6281234567890",
        "installation_complete": false,
        "chat_tour_agents_status": [
            "31de9b49-6187-41b8-8350-6a2d011ce9e0",
            "31de9b49-6187-41b8-8350-6a2d011ce9e1"
        ]
    },
    "widget":{  
        "enabled": true|false,
        "visitor_connect": {  
            "option": "DISABLED|ENABLED",
            "form_message": "Hello, we’re here to make your shopping smoother. Let’s chat!",
            "form_options": {  
                "name": {  
                    "show":false,
                    "required":false
                },
                "phone": {  
                    "show":false,
                    "required":false
                },
                "email": {  
                    "show":false,
                    "required":false
                }
            }
        },
        "appearance": {  
            "persona": {  
                "enabled":false,
                "image_url":"https://img.com/avatar.png",
                "name":"Danny"
            },
            "texts": {  
                "title_expanded": "Let`s shop with us!",
                "subtitle": "Chat to buy",
                "title_minimized": "Mau pesan? Klik disini",
                "welcome_message": "Hello, we’re here to make your shopping smoother. Let’s chat!"
            },
            "color_theme": "PINK|WHITE|BLACK|BLUE|GREEN|CORAL|YELLOW",
            "position": "bottom-right"
        },
        "attention_grabber":{  
            "option":"DISABLED|TEXT|IMAGE|TEXT_AND_IMAGE",
            "desktop_text":"PRISM IS YOUR CONVERSION RATE BOOSTER",
            "desktop_image_url":"https://img.com/attention-grabber-desktop.png",
            "mobile_text":"PRISM IS YOUR CONVERSION RATE BOOSTER",
            "mobile_image_url":"https://img.com/attention-grabber-desktop.png"
        },
        "working_hours":{  
            "monday":[  
                {  
                    "from":"08:00",
                    "to":"12:00"
                },
                {
                    "from":"13:00",
                    "to":"18:00"
                }
            ],
            "tuesday":[  
                {  
                    "from":"08:00",
                    "to":"12:00"
                },
                {
                    "from":"13:00",
                    "to":"18:00"
                }
            ],
            "wednesday":[  
                {  
                    "from":"08:00",
                    "to":"12:00"
                },
                {
                    "from":"13:00",
                    "to":"18:00"
                }
            ],
            "thursday":[  
                {  
                    "from":"08:00",
                    "to":"12:00"
                },
                {
                    "from":"13:00",
                    "to":"18:00"
                }
            ],
            "friday":[  
                {  
                    "from":"08:00",
                    "to":"12:00"
                },
                {
                    "from":"13:00",
                    "to":"18:00"
                }
            ],
            "saturday":[],
            "sunday":[]
        },
        "offline_widget":{  
            "texts":{
                "equals_title_minimized": false,
                "equals_title_expanded": false,
                "title_expanded":"We’re Offline, leave us a message",
                "title_minimized":"We’re Offline, leave us a message",
                "offline_message":"Hello, our chat service is closed now. Please leave a message, we will contact you as soon as we’re back",
                "offline_message_confirmation": "Thank you for contact us"
            },
            "form_options":{  
                "name":{  
                    "show":false,
                    "required":false
                },
                "phone":{  
                    "show":false,
                    "required":false
                },
                "email":{  
                    "show":false,
                    "required":false
                }
            }
        },
        "triggers": [  
            {  
                "url": "http://prismapp.io/trigger",
                "wait_time": "5",
                "action": "Widget Expanded|Widget Minimized",
                "enabled": true|false
            },
            {  
                "url": "http://prismapp.io/products",
                "wait_time": "15",
                "action": "Widget Expanded|Widget Minimized",
                "enabled": true|false
            }
        ],
        "auto_responders":[  
            {  
                "channel_id": "123674762",
                "channel_type": "SHAMU|LINE|FACEBOOK",
                "condition": "When Online|When Offline",
                "response_message": "Welcome to Prismshop, what can we do for you today?",
                "enabled": true|false
            }
        ]
    }
}

2.6. Visitor Connect

Visitor connect is used to get credentials for your visitors so they can use Prism chat to buy capabilities.

PrismCore
    .getInstance()
    .visitorConnect(VISITOR_NAME, VISITOR_UNIQUE_ID, new Callback<VisitorConnectResponse>() {
            @Override
            public void onSuccess(VisitorConnectResponse response) {
                Mqtt mqttCredential = response.getMqtt();
                Oauth oauthCredential = response.getOauth();
                Visitor visitorData = response.getVisitor();
                // Save your visitor credentials to be used later
            }

            @Override
            public void onFailure(@NotNull PrismCoreException error) {
                // Handle failure
            }
        });

Notes:

  • Oauth credentials is used to access more features such as initiate a conversation, upload attachment to Prism storage, etc.
  • Mqtt credentials is used to access real time messaging broker that Prism use to hold a conversation.
  • Visitor contains visitor data that may be used to identify each visitor.

2.7. Create Conversation

Create conversation is used by visitor to initiate a conversation so it needs visitor credential obtained at visitor connect step.

PrismCore
    .getInstance()
    .createConversation(visitor.getName(), oauth.getAccessToken(), new Callback<CreateConversationResponse>() {
                @Override
                public void onSuccess(CreateConversationResponse response) {
                    // Here is the conversation details
                    Conversation conversation = response.getConversation();
                    // Conversation topic to be used on Prism Messaging Broker
                    String topic = conversation.getTopic();
                    // Conversation id to be used to get conversation history
                    String conversationId = conversation.getId();
                    // Save them so it can be used later
                }

                @Override
                public void onFailure(@NotNull PrismCoreException error) {
                    // Handle failure
                }
            });

Notes:

  • visitor is obtained at visitor connect step.
  • oauth is also obtained at visitor connect step.

2.8. Connect to Messaging Broker

Before you can use real time messaging broker subscribe to a conversation, your visitor must connect to Prism messaging broker first.

PrismCore
    .getInstance()
    .connect(mqtt.getUsername(), mqtt.getPassword(), new Callback<Boolean>() {
                @Override
                public void onSuccess(Boolean response) {
                    // Check the connection status
                    if(response) {
                        // Visitor is connected to messaging broker
                    } else {
                        // Visitor is failed to connect
                    }
                }

                @Override
                public void onFailure(@NotNull PrismCoreException error) {
                    // Handle failure
                }
            });

Notes:

  • mqtt is obtained at visitor connect step.

2.9. Subscribe to Conversation

Your visitor can subscribe to a conversation to receive new message by real time.

PrismCore
    .getInstance()
    .subscribeToTopic(conversation.getTopic(), new MessageSubscriptionCallback() {
                @Override
                public void onMessageReceived(@NotNull Message<?> response) {
                    // New message received
                    // Each type must be parsed differently
                    switch (response.getType()) {
                        case MessageType.TEXT:
                            Message<ContentText> textMessage = (Message<ContentText)) response;
                            // Do something about text message
                            showTextMessage(textMessage);
                            break;
                        case MessageType.PRODUCT:
                            Message<ContentProduct> productMessage = (Message<ContentProduct)) response;
                            // Do something about product message
                            showProductMessage(productMessage);
                            break;
                        case MessageType.INVOICE:
                            Message<ContentInvoice> invoiceMessage = (Message<ContentInvoice)) response;
                            // Do something about invoice message
                            showInvoiceMessage(invoiceMessage);
                            break;
                        case MessageType.CART:
                            Message<ContentCart> cartMessage = (Message<ContentCart)) response;
                            // Do something about cart message
                            showCartMessage(cartMessage);
                            break;
                        case MessageType.ATTACHMENT:
                            Message<ContentAttachment> attachmentMessage = (Message<ContentAttachment)) response;
                            // Do something about attachment message
                            showAttachmentMessage(attachmentMessage);
                            break;
                        case MessageType.STICKER:
                            Message<ContentSticker> stickerMessage = (Message<ContentSticker)) response;
                            // Do something about sticker message
                            showStickerMessage(stickerMessage);
                            break;
                        case MessageType.CLOSE_CHAT:
                            // Handle close conversation message
                            // Visitor should stop listening to current topic and disable sending message to current topic.
                            // Go to 2.9.1 Handle Close Conversation for more information
                            break;   
                    }
                }

                @Override
                public void onMessageSubscriptionError(@NotNull PrismCoreException exception) {
                    // Handle failure when subscribing to a topic
                }
            });

Notes:

  • conversation is conversation details obtained at create conversation step.
  • Each message type must be handled differently based on its type and content.
2.9.1 Handle Close Conversation

When visitor receiving message that have MessageType.CLOSE_CHAT there are several actions needed on the visitor side.

  • Visitor should stop subscribing to the current topic. Go to 2.11. Unsubscribe From Topic section.
  • Visitor shouldn't be able to send message to this topic again.

If the visitor want to continue the conversation, they need to restart the conversation by following this

  1. Visitor connect using previous credentials
  2. Create conversation using above visitor connect result

2.10. Send Message to Conversation

Visitor can send message to a conversation.

You can easily use Message.Builder to build message object easily.

Another note is that Prism support same content types of the message as in subscribeToTopic but as visitor you can only send text, attachment, sticker message and offline message.

2.10.1. Text Message

Text message is the simplest message type. It contains a text in string format.

2.10.1.1. Build Text Message

To build text message, you need to build a ContentText based message. It just needs a text in String format.

ContentText text = new ContentText(MESSAGE);

Message<ContentText> textMessage = new Message.Builder<ContentText>()
                .id(RANDOM_UUID)
                .merchantId(conversation.getMerchantId())
                .conversationId(conversation.getId())
                .channel(conversation.getChannel())
                .visitorName(visitor.getName())
                .visitorId(visitor.getId())
                .type(MessageType.TEXT)
                .content(text)
                .timestamp("2017-05-28T06:33:15-0700") // must be ISO-8601 formatted
                .build();

Notes:

  • Message id is a random UUID. For example you can generate it using UUID.randomUUID().toString().
  • conversation is the conversation details obtained at create conversation step.
  • visitor is the visitor details obtained at visitor connect process.
2.10.1.2. Send Text Message
PrismCore
    .getInstance()
    .sendTextMessage(oauth.getAccessToken, conversation.getTopic(), textMessage, new MessagePublicationCallback() {
                    @Override
                    public void onMessagePublished(@NotNull Message<?> message) {
                        // Handle sent message
                    }

                    @Override
                    public void onMessagePublicationError(@NotNull Message<?> message, @NotNull PrismCoreException error) {
                        // Handle failure
                    }
                });
  • oauth is API credential obtained at visitor connect step.
  • conversation is conversation details obtained at create credential step.
2.10.2. Attachment Message

Attachment message is a message type which includes a file. The file needs to be uploaded at some server and can be accessed using specific url. This attachment message only need those url and its content type.

Note: Currently Prism only supports image messages.

2.10.2.1. Build Attachment Message

To send a attachment message you need to provide FILE_NAME, CONTENT_TYPE, FILE_URL, and PREVIEW_URL.

Attachment attachment = new Attachment(
                FILE_NAME,
                CONTENT_TYPE,
                FILE_URL,
                PREVIEW_URL // Optional
);

ContentAttachment contentAttachment = new ContentAttachment(attachment);

Message<ContentAttachment> attachmentMessage = new Message.Builder<ContentAttachment>()
                .id(UUID.randomUUID().toString())
                .merchantId(conversation.getMerchantId())
                .conversationId(conversation.getId())
                .channel(conversation.getChannel())
                .visitorName(visitor.getName())
                .visitorId(visitor.getId())
                .type(MessageType.ATTACHMENT)
                .content(contentAttachment)
                .timestamp("2017-05-28T06:33:15-0700")
                .build();

Notes:

  • FILE_NAME should includes extension. For example: attachment.jpg
  • CONTENT_TYPE is based on attachment type. For now Prism only supports image attachment so the CONTENT_TYPE should be image/png, image/jpeg, or image/gif.
  • FILE_URL is URL to download or view your attachment.
  • PREVIEW_URL is optional URL to preview your attachment.

You can either use your own storage to upload your attachment or you can upload your attachment to Prism storage. If you want to upload attachment to Prism storage please proceed to upload attachment section.

2.10.2.2. Send Attachment Message
PrismCore
    .getInstance()
    .sendAttachmentMessage(oauth.getAccessToken, conversation.getTopic(), attachmentMessage, new MessagePublicationCallback() {
                    @Override
                    public void onMessagePublished(@NotNull Message<?> message) {
                        // Handle message sent
                    }

                    @Override
                    public void onMessagePublicationError(@NotNull Message<?> message, @NotNull PrismCoreException error) {
                        // Handle failure
                    }
                });
  • oauth is API credential obtained at visitor connect step.
  • conversation is conversation details obtained at create credential step.
2.10.3. Sticker Message

Merchant can use sticker pack that is available on Prism dashboard settings page to send message.

2.10.3.1. Build Sticker Message

You must implement getStickers on this section in order to proceed to this section.

You must provide STICKER_NAME, STICKER_IMAGE_URL, STICKER_ID, and STICKER_PACK_ID from your visitor selected sticker.

Sticker sticker = new Sticker(
    STICKER_NAME,
    STICKER_IMAGE_URL,
    STICKER_ID,
    STICKER_PACK_ID
);
ContentSticker contentSticker = new ContentSticker(sticker);

Message<ContentSticker> stickerMessage = new Message.Builder<ContentSticker>()
                .id(UUID.randomUUID().toString())
                .merchantId(conversation.getMerchantId())
                .conversationId(conversation.getId())
                .channel(conversation.getChannel())
                .visitorName(visitor.getName())
                .visitorId(visitor.getId())
                .type(MessageType.STICKER)
                .content(contentSticker)
                .timestamp("2017-05-28T06:33:15-0700")
                .build();

Notes:

  • Sticker details such as name, image URL, id and pack id should be available on each sticker pack when getting available stickers.
2.10.3.2. Send Sticker Message
PrismCore
    .getInstance()
    .sendAttachmentMessage(oauth.getAccessToken, conversation.getTopic(), stickerMessage, new MessagePublicationCallback() {
                    @Override
                    public void onMessagePublished(@NotNull Message<?> message) {
                        // Handle message sent
                    }

                    @Override
                    public void onMessagePublicationError(@NotNull Message<?> message, @NotNull PrismCoreException error) {
                        // Handle failure
                    }
                });
  • oauth is API credential obtained at visitor connect step.
  • conversation is conversation details obtained at create credential step.
2.10.4. Offline Message

Offline message is a type of message that sent from visitor when they are want to reach to agent on offline hours.

2.10.4.1. Build Offline Message
OfflineMessage message = new OfflineMessage(NAME, EMAIL, PHONE, MESSAGE);
ContentOfflineMessage contentOfflineMessage = ContentOfflineMessage(message);

Message<ContentOfflineMessage> offlineMessage = Message.Builder<ContentOfflineMessage>()
                .id(UUID.randomUUID().toString())
                .merchantId(conversation.getMerchantId())
                .conversationId(conversation.getId())
                .channel(conversation.getChannel())
                .visitorName(visitor.getName())
                .visitorId(visitor.getId())
                .type(MessageType.OFFLINE_MESSAGE)
                .content(contentOfflineMessage)
                .timestamp("2017-05-28T06:33:15-0700")
                .build();

2.10.4.2. Send Offline Message
PrismCore
    .getInstance()
    .sendOfflineMessage(oauth.getAccessToken, conversation.getTopic(), offlineMessage, new MessagePublicationCallback() {
                    @Override
                    public void onMessagePublished(@NotNull Message<?> message) {
                        // Handle message sent
                    }

                    @Override
                    public void onMessagePublicationError(@NotNull Message<?> message, @NotNull PrismCoreException error) {
                        // Handle failure
                    }
                });

Notes:

  • oauth is API credential obtained at visitor connect step.
  • conversation is conversation details obtained at create credential step.

2.11. Unsubscribe From Topic

In some case, your visitor can unsubscribe from a conversation when they don't want receive message.

PrismCore
    .getInstance()
    .unsubscribeFromTopic(conversation.getTopic(), new Callback<Boolean>() {
        @Override
        public void onSuccess(Boolean response) {
            // Handle response
        }

        @Override
        public void onFailure(@NotNull PrismCoreException error) {
            // Handle review
        }
    });

Notes:

  • conversation is conversation details obtained at create credential step.

2.12. Disconnect

There is case when in merchant app, visitor is logged out, they need to disconnect from message broker because it's not used anymore.

PrismCore
    .getInstance()
    .disconnect(new Callback<Boolean>() {
        @Override
        public void onSuccess(Boolean response) {
            // Handle response
        }

        @Override
        public void onFailure(@NotNull PrismCoreException error) {
            // Handle review
        }
    });

2.13. Upload Attachment

Note: Currently Prism only supports images for attachment.

To upload an image to Prism storage there are some steps to follow:

  1. Create attachment URL from Prism
  2. Upload selected image to Prism storage.
2.13.1. Create Attachment URL

To create attachment URL you must provide file name and its content type.

PrismCore
    .getInstance()
    .createAttachmentUrl(
        conversation.getId(),
        oauth.getAccessToken(),
        FILENAME,
        CONTENT_TYPE,
        new Callback<AttachmentUrlResponse>() {
             @Override
             public void onSuccess(AttachmentUrlResponse response) {
                 String uploadUrl = response.getUploadUrl();
                 // Then proceed to upload your image using uploadUrl
             }

             @Override
             public void onFailure(@NotNull PrismCoreException error) {
                 // Handle failure            
             }
        }
    );
2.13.2. Upload Image to Prism Storage

To upload image you must provide a File based on your selected image and the same content type that you provide when creating attachment URL.

PrismCore
    .getInstance()
    .uploadAttachment(uploadUrl, FILE, CONTENT_TYPE, new UploadCallback() {
            @Override
            public void onFinished() {
                // Handle upload success
                // You can send attachment message using uploadUrl
            }

            @Override
            public void onFailure(@NotNull PrismCoreException error) {
                // Handle upload failure
            }
        });

2.14. Get Available Stickers

By default Prism has several Prism sticker packs that can be used freely. In order to use that, you must enable your sticker packs in Prism dashboard by selecting Settings -> Stickers menu.

PrismCore
    .getInstance()
    .getStickers(oauth.getAccessToken(), new Callback<StickerResponse>() {
                @Override
                public void onSuccess(StickerResponse response) {
                    // Get stickers success
                    List<StickerPack> packs = response.getPacks();
                    // Each sticker pack also have list of stickers
                    StickerPack packOne = packs.get(0);
                    List<Sticker> stickers = packOne.getStickers();
                }

                @Override
                public void onFailure(@NotNull PrismCoreException error) {
                    // Handle failure
                }
            });

2.15. Refresh Token

Oauth credentials can be expired. Visitor can request a new oauth credentials by doing refresh token using current refresh token and client id obtained on visitor connect.

PrismCore
    .getInstance()
    .refreshToken(oauth.getRefreshToken(), oauth.getClientId(), new Callback<RefreshTokenResponse>() {
        @Override
        public void onSuccess(RefreshTokenResponse response) {
            // Handle response
        }

        @Override
        public void onFailure(@NotNull PrismCoreException error) {
            // Handle failure
        }
    });

Notes:

  • oauth is API credentials obtained at visitor connect step.

2.16. Update Visitor Data

Currently, Prism only allow visitor to update their name.

UpdateVisitorRequest updateVisitorRequest = new UpdateVisitorRequest(
    visitor.getId(), 
    UPDATED_VISITOR_NAME
);

PrismCore
    .getInstance()
    .updateVisitorData(updateVisitorRequest, oauth.getAccessToken(), new Callback<UpdateVisitorResponse>() {
            @Override
            public void onSuccess(UpdateVisitorResponse response) {
                // Handle success
            }

            @Override
            public void onFailure(@NotNull PrismCoreException error) {
                // Handle failure
            }
        });

2.17. Auto Assignment

Auto assignment feature activation is required if you want to use it on your Android application. Please tell our integration team if you want to activate it.

Since version 0.1.4.0, Prism Android SDK supports auto assignment feature that has already been supported by web widget previously.

Notes: UI SDK is already handled it automatically just like on the web version.

Since you are using Core SDK, this documentation will help you implement the auto assignment feature on your Android application.

2.17.1 Receive Auto Responder Message

This part assume that you already implemented message broker subscription to specific topic.

When user sent first message on a conversation, they will receive an auto responder message that contains the information of the assignment department selection.

Here are how you filter auto responder message when you get it from message broker subscription callback.

PrismCore
    .getInstance()
    .subscribeToTopic(conversation.getTopic(), new MessageSubscriptionCallback() {
                @Override
                public void onMessageReceived(@NotNull Message<?> response) {
                    // New message received
                    // Each type must be parsed differently
                    switch (response.getType()) {
                        // ... Handle for another type
                        case MessageType.AUTO_RESPONDER:
                            Message<ContentAutoResponder> autoResponderMessage = (Message<ContentAutoResponder) response;
                            handleAutoResponderMessage(autoResponderMessage);
                            break;
                    }
                }

                @Override
                public void onMessageSubscriptionError(@NotNull PrismCoreException exception) {
                    // Handle failure when subscribing to a topic
                }
            });

Handle it in a new function called handleAutoResponderMessage

The department list were contained at message.content.auto_responder. You must get its content before you present it to your visitors.

private void handleAutoResponderMessage(Message<ContentAutoResponder> message) {
    ContentAutoResponder content = message.content;
    String message = content.autoResponder.text;
    List<Department> departmentList = content.autoAssignment.departments; 
}

Here is the example how the UI SDK version show the auto assignment selection message.

2.17.2 Handle Department Selection

After your visitors select the department, you can build the request object.

SmartAssignmentRequest smartAssignmentRequest = new SmartAssignmentRequest(
    SELECTED_DEPARTMENT_ID,
    conversation.getId()
);

PrismCore
    .getInstance()
    .selectDepartmentForAssignment(smartAssignmentRequest, oauth.getAccessToken(), new Callback<Object>() {
        @Override
        public void onSuccess(Object response) {
            // Handle success
        }

        @Override
        public void onFailure(@NotNull PrismCoreException error) {
            // Handle failure
        }
});

You can assume it's a success if you receive success callback.

When it's success, you may hide the selection from your message view. Please save it locally, so it won't be shown again in the next time your visitor opening your application.

Notes: Don't forget to clear the selected department from local data when the conversation is closed and visitor decides to start a new conversation so when auto responder message came, your visitors can select the department again.

Here is the example how the UI SDK version show that visitors are already select the department previously.

2.18. Handle Failure

There are several error types available from PrismCoreException.

Error Types Description
NoInternetError No network connection
NetworkError There are problems when sending API request
ServerError Backend related error. Check code and message for more details.
UnauthorizedError Invalid authorization token. Please refresh the token.
InvalidTokenError After refreshing token, the token still is invalid.
MessagingBrokerError Messaging broker related error. See message for more details.
UnknownError Unknown error. See message for more details.

Here is some example to check the error in Java.

private void checkError(PrismCoreException error) {
        if (error instanceof ServerError) {
            ServerError serverError = (ServerError) error;
            // Handle server error
        } else if (error instanceof NoInternetError) {
            // Handle no internet error
        } else if (error instanceof NetworkError) {
            // Handle network error
        } else if (error instanceof UnauthorizedError) {
            // Handle unauthorized error
        } else if (error instanceof MessagingBrokerError) {
            // Handle messaging broker error
        } else if (error instanceof InvalidTokenError) {
            // Handle invalid token error
        } else {
            // Handle unknown error
        }
}

2.19. Handle Push Notification

Prism system provides push notification for merchant who wants to use it via Firebase Cloud Messaging (FCM).

2.19.1. Integrate Firebase to Android Project
  1. Open Firebase website at https://firebase.google.com/
  2. Click go to console to register using google account.
  3. On Firebase console, please create a project.
  4. Fill project name and country.
  5. Wait for a while when the project is created. Then the project page was opened.
  6. Add your Android app by clicking `Add Firebase to your Android app. Only your app's package name is required.
  7. Please download google-services.json and add it to app's module in your Android project.
  8. Follow Firebase instruction to integrate Firebase to Android project.
2.19.2. Obtain Firebase Server Key and Sender Key
  1. Back on Firebase console. Please open settings page.
  2. Go to CLOUD MESSAGING tab. Find your server key and sender id there.
  3. You need to tell our integration team these credentials so we can integrate the push notification service to your application.
2.19.3. Add Firebase Messaging Dependencies to Android Project

On your app's module build.gradle, you need to add these lines.

dependencies {
     compile 'com.google.firebase:firebase-messaging:10.2.4'
}
2.19.4. Send Device Token

To identify specific visitor device, merchant need to send their visitor's device token to Prism system.

First, create a class extends from FirebaseInstanceIdService. For example, the class name is MyFirebaseInstanceIdService.

Merchant needs to override onTokenRefresh. It's a callback whenever new token is created or updated by Firebase.

public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String refreshedToken) {
        Device device = new Device(DEVICE_ID, refreshedToken, Device.ANDROID_TYPE);
        PrismCore.getInstance().updateDeviceForFcm(
                device,
                visitor.getId(),
                oauth.getAccessToken(),
                new Callback<Device>() {
                    @Override
                    public void onSuccess(Device response) {
                        // Handle success registering
                    }

                    @Override
                    public void onFailure(PrismCoreException error) {
                        // Handle failed to register
                    }
                }
        );
    }

}

Second, register created MyFirebaseInstanceIdService to app's manifest.

<service
    android:name=".MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>
2.19.5. Handle received message

To receive message in Firebase, merchant need to add a class extends from FirebaseMessagingService. For example, the class name is MyFirebaseMessagingService.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        String messagePayload = remoteMessage.getData().get(PrismCore.MESSAGE_PAYLOAD);
        // Handle message payload here
    }
}

Notes: - messagePayload is stringified version of message payload. See below example for text message notification.

    {
        "_broker_metadata": {
            "timestamp": "2017-08-01T04:11:37.268Z"
        },
        "channel": "ANDROID_SDK",
        "content": {
            "text": "jghjhgjhgjhgjhg"
        },
        "conversation_id": "710ee451-386d-436a-8717-726292eb8318",
        "id": "7fe3d5d1-8204-4698-95c3-7c9259d90fb4",
        "merchant_id": "fc69d550-07fa-44e6-9c03-b35250a7bd43",
        "sender": {
            "id": "f1e18088-cecc-4042-98fb-1e1e42f9e212",
            "name": "Sender Name",
            "role": "Agent",
            "user_agent": "PrismDashboard-v0.1.34.2"
        },
        "type": "text",
        "version": 2,
        "visitor": {
            "channel": "ANDROID_SDK",
            "id": "8a1cebd3-f4af-4598-aee6-e12079f3a161",
            "name": "visitor"
        }
    }

For more information about the message payload specification you can see Prism message specification here.


Then register created MyFirebaseMessagingService into app's manifest.

<service
    android:name=".MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

2.20. Multidex

You may encounter a problem when building your app after integrating with Prism. It's called DexOverflowException problem that is caused because your application package total method count is over 65k (limitation of Android).

To get rid of this problem, you can enable MultiDex on your build.gradle.

Here is the setup on your build.gradle.

defaultConfig {
        ... // other config
        multiDexEnabled true
    }

dependencies {
    ... //other config
    compile 'com.android.support:multidex:1.0.1'
}

Also you need to initialize the Multidex on your App class.

public class App extends Application {

    @Override
    public void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }
}

Make sure it's used on your AndroidManifest.xml.

<application
    ...//other config
    android:name=".App">