天天看點

SAP Marketing Cloud Restful API SDK 使用案例分享

本文介紹筆者在 SAP Marketing Cloud 工作項目中使用 Restful API SDK 過程中積累的一些使用經驗。

成功登入 SAP Marketing Cloud 系統之後,可以在菜單"快速啟動"->"Manage Contacts"裡找到Marketing Cloud contact管理應用。單擊:

SAP Marketing Cloud Restful API SDK 使用案例分享

這裡就能看到該系統裡所有的contact清單了。

左邊的1218377是系統contact總個數,正下方Create就是建立按鈕,可以通過這個按鈕打開contact建立頁面。右邊的search bar就是一個Google風格的模糊搜尋入口。

SAP Marketing Cloud Restful API SDK 使用案例分享

這個界面第一次使用的話需要注意一些小技巧。

SAP Marketing Cloud Restful API SDK 使用案例分享

上圖高亮的四個控件實際上是四個過濾器,例如目前系統裡并不存在狀态為For Review的contact,數字為0,是以單擊這個過濾器後:

SAP Marketing Cloud Restful API SDK 使用案例分享

表格會顯示0條資料。這是使用者期望的行為,是以大家如果看到表格是空的,不要覺得奇怪。

SAP Marketing Cloud Restful API SDK 使用案例分享

當單擊某條contact資料的超連結後,

SAP Marketing Cloud Restful API SDK 使用案例分享

會跳轉到contact明細頁面. 下圖url裡高亮的guid就是這條contact在SAP資料庫裡的主鍵值。

SAP Marketing Cloud Restful API SDK 使用案例分享

使用nodejs對Marketing Cloud的contact主資料進行修改操作

假設在Marketing Cloud有這樣一個contact主資料:

SAP Marketing Cloud Restful API SDK 使用案例分享

現在需求是使用程式設計語言比如nodejs修改這個contact執行個體的高亮屬性。

代碼如下:

var config = require("./mcConfig");
var request = require('request');

var url = config.tokenURL;

console.log("user: " + config.user + " password: " + config.password); 
var getTokenOptions = {
        url: url,
        method: "GET",
        json:true,     
        headers: {
            'Authorization': 'Basic ' + new Buffer(config.user + ":" + config.password).toString('base64'),
            "content-type": "application/json",
            "x-csrf-token" :"fetch"
        }
};

function getToken() {
  return new Promise(function(resolve,reject){
      var requestC = request.defaults({jar: true});
      console.log("Step1: get csrf token via url: " + url );

      requestC(getTokenOptions,function(error,response,body){
       var csrfToken = response.headers['x-csrf-token'];
       if(!csrfToken){
          reject({message:"token fetch error: " + error});
          return;
       }
       console.log("Step1: csrf token got: " + csrfToken);
       resolve(csrfToken);
      }); 
     });
}

function updateContact(token){
    return new Promise(function(resolve, reject){
        var sPostData = "--batch_1f7d-bd35-caed" + "\n" + 
  "Content-Type: multipart/mixed; boundary=changeset_8f9e-9a44-9f9e" + "\n" + 
  "\n" + 
  "--changeset_8f9e-9a44-9f9e" + "\n" + 
  "Content-Type: application/http" + "\n" + 
  "Content-Transfer-Encoding: binary" + "\n" + 
  "\n" + 
  "MERGE Consumers('02000A21209F1EE99CDF1A1FC9AA8065')?sap-client=100 HTTP/1.1" + "\n" + 
  "Cache-Control: max-age=360" + "\n" + 
  "sap-contextid-accept: header" + "\n" + 
  "Accept: application/json" + "\n" + 
  "Accept-Language: en" + "\n" + 
  "DataServiceVersion: 2.0" + "\n" + 
  "MaxDataServiceVersion: 2.0" + "\n" + 
  "x-csrf-token: fQ2Pwfmf0K_LVYoKV9QYUw==" + "\n" + 
  "Content-Type: application/json" + "\n" + 
  //"Content-Length: 215" + "\n" + 
  "\n" + 
  "{\"YY1_CustomerType_ENH\":\"Jerry測試1\"}" + "\n" + 
  "--changeset_8f9e-9a44-9f9e--" + "\n" + 
  "\n" + 
  "--batch_1f7d-bd35-caed--";

        var requestC = request.defaults({jar: true});
    var createOptions = {
              url: config.updateContactURL,
              method: "POST",
              json:false,
              headers: {
                  "content-type": "multipart/mixed;boundary=batch_1f7d-bd35-caed",
                  'x-csrf-token': token
              },
              body:sPostData
        };
        requestC(createOptions,function(error,response,data){
            if(error){
                reject(error.message);
            }else {
               debugger;
               console.log("Contact updated successfully");
               resolve(data);
            }
        });
    });
}

getToken().then(updateContact).catch((error) =>{
  console.log("error: " + error.message);
});      

我在nodejs代碼裡把需要更改的字段值賦為"Jerry測試1”:

