Skip to Content

PS: Final demo at end of blog.

Finally, one of the demo which was on my Wish-list for long, to bring together different technologies and see how it all fits in has been completed. The sense of satisfaction is evident after getting this mash up of technologies up and running although a basic example.

High Level Idea

At a high level the user will interact with the chatbot to trigger request for Purchase Order creation. The request creation will trigger the SAP Cloud platform workflow approval of his/her manager.   So, we will be using Google Dialog flow to act as our interface between user and SAP Cloud platform. User will interact with Dialog Flow chatbot, the chatbot will call the PHP API via webhook to place the Purchase order request. The PHP script will consume SAP Cloud Platform API’s and trigger the workflow. The workflow will be sent to the manager for approval via SAPUI5 App.

We have not covered here the purchase order creation part once workflow is approved. This will be covered later.

Technology Stack Used

  • Dialog Flow for chat bots
  • PHP Script acting as bridge between DialogFlow and SAP Cloud Platform API
  • SAP Cloud Platform Workflow API
  • SAP Cloud Platform Workflow frontend designer
  • SAP Cloud Platform SAPUI5 Application

First Struggle – Dialogflow interaction with SAP Cloud Platform API’s

After going through wonderful blog series on SAP cloud platform Workflow by DJ Adams, I wanted to check how does the integration works outside of the SAP Cloud platform world. The thought of creating a chatbot came to my mind and Dialogflow was the obvious choice. By following this tutorial by Othmane, I was able to get the chatbot part working but how do I connect it to my SAP cloud platform Workflow API’s was to be resolved.

While searching on google I found out about the concept of webhooks which can be triggered once a request is fulfilled. They call external API’s to pass the data. I tried consuming our Workflow API’s via webhook directly but since the format of the data being sent was different then needed, it did not work and I was stuck.

Eventually since I have significant exposure to PHP and It triggered my mind to use PHP to interact with SAP Cloud platform. Let the Chatbot calls my API and in turn I will call workflow API in the format it desired. As can be seen from screen shot once the inputs are taken the webhook triggers external PHP API script

PS: I could have also use adding custom coded JS files also but wanted to try out different things.

Second Struggle – Consuming SAP Cloud Platform Workflow API via PHP

So, first part to get the data out of Dialogflow to PHP was accomplished easily. Next challenge was to pass this data to SAP Cloud Platform Workflow via API. A must read blog Scripting the Workflow API with bash and curl from DJ Adams highlighted usage of CURL,  actually helped me in setting the context of how to make the call in PHP using CURL. Luck had it the API call was failing over and over again, it was not going through. I was able to get the XSRF token but could not trigger workflow, each time error was invalid token.

On doing the deeper analysis found out I was closing the CURL connection after every call. Removed the closing call after fetching token did the trick. Finally, this PHP script was able to consume Workflow API’s.  Complete PHP script code shown below.

