[SalesForce] HTTP Callout with form-data not working

I am making a callout to a payment gateway, and initially I tested the API using Postman app.

enter image description here

And the response is given

enter image description here

Now, that I transform all that to Salesforce Apex, I am getting following error:

RESPONSE:
{"method":"unknown","trace":"4001/10644/5bb4e0c6","error":{"message":"E01:Invalid
request","note":"Unknown method"}}


Http h = new Http(); 
String url = 'https://secure.telr.com/gateway/order.json';

HttpRequest req = new HttpRequest();
System.debug('Complete URL: ' + url);
req.setEndpoint(url );
req.setHeader('Content-Type','application/json');
req.setMethod('POST');
  req.setBody('{"ivp_store":"21025","ivp_authkey":"<it\'s a secret to everyone>","ivp_currency":"AED","ivp_amount":"2","ivp_test":"1","ivp_cart":"ORD113","return_auth":"https://www.google.com","return_decl":"https://www.google.com","return_can":"https://www.google.com","ivp_desc":"TEST description","ivp_method":"create"}');
HttpResponse res = h.send(req);

System.debug('RESPONSE: ' + res.getBody());

Best Answer

It appears your payment gateway wants a form post. You would need to change the following line:

req.setHeader('Content-Type','application/x-www-form-urlencoded');

And change your parameter building section as follows:

// Following URL can be anything; we only care about the query string
PageReference ref = new PageReference('https://contoso.com/');
// Populate parameters
Map<String, String> params = new Map<String, String>();
params.put('ivp_method','create');
params.put('ivp_desc','Test description - order');
// ... add remaining parameters here ...
ref.getParameters().putAll(params);
Url finalUrl = new Url(ref.getUrl());
// fully url-encoded query string - set the body of http request object
req.setBody(finalUrl.getQuery()));

This is the most literal translation of the Postman post in your screenshot.

Related Topic