執行之後這個屬性被成功更新了:

SAP Marketing Cloud Restful API SDK 使用案例分享
SAP Marketing Cloud Restful API SDK 使用案例分享

使用postman修改SAP Marketing Cloud contact主資料

Marketing Cloud裡的contact主資料,建立成功後也不是所有字段都能夠被修改。在Personal data區域的字段是可以被修改的。

SAP Marketing Cloud Restful API SDK 使用案例分享

比如我在“客戶屬性”字段裡維護了一些值:

SAP Marketing Cloud Restful API SDK 使用案例分享

然後點儲存:

SAP Marketing Cloud Restful API SDK 使用案例分享

其中第二個batch操作是通過一個roundtrip讀取contact模型下多個子節點的資料,和我們這個修改的場景沒有關聯。

使用postman進行修改:

SAP Marketing Cloud Restful API SDK 使用案例分享

body字段維護以下内容:

--batch_1f7d-bd35-caed
Content-Type: multipart/mixed; boundary=changeset_8f9e-9a44-9f9e
--changeset_8f9e-9a44-9f9e
Content-Type: application/http
Content-Transfer-Encoding: binary
MERGE Consumers('02000A21209F1EE99CDF1A1FC9AA8065')?sap-client=100 HTTP/1.1
Cache-Control: max-age=360
sap-contextid-accept: header
Accept: application/json
Accept-Language: en
DataServiceVersion: 2.0
MaxDataServiceVersion: 2.0
x-csrf-token: fQ2Pwfmf0K_LVYoKV9QYUw==
Content-Type: application/json
Content-Length: 215
{"__metadata":{"uri":"https://jerry.hybris.com/sap/opu/odata/sap/CUAN_CONTACT_SRV/Consumers('02000A21209F1EE99CDF1A1FC9AA8065')","type":"CUAN_CONTACT_SRV.Consumer"},"YY1_CustomerType_ENH":"Jerry測試2"}
--changeset_8f9e-9a44-9f9e--
--batch_1f7d-bd35-caed--      

我想修改的字段的新的值為:Jerry測試2

執行postman後,發現值已經更新了,修改成功

SAP Marketing Cloud Restful API SDK 使用案例分享

使用nodejs建立Marketing Cloud的contact資料

源代碼如下:

var config = require("./mcConfig");
var request = require('request');

var url = config.tokenURL;

console.log("user: " + config.user + " password: " + config.password); 
var getTokenOptions = {
        url: url,
        method: "GET",
        json:true,     
        headers: {
            'Authorization': 'Basic ' + new Buffer(config.user + ":" + config.password).toString('base64'),
            "content-type": "application/json",
            "x-csrf-token" :"fetch"
        }
};

function getToken() {
  return new Promise(function(resolve,reject){
      var requestC = request.defaults({jar: true});
      console.log("Step1: get csrf token via url: " + url );

      requestC(getTokenOptions,function(error,response,body){
       var csrfToken = response.headers['x-csrf-token'];
       if(!csrfToken){
          reject({message:"token fetch error: " + error});
          return;
       }
       console.log("Step1: csrf token got: " + csrfToken);
       resolve(csrfToken);
      }); 
     });
}

function createContact(token){
    return new Promise(function(resolve, reject){
        var oPostData = {"CountryCode":"CN",
                    "City":"Chengdu",
                    "FirstName":"Jerry4",
                    "LastName":"Wang2",
                    "PostalCode":"610093",
                    "RegionCode":"",
                    "Street":"天府軟體園",
                    "HouseNumber":"天府軟體園",
                    "DateofBirth":null,
                    "ContactPersonFacets":[
                      {"Id":"[email protected]",
                       "IdOrigin":"EMAIL",
                       "Obsolete":false,
                       "Invalid":false},
                       {"Id":"",
                       "IdOrigin":"PHONE",
                       "Obsolete":false,
                       "Invalid":false},
                       {"Id":"",
                       "IdOrigin":"MOBILE",
                       "Obsolete":false,
                       "Invalid":false},
                       {"Id":"",
                       "IdOrigin":"FAX",
                       "Obsolete":false,
                       "Invalid":false}
                       ],
                       "IsConsumer":true,
                       "Filter":{
                        "MarketingAreaId":"CXXGLOBAL"
                      }
                    };
        var requestC = request.defaults({jar: true});
        var createOptions = {
              url: config.createContactURL,
              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 {
               var oCreatedContact = data;
               console.log("created contact ID: " + oCreatedContact.d.ContactPersonId);
               resolve(data);
            }
        });
    });
}

getToken().then(createContact).catch((error) =>{
  console.log("error: " + error.message);
});      

這裡我把建立的contact的名稱字段寫死成Jerry4:

SAP Marketing Cloud Restful API SDK 使用案例分享

使用nodejs執行這個js檔案,輸出成功建立的contact guid:

SAP Marketing Cloud Restful API SDK 使用案例分享

在Marketing Cloud UI上看到這個建立成功的contact:

總結

繼續閱讀