Created
September 7, 2016 14:18
-
-
Save drobakowski/6f2bf5419675e348754ad12d69190df8 to your computer and use it in GitHub Desktop.
Apex class for converting a Lead into an Account/Contact/Opportunity through the REST-API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@RestResource(urlMapping='/Lead/*') | |
global with sharing class RestLeadConvert { | |
@HttpPost | |
global static void convertLead() { | |
RestRequest req = RestContext.request; | |
RestResponse res = RestContext.response; | |
res.addHeader('Content-Type', 'application/json'); | |
String leadId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1); | |
Database.LeadConvert lc = new Database.LeadConvert(); | |
lc.setLeadId(leadId); | |
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1]; | |
lc.setConvertedStatus(convertStatus.MasterLabel); | |
Database.LeadConvertResult lcr; | |
try { | |
lcr = Database.convertLead(lc); | |
if (lcr.isSuccess()) { | |
system.debug(LoggingLevel.INFO, 'Successfully converted LeadId: ' + leadId + ' to an Account with AccountId: ' + lcr.getAccountId()); | |
res.responseBody = Blob.valueOf('{"account_id":"'+lcr.getAccountId()+'","contact_id":"'+lcr.getContactId()+'","opportunity_id":"'+lcr.getOpportunityId()+'"}'); | |
res.statusCode = 200; | |
} else { | |
system.debug(LoggingLevel.WARN, 'LeadId: ' + leadId + ' could not be converted'); | |
res.statusCode = 400; | |
} | |
} catch(exception ex) { | |
system.debug(LoggingLevel.ERROR, 'Error while trying to convert LeadId: ' + leadId +'; Reason: "' + ex.getMessage() + '"'); | |
res.responseBody = Blob.valueOf('{"error_message":"'+ex.getMessage()+'"}'); | |
res.statusCode = 400; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment