I have a requirement with the following functionality:
- Before the Opp stage gets updated to Closed-Won on ever opp I should be able to push the opp info to an external REST webservice URL as JSON format.
- After successfully pushed I will get a JSON response with an account Id and status message with this I need to update the Opportunity.
I was not able to look my trigger in the debug lo is something in my trigger?I'm not able to make call to the URL? How to handle the request and response and map it to the opp?
Here is the Trigger:
trigger OppUpdate on Opportunity (before insert,before update) {
for (Opportunity Opp : Trigger.new) {
if (Opp.StageName=='ClosedWon') {
opptycall.post(JSON.serializePretty(Trigger.new));
system.debug(JSON.serializePretty(Trigger.new));
system.debug(JSON.serialize(trigger.new));
}
}
}
Here is my class:
public class opptycall {@future(callout = true)
public static void post(id opptyid) {
//Construct HTTP request and response
HttpRequest req = new HttpRequest();
//Http http = new Http();
//Construct Authorization and Content header
//request.setHeader('Authorization', getBasicAuthHeader('test','test'));
//req.setHeader('Authorization', authorizationHeader);
req.setHeader('Content-Type', 'application/json');
//Construct Endpoint
String endpoint = 'https://test.com';
//Set Method and Endpoint and Body
req.setMethod('POST');
req.setEndpoint(endpoint);
//json string in body
system.debug('Opportunity ID' + opptyid);
Opportunity Op = [select id, Name, Stagename, Account.Name from opportunity where stagename = 'Closed-Won'
and id = : opptyid];
System.debug('with pretty' + JSON.serializePretty(Op));
system.debug('without pretty' + JSON.serialize(Op));
String JsonString = JSON.serializePretty(Op);
req.setBody(JsonString);
system.debug(JsonString);
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());
if (response.getStatusCode() == 200) {
JSONParser par = JSONParser.parse(response.getBody());
System.debug('-par.message.Opportunity-' + par.message.Opportunity);
for (JSONParser.Opportuntiy Opp: par.message.Opportuntiy) {
Opp.add(new Opportunity(
Id = par.message.Opportuntiy.Id,
Status = par.message.Opportuntiy.status,
Description = par.message.Opportuntiy.description));
update opp Id;
}
}
}
}
string
you are using forStageName
. You've got bothClosedWon
andClosed-Won
in your code. Since this field is a picklist and can be changed by the user and more importantly multiple opportunity stage values can represent a closed opportunity, you might consider querying theOpportunityStage
object for the StageName and check the values ofisClosed
andisWon
and drive your logic from that data.opptycall.post
when it is expecting an ID.