<?php
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'POST') {
    $request           = file_get_contents('php://input');
    $json              = json_decode($request);
    $parameters        = array();
    $parameters        = $json->result->parameters;
    // Call SAP Cloud platform workflow API  Fetch XSRF token
    $username          = <Enter Cloud username>;
    $password          = <Enter Password>;
    $ch                = curl_init('https://bpmworkflowruntimewfs-<username>trial.hanatrial.ondemand.com/workflow-service/rest/v1/xsrf-token');
    $request_headers   = array();
    $request_headers[] = 'X-CSRF-Token: Fetch';
    $request_headers[] = 'Content-Type: application/json';
    $request_headers[] = 'Accept: application/json';
    $request_headers[] = 'APIKey: <API Key>';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
    curl_setopt($ch, CURLOPT_POST, 0);
    curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($curl, $header) use (&$headers)
    {
        $len    = strlen($header);
        $header = explode(':', $header, 2);
        if (count($header) < 2) { // ignore invalid headers
            return $len;
        }
        $name = strtolower(trim($header[0]));
        if (!array_key_exists($name, $headers)) {
            $headers[$name] = [trim($header[1])];
        } else {
            $headers[$name][] = trim($header[1]);
        }
        return $len;
    });
    $tmpfname = dirname(__FILE__) . '/cookie.dat';
    curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname);
    
    //Call workflow instance API, pass token and other data and trigger workflow
    $resp                              = curl_exec($ch);
    $context                           = array();
    $context["context"]["material"]    = $parameters->POMaterial;
    $context["context"]["quantity"]    = $parameters->POqty;
    $context["context"]["description"] = $parameters->PODescription;
    $context["definitionId"]           = "mypurchaseorder";
    curl_setopt($ch, CURLOPT_URL, 'https://bpmworkflowruntimewfs-<user name>trial.hanatrial.ondemand.com/workflow-service/rest/v1/workflow-instances');
    $request_headers   = array();
    $request_headers[] = 'X-CSRF-Token: ' . $headers['x-csrf-token'][0];
    $request_headers[] = 'Content-Type: application/json';
    $request_headers[] = 'Accept: application/json';
    $request_headers[] = 'APIKey: <key here>';
    $request_headers[] = 'Content-Length: ' . strlen(json_encode($context));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($curl, $header) use (&$headers)
    {
        $len    = strlen($header);
        $header = explode(':', $header, 2);
        if (count($header) < 2) { // ignore invalid headers
            return $len;
        }
        $name = strtolower(trim($header[0]));
        if (!array_key_exists($name, $headers)) {
            $headers[$name] = [trim($header[1])];
        } else {
            $headers[$name][] = trim($header[1]);
        }
        return $len;
    });
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($context));
    $resp = curl_exec($ch);
    // Close request to clear up some resources
    curl_close($ch);
    $resp1                 = json_decode($resp);
    $response              = new \stdclass();
    $response->speech      = '';
    $response->displayText = 'PO sent for approval';
    $response->source      = 'webhook';
    echo json_encode($response);
}
?>

Final pieces of Puzzle SAPUI5 Application and Workflow

This actually was the easiest part as I simply followed this awesome blog by Christian Loose to create the SAPUI5 Application and workflow with basic approval step.

Final Demo

Next Ideas

  • Explore SAP Cloud Platform Workflow other steps, task type etc.
  • Ionic being close to my heart so would like to see how this workflow works with Ionic framework.

I hope SAP Cloud Platform will also have a Chatbot as a service in future upgrades.

Feel free to provide your feedback, open to all ears.

To report this post you need to login first.

4 Comments

You must be Logged on to comment or reply to a post.

  1. Moya Watson

    Caught the birds in the demo 🙂 You must be working in a beautiful forest!

     

    I love what you’re doing with SAP technology and that you’re exploring SAP Cloud Platform including IoT, APIs, and now Workflow.  Thanks for taking the time to share your great stuff!

     

    PS: Chatbot as a Service!  What a cool idea… <disclaimer: i have no roadmap knowledge here…>

    (1) 
    1. Nabheet Madan Post author

      Thanks Moya Watson for the feedback. Actually the concept of Cloud and Services has altogether added a new twist. Earlier all my thoughts were limited to ABAP, workflow & Webdynpro etc but now it has changed drastically. With all the new buzz words around such as ML, BlockChain, AI, RPA, Cloud etc it makes sense to learn and share the experience it might help someone.

      Thanks

      Nabheet

      (1) 
  2. Nagaraju Nagabandi

    Good Work Nabheet.

    Just FYI. You can also connect with the SAP On premise system(ECC,CRM etc..) with a Restful Webservice. All you need is to format the response of Webhook in JSON( Display Text & Speech) as per the Web hook requirement.

    (1) 
    1. Nabheet Madan Post author

      Thanks Nagaraju for the feedback. I would have loved to expose my on premise system via Odata and all but unfortunately they are all under a secure environment.

      (0) 

Leave a Reply