Wechat development series 3 – Trigger C4C Account creation in Wechat app

* Wechat development series 1 – setup your development environment
* Wechat development series 2 – development Q&A service using nodejs
* Wechat development series 3 – Trigger C4C Account creation in Wechat app

Tencent’s WeChat, a social networking app with more than 760 million monthly active users, is becoming a dominant mobile channel connecting businesses and customers. In previous blogs we have already setup the environment for Wechat development and build some toy services to get familar with overall process. In this blog, we will implement some feature which interacts with C4C system. The implementation contains purely nodejs development via Javascript and do not need any development in C4C side.

Implemented feature

Here below is my testing subscription account. When I scan it via my Wechat app, I can click the Green button “关注” ( subscribe ) to finish subscription to this account. After the button is pressed, I will received a welcome message sent automatically from this test subscription account: And then a new individual customer will be created in a configured C4C system via OData service. Once created, I will see the ID of created account in Wechat app: This created account has first name as hard coded “Wechat” and last name equals to the technical id of Wechat account who has performed the QRCode scan activity. Here below is the screenshot of created account in C4C system.

Detail implementation steps

1. Create a configuration module in your nodejs project with the following settings: var config = { individualCustomerurl: “https:///sap/c4c/odata/v1/c4codata/IndividualCustomerCollection/”, credential: “:”, accessToken: “access token of your test subscription account” }; module.exports = config; You must maintain a valid user name and password which could have access to create new individual customer in your C4C system. The access token will be used when you try to send a message to an user who has subscribed your Wechat account via Wechat Restful API. It will expire by default 2 hours after generation. The token could be refreshed based on appid and secret. For simplification purpose I just generate the token and store it in configuration file. 2. Once a Wechat user presses “subscribe” button, an event with HTTP post will be sent to the Wechat server which is bound to your subscription account. As a result we have to react to this post request, parse the Wechat ID which has clicked the “subscribe” button, and create a new individual customer in C4C system based on this Wechat ID. Here below is the source code how we react to the event with event key “subscribe”. (1) the welcome message “Welcome to Jerry’s subscription account” is hard coded (2) The Wechat ID of user who has finished subscription is stored in variable fromUserName var request = require(‘request’); var createAccount = require(“../service/createAccountInC4C.js”); var getXMLNodeValue = require(“../tool/xmlparse.js”); var formattedValue = require(“../tool/formatValue.js”); var replyMessage = require(“../tool/replyMessage.js”); module.exports = function (app) { app.route(’/’).post(function(req,res){ var _da; req.on(“data”,function(data){ _da = data.toString(“utf-8”); }); req.on(“end”,function(){ console.log(“new http post: ” + _da); var msgType = formattedValue(getXMLNodeValue(‘MsgType’,_da)); if( msgType === “event”){ var event = formattedValue(getXMLNodeValue(‘Event’,_da)); if( event === “subscribe”){ var replyxml = replyMessage(_da, “Welcome to Jerry’s subscription account”); var fromUserName = formattedValue(getXMLNodeValue(‘FromUserName’,_da)); createAccount(fromUserName); res.send(replyxml); } } }); }); }; 3. The individual customer is created by C4C OData service implemented in module createAccountInC4C.js. var config = require(“../../config.js”); var request = require(‘request’); var postWCMessage = require(“./postMessageToUser.js”); var getTokenOptions = { url: config.individualCustomerurl, method: “GET”, json:true, headers: { “content-type”: “application/json”, ‘Authorization’: ‘Basic ’ + new Buffer(config.credential).toString(‘base64’), “x-csrf-token” :“fetch” } }; function getToken() { return new Promise(function(resolve,reject){ var requestC = request.defaults({jar: true}); requestC(getTokenOptions,function(error,response,body){ var csrfToken = response.headers[‘x-csrf-token’]; if(!csrfToken){ reject({message:“token fetch error”}); return; } resolve(csrfToken); }); // end of requestC }); } function _createIndividualCustomer(token, fromUserName){ return new Promise(function(resolve, reject){ var oPostData = { “FirstName”:“Wechat”, “LastName”:fromUserName, “RoleCode”: “ZCRM01”, “CountryCode”: “US”, “StatusCode”: “2” }; var requestC = request.defaults({jar: true}); var createOptions = { url: config.individualCustomerurl, method: “POST”, json:true, headers: { “content-type”: “application/json”, ‘x-csrf-token’: token }, body:oPostData }; requestC(createOptions,function(error,response,data){ if(error){ reject(error.message); }else { resolve(data); } });// end of requestC }); } module.exports = function createAccount(fromUserName){ getToken().then(function(token) { console.log(“token received: ” + token); _createIndividualCustomer(token, fromUserName).then(function(data){ var message = “account created: ” + data.d.results.CustomerID; console.log(message); postWCMessage(fromUserName, message); }); }); }; In the code the first name of created account is hard code as Wechat and the last name is filled with variable fromUserName parsed from previous step. 4. Once individual customer is created in C4C system successfully, a responsible message will be sent to Wechat subscription account user to notify him/her with the ID of created account. This reply is implemented by Wechat message Restful API: var config = require(“../../config.js”); var request = require(“request”); function printObject(oData){ for( var a in oData){ console.log(“key: ” + a); console.log(“value: ” + oData[a]); if( typeof oData[a] === “object”){ printObject(oData[a]); } } } function sendWCMeaasge(toUser,sMessage){ console.log(“begin to send message to user: ” + toUser + “ with message: ” + sMessage); var options = { url:“https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=” + config.accessToken, method: “POST”, json:true, headers: { “content-type”: “application/json”}, body:{ “touser”:toUser, “msgtype”:“text”, “text”: { “content”:sMessage } } }; request(options,function(error,response,data){ console.log(“Status message: ” + response.statusMessage); console.log(“Data: ” + data.errmsg); }); } module.exports = sendWCMeaasge; It is very convenient to use this Restful API to send message to a given Wechat user who has subscribed the testing account. You could test it in postman: http://bit.ly/2CYDil7 #SAP #SAPCloud #AI

Machine Learning, Manufacturing and Production and the OODA Loop

US Airforce Pilot and researcher John Boyd once proposed a model known as the OODA Loop   Observe, Orient, Decide, Act.   Boyd suggested that, two pilots locked in a battle would constantly need to observe what their opponent was doing, orient themselves in relation to their opponent’s tactical maneuvering, decide what they should do and then act to counteract the opponent’s tactics.  At the same time, the opponent would be doing the same thing.  As a “loop” this ballet would continue until one pilot could get “inside” of their opponent’s OODA Loop and process enough information quicker than the opponent could react, and that pilot would typically win the fight.

In essence, this is what machine learning today is all about.  The only difference is that we use computers to:

* Observe – collect the relevant data on a business process (data management to us mere data mortals)
* Orient – develop an algorithm that will process the data and predict the likelihood of an optimal result (data science)
* Decide – Using predictive analytics, model and evaluate the alternatives and recommend a course of action
* Act – Execute a business process, transaction or function to produce a business result

Once a cycle of this OODA loop has executed, the machine needs to re-observe the resultant micro-business environment, re-evaluate the results of the action that we just took (orient) and update its data and algorithms (decide) and (re)act.

Nowhere is this OODA loop of machine learning more obvious, tactical and tangible than in the area of manufacturing and production processes.  Take quality control for example.  In this highly simplified view of manufacturing Quality Control, first we detect a defect.  How is the defect detected?  It is observed. Perhaps a Quality Technician physically identifies the defect during a routine inspection.  Alternatively, we could develop an automated process that uses sensors to identify the defect based on optical scans of the product or line item tests of product standards (learn more about the internet of things here).  Next, orient.  All relevant and significant information is recorded in a high volume, high speed database (Big Data and HANA).  A Quality Engineer then analyzes the root cause of the defect and makes a recommendation for actions to be taken to remediate the defect (decide).  Finally, the Quality Engineer takes an action to correct the defect as well as what caused it (act) and the process repeats itself.

In this “loop”,  machine learning can play a critical role:

* During the observe stage, an algorithm can be developed based on past defect history to look for certain, very specific problems, but more importantly areas where problems might Think of the fighter pilot who knows what most average opponents would do in a tactical situation, as well as what an innovative opponent might do.  Further, if this set of actions has been recorded and can be observed in a fraction of an instant – we have an opportunity to get inside that opponent (or strategic competitor’s) decision loop.
* During the orient stage, machine learning could be used to cycle through all of the known root causes for a specific defect, or even to be on the lookout for clues to potential new causes.
* Machine learning can be used during the decide phase to dynamically learn – or to constantly expand the universe of potential courses of action while using analytics to create predictive models of the possibilities of success of alternative strategies for remediation as business conditions continue to expand.
* Once we make our QC decision and act, that action goes into our history of actions and we can assess the results of our actions to repeat this learning cycle.

By using machine learning and the OODA loop, we are now able to accelerate decision making and respond more effectively and more rapidly not only to our own quality issues but to understand our own quality control environment in the context of our competitors.  Once we can observe, orient, decide and act on all of the variables in our manufacturing and production environment – faster and with better information than our competitors, quality control can become a strategic lever which we can use against our competitors who are no longer able to out-innovate, out-produce or out-QC our operations.

In the next blog in this series, we will have a look into what it takes to start a program of machine learning.  What kind of data do I need?  Who processes all of this data?  Am I staffed right for this type of effort?  What sort of infrastructure will I need to build this framework?

This will help us get inside of our competitor’s OODA loop

Share your thoughts with me here, or on Twitter @SDenecken.    http://bit.ly/2EcOV7t #SAP #SAPCloud #AI