CX Works

CX Works brings the most relevant leading practices to you.
It is a single portal of curated, field-tested and SAP-verified expertise for SAP Customer Experience solutions

Build and Integrate Your Chatbot with SAP Marketing Cloud

15 min read


Build chatbots with SAP Conversational AI and integrate with SAP Marketing Cloud

If you're an avid user of new technology or spend time browsing the internet, then you’ve probably come across them. They fill your heart with love or rage, they can be frustrating, but sometimes they actually answer your questions within seconds.

Yes, we are talking about Chatbots. 

Chatbots are used across various platforms technologies and industries. You might even find bots talking to bots, which can lead to endless loops of conversations that sometimes generate results. However, we will not cover Bot-to-Bot scenarios or live chats. Instead, we will use a case study to help you understand how you can leverage artificial intelligence (AI) on a customer facing application (and have a little fun).

Table of Contents

Overview

This article will help you:

  • Build a simple Chatbot with SAP Conversational AI
  • Embed Chatbot in a HTML5 Application running on SAP Business Technology Platform
  • Integrate a Chatbot to leverage recommendations on SAP marketing Cloud
  • Kill 15 minutes of your time if you have nothing better to do

Imagine you want to capture visitor data at your booth, but you don’t want your employees typing in the information for each visitor. So, you decide to place tablet computers with a self-service application to let visitors register their information before talking to your staff (maybe you have a super cool raffle for registered visitors). You quickly realize visitors might have questions about the offers they get if they register. You also realize, it would be best to include personalized offerings, from SAP Sales Cloud, to existing customers and provide them with some contextual content.

To answer your dilemma we will use the following solutions:

SAP Business Technology Platform (SAP BTP) Build, deploy, and run our HTML5 application.
SAP Integration Suite Connect processes between our web application, chatbot, and recommendation engine
SAP Marketing Cloud Build a contact profile and configure and manage offer recommendation
SAP Conversational AI Build and maintain our chatbot
SAP Sales Cloud

Customer data source

Technical Configuration Basics

For this End-to-End scenario we need to consider the multiple solutions that are integrated and configured to perform the actions needed to validate this scenario. In our example, all systems are hosted in the cloud and communication between systems is enables using Web Services, APIs, and secure HTTP Endpoints.

Roles:

  • Visitor application

End user registering on the HTML5 Applicattion and using the chat.
Find more information here.

  • Sales: Sales representative using SAP Sales Cloud

SAP Sales Cloud is one of our data sources in this scenario. Contact and sales related data are replicated to SAP Marketing Cloud to build a contact base.This integration is not described in this blog post but the replicated contact records can be used for retrieving offer recommendations and coupon codes from SAP Marketing CLoud from SAP Conversational AI.

  • Marketing: The Marketing Expert creates and maintains the offer recommendations, relevant offers, coupous and customer segments.
  • Developers:

Integration Developer: Builds the integration content for connecting systems and business processes.

Chatbot Developer: Builds and trains the Chatbot that is embedded in the HTML5 Application.


Technical Integration Diagram

The Technical Integration Diagrams (TID) visualizes the technical communication channels between systems, which includes its technical integration paths (highlighted in different colours).

SAP Conversational AI


With SAP Conversational AI you can build and run a chatbot in the cloud.

First, you need an account to get started, visit the SAP Conversational AI website  to create an account and get started for free!

Next, create and open your new chatbot.


Next start training and building your chatbot. You can add “intents” from the library or create new ones. We used existing intents and added a few of our own. Every chatbot needs to be trained to get better at providing user experience.

Let's start building the chatbot. We created a skill for retrieving coupon codes from SAP Marketing Cloud, a skill for small-talk, and a fallback skill. But, in this article we only focus on the Coupon skill. Your chatbot needs to know when to trigger a specific skill. To do so, make sure you define an intent

In this case, we’ve defined an intent to get-coupon-code. This intent recognizes when the user asks for a coupon code and triggers the coupon skill. Remember, you have to train your chatbot to properly recognize entries.


