微信开发系列之三 - 在微信公众号里发起SAP C4C Account的创建
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://<host_name>/sap/c4c/odata/v1/c4codata/IndividualCustomerCollection/",
credential: "<your user name>:<your password>",
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:
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- 【Java基础-2】构造函数与构造代码块
- 【Java基础-3】数据结构之JSON浅析
- linux环境svn服务端及windows环境客户端安装配置
- 【Java集合-1】整体框架
- 【Java集合-2】HashMap简析
- 【Java集合-3】ArrayList简析
- Springboot之Security前后端分离登录
- Windows 10使用WSL作为python宿主机调试开发
- 小米正式开源 SQL 智能优化与改写工具 SOAR
- 【SpringBoot-1】面向小白编程:从0开始创建一个SpringBoot项目
- 【SpringBoot-3】Lombok使用详解
- 【JMeter系列-3】JMeter元件详解之配置元件
- 【JMeter-4】JMeter元件详解之逻辑控制器
- 【JMeter-4】JMeter关联:JMeter正则表达式提取器与JSON提取器
- 【JMeter系列-5】JMeter操作Mysql数据库