Monday, November 25, 2013

[NodeJS + Salesforce SOAP WS] How to consume a Salesforce SOAP WSDL

I was wondering how to consume Salesforce WSDLs with nodejs.
I found Node Soap package (see npm) and I tried to consume a Partner WSDL.
Then I saved the WSDL in the "sf-partner.wsdl" file and played with the methods to get nodeJS speak SOAP with Salesforce.

var soap = require('soap');
var url = './sf-partner.wsdl';
soap.createClient(url, function(err, client) {
   console.log('Client created');
   console.log(client.SforceService.Soap); //all methods usable in the stub
});

If you try to console.log(client) you will see too much data

This is the output:

{ login: [Function],
  describeSObject: [Function],
  describeSObjects: [Function],
  describeGlobal: [Function],
  describeDataCategoryGroups: [Function],
  describeDataCategoryGroupStructures: [Function],
  describeFlexiPages: [Function],
  describeAppMenu: [Function],
  describeGlobalTheme: [Function],
  describeTheme: [Function],
  describeLayout: [Function],
  describeSoftphoneLayout: [Function],
  describeSearchLayouts: [Function],
  describeSearchScopeOrder: [Function],
  describeCompactLayouts: [Function],
  describeTabs: [Function],
  create: [Function],
  update: [Function],
  upsert: [Function],
  merge: [Function],
  delete: [Function],
  undelete: [Function],
  emptyRecycleBin: [Function],
  retrieve: [Function],
  process: [Function],
  convertLead: [Function],
  logout: [Function],
  invalidateSessions: [Function],
  getDeleted: [Function],
  getUpdated: [Function],
  query: [Function],
  queryAll: [Function],
  queryMore: [Function],
  search: [Function],
  getServerTimestamp: [Function],
  setPassword: [Function],
  resetPassword: [Function],
  getUserInfo: [Function],
  sendEmailMessage: [Function],
  sendEmail: [Function],
  performQuickActions: [Function],
  describeQuickActions: [Function],
  describeAvailableQuickActions: [Function] }

There is a quicker way to obtain this using the console.log(client.describe()) function, but this seems not to work with big WSDL like Salesforce ones (Maximum stack error)

The first move was to login to obtain a valid session id (using SOAP login action):

soap.createClient(url, function(err, client) {
    client.login({username: 'user@name.com',password: 'FreakPasswordWithTkenIfNeeded'},function(err,result,raw){
      if(err)console.log(err);
      if(result){
          console.log(result.result);
    });
});

And this is the result

{ metadataServerUrl: 'https://na15.salesforce.com/services/Soap/m/29.0/00Di0000000Hxxx',
  passwordExpired: false,
  sandbox: false,
  serverUrl: 'https://na15.salesforce.com/services/Soap/u/29.0/00Di0000000Hxxx',
  sessionId: 'XXXXXXXXXX',
  userId: '005i0000000MXXXAAC',
  userInfo: 
   { accessibilityMode: false,
     currencySymbol: '€',
     orgAttachmentFileSizeLimit: 5242880,
     orgDefaultCurrencyIsoCode: 'EUR',
     orgDisallowHtmlAttachments: false,
     orgHasPersonAccounts: false,
     organizationId: '00Di0000000HxxxXXX',
     organizationMultiCurrency: false,
     organizationName: 'Challenges Co.',
     profileId: '00ei0000000UM6PAAW',
     roleId: {},
     sessionSecondsValid: 7200,
     userDefaultCurrencyIsoCode: {},
     userEmail: 'user@email.com',
     userFullName: 'Admin',
     userId: '005i0000000MxxxXXX',
     userLanguage: 'en_US',
     userLocale: 'en_US',
     userName: 'user@name.com',
     userTimeZone: 'Europe/Rome',
     userType: 'Standard',
     userUiSkin: 'Theme3' } }

Now the problem was to put the new endpoint and the session id or the next call, and this is the solution:

  //sets new soap endpoint and session id
  client.setEndpoint(result.result.serverUrl);
  var sheader = {SessionHeader:{sessionId: result.result.sessionId}};
  client.addSoapHeader(sheader,"","tns","");

And after that you can make wathever call you want:

      client.query({queryString:"Select Id,CaseNumber From Case"},function(err,result,raw){
          if(err){
            //console.log(err);
            console.log(err);
          }
          if(!err && result){
            console.log(result);
          }
      });

The result var will have all the data you expect from the SOAP response:

{ result: 
   { done: true,
     queryLocator: {},
     records: 
      [ [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object] ],
     size: 26 } }

The fact that you cannot call the client.describe() force us to read the WSDL to know which parameters send to the call.

No comments:

Post a Comment