You can define specific actions as reactions of recognized user entires in the chat. This can be a simple text response or something more complex, such as calling a third party service and mapping the response to be displayed in the Chat.

In this article, we focus on building a more complex request from SAP Conversational AI to SAP Marketing Cloud using SAP Integration Suite to mediate and transform the request and response. Of course, all this is invisible to the chat user. The chat user just need to type in the request to the chat window and hit enter.

In our example, we want to respond with personalize offers. So, we need to identify the contact on SAP marketing Cloud and read the offers that apply to that contact. To make sure we have all the information to do the available request, you can add a requirement to request additional information form the chat user. For our marketing offers request, we added the requirement to have a valid e-mail before sending the request to SAP Marketing Cloud.

When setting up the Chatbot,  you have to define where you want to use it. You can choose different channels such as Alexa, Line, Slack, Facebook Massenger, Twitch, or Webchat to name a few. Additionally, you can define a persistent static menu to the chat.

SAP Marketing Cloud

Before requesting any offer recommendation from SAP Marketing Cloud, you need to build a customer base on SAP Marketing Cloud. In this example we use a Fiori application to capture and load contact data to SAP Marketing Cloud. You can find more details about the custom application in this blog post.

Define the recommendation scenario you plan to use for the recommendation requests from the chat. You can find more information on creating and maintaining recommendation scenarios here.


Create a new offer and assign the coupon. Detailed information on how to manage offers and coupons is described in the SAP help documentation.

Once the recommendation scenario and offer is assigned, you can test the offer recommendation from any HTTP Client.

Example request:

POST /sap/opu/odata/SAP/CUAN_OFFER_DISCOVERY_SRV/Recommendations/ HTTP/1.1
Host: <SAP Marketing Cloud Host Name>
x-csrf-token: <access token>
content-type: application/json

{
  "UserOriginId": "EMAIL",
  "UserId": "<contact E-Mail address>",
  "RecommendationScenarioId": "BEST_RUN_OFFERS",
  "BasketObjects": [],
  "LeadingObjects": [{
  	"LeadingObjectType": "CUAN_PROD_CATEGORY_HIERARCHY",
	"LeadingObjectId": "ZMTN:bestrunProductCatalog"
    }],
  "ContextParams": [{
    "ContextId": 1,
    "Value": "ONLINE_SHOP",
    "Name": "P_COMM_MEDIUM"
	},
	{
  "ContextId": 2,
    "Value": "X",
    "Name": "P_WITH_COUPON"
  }],
  "Results": [{
     "AssignedCoupon": {}
  }]
}

SAP Business Technology Platform HTML5 Application


We have deployed the HTML5 Application on SAP BTP and configured the connection to SAP Integration Suite and SAP Marketing Cloud.
For more details please refer to this blog post.


SAP Integration Suite

When the Chatbot is built and trained, and the offers on SAP Marketing Cloud maintained, you need to make sure that SAP Conversational AI and SAP Marketing Cloud can communicate and understand each other. To do so, we use Cloud Integration capability within SAP Integration Suite to mediate and orchestrate messages between our chat, custom application, and SAP Marketing Cloud.

We configured the following iFlows:

  • Chatbot Integration with SAP Marketing Cloud
  • Fiori Trade App Integration with SAP Marketing Cloud
  • Please refer to this blog post for details on this scenario.


iFlow configuration

Since this is a synchronous call, we do not have to configure a receiver for our Chatbot. When the message request processing is successful (or not) we map the response and end the process with the response message.

The SAP Conversational AI Webhook sends a notification the the Cloud Integration endpoint where the message is received. In the first step ("set inbound parameter") we are extracting some of the parameters we need during message processing from the inbound JSON message. The webhook is created and configured on SAP Conversational AI as an action on the skill you have defined. You can configure basic authentication against the CPI HTTP endpoint and make sure it is not csrf protected.

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.HashMap
import groovy.json.JsonSlurper

