Friday, April 23, 2010

Call External Web Service from Salesforce Apex

Call External Web Service from Salesforce Apex

Some times, you may need to call an extenal web service which might have written on a serverside language like .net, php or java.
Once you made your web service on the serverside or you can use a third party web service api.

I will explain you this using Authorize.net payment gateway.
There are several types of payment criterias available for Authorize.net. For an example I will go with CIM (Customer Information Manager)
You will find all the details in Authoirze.net developer documentation.

To do payments on authorize using CIM we need to create customer profile first.

Here is the apex code that calls an external web service.

//Before any Apex callout can call an external site, that site must be registered in the Remote Site Settings page, or the call will fail. The platform, by default, prevents calls to unauthorized network addresses.
//You can do this like this: got Setup->Administration setup->Security controls->Remote site settings->New and add your endpoint URL there.
//In our case the ende point is https://api.authorize.net/soap/v1/Service.asmx.

Public class callExternalWS
{
    public void invokeExternalWs()
    {
        HttpRequest req = new HttpRequest();
        //Set HTTPRequest Method
        req.setMethod('POST');
        req.setEndpoint('https://api.authorize.net/soap/v1/Service.asmx');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'text/xml; charset=utf-8');
        req.setHeader('SOAPAction', 'https://api.authorize.net/soap/v1/CreateCustomerProfile');//
        string b =   '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'+
                      '<soap:Body><CreateCustomerProfile xmlns="https://api.authorize.net/soap/v1/">'+
                      '<merchantAuthentication><name>Merchant name here</name>'+
                      '<transactionKey>Transaction Key here</transactionKey></merchantAuthentication>'+
'<profile><description>description</description>'+
                      '<email>sforce2009@gmail.com</email>'+
                      '<paymentProfiles>'+
                      '<CustomerPaymentProfileType><customerType>individual</customerType>'+
'<payment><creditCard><cardNumber>6011000000000012</cardNumber>'+
                      '<expirationDate>2009-12</expirationDate></creditCard>'+
                      '</payment></CustomerPaymentProfileType></paymentProfiles></profile>'+
                      '</CreateCustomerProfile></soap:Body></soap:Envelope>';
        req.setBody(b);
        Http http = new Http();
        try {
          //Execute web service call here       
          HTTPResponse res = http.send(req);   
          //Helpful debug messages
          System.debug(res.toString());
          System.debug('STATUS:'+res.getStatus());
          System.debug('STATUS_CODE:'+res.getStatusCode());
        //YOU CAN ALWAYS PARSE THE RESPONSE XML USING XmlStreamReader  CLASS
       } catch(System.CalloutException e) {
            //Exception handling goes here....
     }       
}
}

Hope this is useful

5 comments:

  1. how do we use this for credit card processing? Authorize.net does not provide SOAP service for credit card processing. Both CIM and ARB. CIM is for creating customers with credit card info (not for running transaction). ARB is for running auto renewals which happen at some specified time (not real time).

    Any example on how to run a payment transaction through authorize.net would be really nice.

    ReplyDelete
  2. Is this passing credit card information in the clear?? I don't see https anywhere.

    ReplyDelete
  3. No, man. It is passing in a encrypted channel since all request from and to SalesForce.com use https.
    See the endpoint: req.setEndpoint('https://api.authorize.net/soap/v1/Service.asmx')

    ddtaxe@gmail.com
    Regards.

    ReplyDelete
  4. Is there any possibility to get Settlement date by Https response?

    ReplyDelete
  5. Very Impressive Salesforce tutorial. The content seems to be pretty exhaustive and excellent and will definitely help in learning Salesforce course. I'm also a learner taken up Salesforce training and I think your content has cleared some concepts of mine. While browsing for Salesforce tutorials on YouTube i found this fantastic video on Salesforce. Do check it out if you are interested to know more.https://www.youtube.com/watch?v=5FTe-ah3WBU

    ReplyDelete