Message processData(Message message) {
    
    //def propertiesMap = message.getProperties()
    //def originalPayload = propertiesMap.get("OriginalMsgPayload")

    def jsonInb = new JsonSlurper().parseText(message.getBody(java.lang.String))

    def conversationid = jsonInb.user.conversationid
	def email = jsonInb.user.email
	def inbmessage = jsonInb.user.message
    def timestamp = jsonInb.user.timestamp
	
    //Properties 
    message.setProperty("conversationid", conversationid)
	message.setProperty("email", email)
	message.setProperty("message", inbmessage)
	message.setProperty("timestamp", timestamp)
	
	//Headers
	 message.setHeader("x-csrf-token", "fetch")
	
    return message
}

Considering this is a synchronous request  we tried to keep the logic to a minimum avoid too many conversions and transformations. We defined a fairly static request message to the Offer Recommendation API in the "define request message" step, which is used to request applicable offer recommendations for the submitted contact. The response is transformed to a message with only the information we need in this scenario and the properties needed to define the loop process. For convenience we added code for transforming xml and json responses.

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.HashMap
import groovy.json.JsonSlurper

Message processData(Message message) {
    
def jsonResponse = new JsonSlurper().parseText(message.getBody(java.lang.String))

def xmlOffers = []
for (i = 0; i < jsonResponse.d.Results.results.size(); i++)
{
	
	//XML 
	String offerId = "<offerId>" + jsonResponse.d.Results.results.OfferId[i] + "</offerId>"
	String offer = "<offer>" + jsonResponse.d.Results.results.Offer[i] + "</offer>"
	String coupon = "<coupon>" + jsonResponse.d.Results.results.AssignedCoupon.Coupon[i] + "</coupon>"
	String couponName = "<couponName>" + jsonResponse.d.Results.results.AssignedCoupon.CouponName[i] + "</couponName>"
	xmlOffers[i] = "<Offer>" + offerId + offer + coupon + couponName + "</Offer>"
	
	//JSON
	/*
	String offerId = "\"offerId\": \"" + jsonResponse.d.Results.results.OfferId[i] + "\","
	String offer = "\"offer\": \"" + jsonResponse.d.Results.results.Offer[i] + "\","
	String coupon = "\"coupon\": \"" + jsonResponse.d.Results.results.AssignedCoupon.Coupon[i] + "\","
	String couponName = "\"couponName\": \"" + jsonResponse.d.Results.results.AssignedCoupon.CouponName[i] + "\""
	xmlOffers[i] = "{" + offerId + offer + coupon + couponName + "}"
	*/
}

//XML
def xmlResponseUnformatted = "<Offers>" + xmlOffers + "</Offers>"
def xmlResponse = xmlResponseUnformatted.toString().replace("[", "").replace("]","").replace(",","")

/*
//JSON
def jsonResponse = "{\"Offer\": " + xmlOffers + "}"
*/

//define properties for looping process
message.setProperty("couponCount", jsonResponse.d.Results.results.size())
message.setProperty("count", "0")
message.setProperty("originalMessage", xmlResponse)

message.setBody(xmlResponse)
return message
}

The loop process loops through the found offer recommendations with assigned coupons, which are valid for the submitted email address, and retrieves the coupon codes for each assigned coupon. Before each run of the process we need to define the correct attributes for the coupon code request. This is done in a script.

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.HashMap

Message processData(Message message) {

def String originalMessage = message.getProperty("originalMessage")
def String sLoopCounter = message.getProperty("count")
def Integer iCounter = new Integer(sLoopCounter)

def xmlPayload = new XmlSlurper().parseText(originalMessage);
message.setProperty("couponName",xmlPayload.Offer[iCounter].coupon);
message.setProperty("offerName",xmlPayload.Offer[iCounter].offer);
//message.setHeader("accept","application/xml");

++iCounter
sLoopCounter = iCounter.toString()
message.setProperty("count",sLoopCounter)

message.setBody(originalMessage);
return message
}

The defined properties are used to dynamically populate the query to the Offer API.

https://<SAP Marketing Cloud>/sap/opu/odata/SAP/CUAN_OFFER_DISCOVERY_SRV/GetCouponCode/Coupon='${property.couponName}'&UserId='${property.email}'&UserOriginId='EMAIL'

The response is transformed and enriched with the properties we have saved in the main process. The new message is persisted in the Cloud Integration data store to be retrieved later when the loop process is finished.

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.HashMap
import groovy.json.JsonSlurper

def Message processData(Message message) {
map = message.getProperties();
	String conversationid = "<conversationid>" + map.get("conversationid") + "</conversationid>"
	String email = "<email>" + map.get("email") + "</email>"
	String chatMessage = "<chatMessage>" + map.get("message") + "</chatMessage>"
	String offerName = "<offerName>" + map.get("offerName") + "</offerName>"
	String couponName = "<couponName>" + map.get("couponName") + "</couponName>"
def jsonResponse = new JsonSlurper().parseText(message.getBody(java.lang.String))

	String couponCode = "<couponCode>" + jsonResponse.d.CouponCode + "</couponCode>"
//XML
def xmlPayload = "<Offer>" + conversationid + email + chatMessage + offerName + couponName + couponCode + "</Offer>"

message.setBody(xmlPayload);
return message
}

The loop process is executed, as long as the condition expression defined in the loop process call is true.

${property.couponCount} != ${property.count}

When the couponCount and count value are equal, we know that we have looped through all coupon codes and are ready to proceed with the message processing.

Since, we might have multiple coupon codes we do a select on the data store where we have saved our transformed message.

The message retrieved from the data store is transformed to the message that will be sent back as a response to our chat.

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.HashMap
import groovy.json.JsonSlurper
import groovy.util.XmlSlurper

def Message processData(Message message) {

def xmlOffersFromDS = new XmlSlurper().parseText(message.getBody(java.lang.String))

def xmlOffers = []
for (i = 0; i < xmlOffersFromDS.message.size(); i++)
{
	String type = "\"type\": \"text\","
	String content = "\"content\": \"Here's something for you: " + xmlOffersFromDS.message.Offer.offerName[i] + ". Use this with this Code: " + xmlOffersFromDS.message.Offer.couponCode[i] + "\""
	xmlOffers[i] = "{" + type + content + "}"
}

//JSON
def jsonChatbotResponse = "{\"replies\": " + xmlOffers + "}"

message.setBody(jsonChatbotResponse);
return message
}

Here is one example how the Response can look like.

{
	"replies": [
		{
			"type": "text",
			"content": "Our response text"
		},
		{
			"type": "text",
			"content": "Our response text"
		}
	]
}


Demo: Chatbot with SAP Fiori Application

Download this short video to view the basic configuration steps are set up.

Demo: Chat conversation with Offers and Coupon Codes from SAP Marketing Cloud

Download this short video to view an example chat conversation with the Chatbot we created.
We only trained some essential skills and focussed on retrieving coupon codes for the submitted usE-Mail address.

Demo: Chatbot walkthrough with multiple Coupon Codes

Download this short video to learn how to embed a chatbot in a website. This video demonstrated displayiong multiple coupon codes.


Conclusion

Chatbots are a great way to interact with users and manage most common requests and interactions. SAP Conversational AI provides easy to use functionalities to build, train, and publish your chatbot on multiple channels. When communicating with other services the webhook functionality is easy to use and provides basic functionality to request data from external services. However, for more complex requests consider using an integration technology, such as SAP Business Technology Platform, to mediate and transform the request and response between SAP Conversational AI and the external service. This can help take off some complexity from the chatbot build and simplify configurations on SAP Conversational AI. SAP Marketing Cloud provides a rich set of capabilities for creating and managing offers and coupon codes. Further, eligibility for offers and the assigned coupon codes can be restricted to specific target groups on SAP Marketing Cloud.

Overlay