Convert Lead

Purpose

To convert a lead into a contact or an account.

Request Details

Request URL

{api-domain}/crm/v2/Leads/{record_id}/actions/convert

Header

Authorization: Zoho-oauthtoken 100xx.d92d4xxxxxxxxxxxxx15f52
If-Modified-Since: Use this header to get the list of recently modified records. Example: 2019-07-25T15:26:49+05:30

Scope

scope=ZohoCRM.modules.ALL
(or)
scope=ZohoCRM.modules.leads.{operation_type}

Possible operation types

ALL - Full access to the record
WRITE - Edit records in the module
CREATE - Create records in the module

Sample Request

Copiedcurl "https://zylkercorp.zohoplatform.com/crm/v2/Leads/1000000145990/actions/convert"
-H "Authorization: Zoho-oauthtoken 100xx.8cb99dxxxxxxxxxxxxx9be93.9b8xxxxxxxxxxxxxxxf"
-d "@convertlead.json"
-X POST
1.0.0ES6
Copied//Get instance of RecordOperations Class
let recordOperations = new ZCRM.Record.Operations();
//Get instance of ConvertBodyWrapper Class that will contain the request body
let request = new ZCRM.Record.Model.ConvertBodyWrapper();
//Array to hold LeadConverter instances
let data = [];
//Get instance of LeadConverter Class
let record = new ZCRM.Record.Model.LeadConverter();
record.setOverwrite(true);
record.setNotifyLeadOwner(true);
record.setNotifyNewEntityOwner(true);
record.setAccounts("3409643692007");
record.setContacts("3409643836001");
record.setAssignTo("3409643302031");
let deals = new ZCRM.Record.Model.Record();
/*
 * Call addFieldValue method that takes two arguments
 * Import the "zcrmsdk/core/com/zoho/crm/api/record/field" file
 * 1 -> Call Field "." and choose the module from the displayed list and press "." and choose the field name from the displayed list.
 * 2 -> Value
 */
deals.addFieldValue(ZCRM.Record.Model.Field.Deals.DEAL_NAME, "deal_name");
deals.addFieldValue(ZCRM.Record.Model.Field.Deals.DESCRIPTION, "deals description");
deals.addFieldValue(ZCRM.Record.Model.Field.Deals.CLOSING_DATE, new Date(2021, 2, 13));
deals.addFieldValue(ZCRM.Record.Model.Field.Deals.STAGE, new Choice("Closed Won"));
deals.addFieldValue(ZCRM.Record.Model.Field.Deals.AMOUNT, 50.7);
/*
 * Call addKeyValue method that takes two arguments
 * 1 -> A string that is the Field's API Name
 * 2 -> Value
 */
deals.addKeyValue("Custom_field", "Value");
deals.addKeyValue("Custom_field_2", "value");
let tagArray = [];
let tag = new ZCRM.Tag.Model.Tag();
tag.setName("Converted");
tagArray.push(tag);
deals.setTag(tagArray);
//Set the Deal record to deals in LeadConverter instance
record.setDeals(deals);
//Add the instance to array
data.push(record);
//Set the array to data ConvertBodyWrapper instance
request.setData(data);
//Call convertLead method that takes ConvertBodyWrapper instance and leadId as parameter
let response = await recordOperations.convertLead(leadId, request);
Copiedvar listener = 0;
class ConvertLead {

	async convertLeadRecord()	{
		var url = "https://zylkercorp.zohoplatform.com/crm/v2/Leads/34770618863059/actions/convert"
        var parameters = new Map()
        var headers = new Map()
        var token = {
            clientId:"1000.CXASM1V0XXXXXXXXXXXXXXXXXXXF7H",
            redirectUrl:"http://127.0.0.1:5501/redirect.html",
            scope:"ZohoCRM.users.ALL,ZohoCRM.bulk.read,ZohoCRM.modules.ALL,ZohoCRM.settings.ALL,Aaaserver.profile.Read,ZohoCRM.org.ALL,profile.userphoto.READ,ZohoFiles.files.ALL,ZohoCRM.bulk.ALL,ZohoCRM.settings.variable_groups.ALL"
        }
        var accesstoken = await new ConvertLead().getToken(token)
        headers.set("Authorization", "Zoho-oauthtoken " + accesstoken)
        var requestMethod = "POST"
        var reqBody = {"data":[{"overwrite":true,"notify_new_entity_owner":true,"notify_lead_owner":true,"Note_Content":"asd","$se_module":"Leads","Contacts":"34770619080160","Deals":{"Campaign_Source":"34770617229030","Deal_Name":"Robert","Closing_Date":"2016-03-30","Stage":"Closed Won","Amount":65.6},"Accounts":"34770619080156","assign_to": "3477061173021"}]}
        var params = "";
        parameters.forEach(function(value, key) {
            if (parameters.has(key)) {
                if (params) {
                    params = params + key + '=' + value + '&';
                }
                else {
                    params = key + '=' + value + '&';
                }
            }
        });
        var apiHeaders = {};
        if(headers) {
            headers.forEach(function(value, key) {
                apiHeaders[key] = value;
            });
        }
        if (params.length > 0){
            url = url + '?' + params.substring(0, params.length - 1);
        }
        var requestObj = {
            uri : url,
            method : requestMethod,
            headers : apiHeaders,
            body : JSON.stringify(reqBody),
            encoding: "utf8",
            allowGetBody : true,
			throwHttpErrors : false
        };
        var result = await new ConvertLead().makeAPICall(requestObj);
        console.log(result.status)
        console.log(result.response)
	}

    async getToken(token) {

        if(listener == 0) {

            window.addEventListener("storage", function(reponse) {
                if(reponse.key === "access_token" && (reponse.oldValue != reponse.newValue || reponse.oldValue == null)){
                    location.reload();
                }
                if(reponse.key === "access_token"){

                    sessionStorage.removeItem("__auth_process");
                }
            }, false);
            listener = 1;
            if(sessionStorage.getItem("__auth_process")) {
                sessionStorage.removeItem("__auth_process");
            }
        }
        ["granted_for_session", "access_token","expires_in","expires_in_sec","location","api_domain","state","__token_init","__auth_process"].forEach(function (k) {
            var isKeyExists = localStorage.hasOwnProperty(k);
            if(isKeyExists) {
                sessionStorage.setItem(k, localStorage[k]);
            }
            localStorage.removeItem(k);
        });
        var valueInStore = sessionStorage.getItem("access_token");
        var tokenInit = sessionStorage.getItem("__token_init");
        if(tokenInit != null && valueInStore != null && Date.now() >= parseInt(tokenInit) + 59 * 60 * 1000){ // check after 59th minute
            valueInStore = null;
            sessionStorage.removeItem("access_token");
        }

        var auth_process = sessionStorage.getItem("__auth_process");
        if ((valueInStore == null && auth_process == null) || (valueInStore == 'undefined' && (auth_process == null || auth_process == "true"))) {
            var accountsUrl = "https://zylkercorp.zohoplatform.com/oauth/v2/auth"
            var clientId;
            var scope;
            var redirectUrl;
            if(token != null) {
                clientId = token.clientId;
                scope = token.scope;
                redirectUrl = token.redirectUrl;
            }

            var fullGrant = sessionStorage.getItem("full_grant");
            var grantedForSession = sessionStorage.getItem("granted_for_session");
            if(sessionStorage.getItem("__token_init") != null && ((fullGrant != null && "true" == full_grant) || (grantedForSession != null && "true" == grantedForSession))) {
                accountsUrl += '/refresh';
            }
            if (clientId && scope) {
                sessionStorage.setItem("__token_init", Date.now());
                sessionStorage.removeItem("access_token");
                sessionStorage.setItem("__auth_process", "true");
                window.open(accountsUrl + "?" + "scope" + "=" + scope + "&"+ "client_id" +"=" + clientId + "&response_type=token&state=zohocrmclient&redirect_uri=" + redirectUrl);
                ["granted_for_session", "access_token","expires_in","expires_in_sec","location","api_domain","state","__token_init","__auth_process"].forEach(function (k) {
                    var isKeyExists = localStorage.hasOwnProperty(k);
                    if(isKeyExists){
                        sessionStorage.setItem(k, localStorage[k]);
                    }
                    localStorage.removeItem(k);
                });
                valueInStore = sessionStorage.getItem("access_token");
            }
        }
        if(token != null && valueInStore != 'undefined'){
            token.accessToken = valueInStore;
        }
        return token.accessToken;
    }

    async makeAPICall(requestDetails) {
        return new Promise(function (resolve, reject) {
            var body, xhr, i;
            body = requestDetails.body || null;
            xhr = new XMLHttpRequest();
            xhr.withCredentials = true;
            xhr.open(requestDetails.method, requestDetails.uri, true);
            for (i in requestDetails.headers) {
                xhr.setRequestHeader(i, requestDetails.headers[i]);
            }
            xhr.send(body);
            xhr.onreadystatechange = function() {
                if(xhr.readyState == 4) {
                    resolve(xhr);
                }
            }
        })
    }
}
CopiedSyntax:
zoho.crm.convertLead(<leadId Long>,<dataMap Map>,<connectionName String>,<userAccess Boolean>);
mandatory : leadId,dataMap

Sample Request:
resp = zoho.crm.convertLead("7000000037308", { "overwrite": true, "notify_lead_owner": false, "notify_new_entity_owner": true, "Accounts": "7000000037323", "Deals": { "Deal_Name": "Robert", "Closing_Date": "2016-03-30", "Stage": "Closed Won", "Amount": 56.6 } });

In the request, "@convertlead.json" contains the sample input.

Input JSON Keys

To convert leads, send a POST request with request body containing the following attributes:

  • overwriteboolean, optional

    Specify if the Lead details must be overwritten in the Contact/Account/Deal based on lead conversion mapping configuration.
    true: Overwrite the lead details in Contact/Account/Deal. Note that when this value is true and you have specified an account ID, only the account name will be overwritten with the company name of that contact. Rest of the details are unchanged.
    false: Do not overwrite the lead details to Contact/Account/Deal.

  • notify_lead_ownerboolean, optional

    Specify whether the lead owner must get notified about the lead conversion via email.
    true: The lead owner gets notified about the conversion via email.
    false: The lead owner does not get notified about the conversion via email. The default value is false.

  • notify_new_entity_ownerboolean, optional

    Specify whether the user to whom the contact/account is assigned to must get notified about the lead conversion via email.
    true: The user gets notified about the conversion via email.
    false: The user does not get notified about the conversion via email. The default value is false.

  • Accountsstring, optional

    Use this key to associate an account with the lead being converted. Pass the unique and valid account ID.
    Example: "Accounts": "4000000373187"

  • Contactsstring, optional

    Use this key to associate a contact with the lead being converted. Pass the unique and valid contact ID.
    Example: "Contacts": "4000000372131"

  • assign_tostring, optional

    Use this key to assign record owner for the new contact and account. Pass the unique and valid user ID.
    Example: "assign_to": "4000000219019"

  • DealsJSON object, optional

    Use this key to create a deal for the newly created Account. The "Deal_Name", "Closing_Date", and "Stage" are default mandatory keys to be passed in the JSON object.

  • carry_over_tagsJSON object, optional

    Use this key to carry over tags of the lead to contact, account, and deal. Refer to sample input for format.

Note
  • In the input, the assign_to value can only be the User ID.

  • You can associate the existing contact or account to the converting lead even if the lead is converted or not converted to a deal. To achieve this, you have to send the account ID and contact ID in your input data.

  • If both account ID and overwrite values are true, then the account name will be replaced by the company name, while associating it with the existing account. However, the data of that account will remain the same.

  • If overwrite value is set to false, then association will only happen. However, if you set the overwrite value without account ID, the working of this method remains unchanged.

  • If contact ID is given in your input, then the converting lead will be associated to the existing contact.

  • You must use only Field API names in the input. You can obtain the field API names from

    • Fields metadata API (the value for the key “api_name” for every field). (Or)

    • Setup > Developer Space > APIs > API Names > {{Module}}. Choose “Fields” from the “Filter By” drop-down.

Sample Input

Copied{
    "data": [
        {
            "overwrite": true,
            "notify_lead_owner": true,
            "notify_new_entity_owner": true,
            "Accounts": "4150868000003283003",
            "Contacts": "4150868000003283024",
            "assign_to": "4150868000001248015",
            "Deals": {
                "Deal_Name": "Robert",
                "Closing_Date": "2020-07-24",
                "Stage": "Closed Won",
                "Amount": 56.6
            },
            "carry_over_tags": {
                "Contacts": [
                    "tag1",
                    "tag2"
                ],
                "Accounts": [
                    "tag1"
                ],
                "Deals": [
                    "tag1"
                ]
            }
        }
    ]
}

Possible Errors

  • DUPLICATE_DATAHTTP 202

    Duplicate data
    Resolution: There already exists a contact with the unique field details present in lead. Ensure you specify unique values for unique fields (both system and user-defined). To know which fields are unique, refer to Fields Metadata API.

  • ID_ALREADY_CONVERTEDHTTP 202

    id already converted
    Resolution: The lead you are trying to convert has already been converted. Specify a valid lead ID. Refer to Get Records API to get valid lead IDs.

  • INVALID_URL_PATTERNHTTP 404

    Please check if the URL trying to access is a correct one
    Resolution: The request URL specified is incorrect. Specify a valid request URL. Refer to request URL section above.

  • OAUTH_SCOPE_MISMATCHHTTP 401

    Unauthorized
    Resolution: Client does not have ZohoCRM.modules.{module_name}.CREATE. Create a new client with valid scope. Refer to scope section above.

  • NO_PERMISSIONHTTP 403

    Permission denied to create
    Resolution: The user does not have permission to create records. Contact your system administrator.

  • INTERNAL_ERRORHTTP 500

    Internal Server Error
    Resolution: Unexpected and unhandled exception in the server. Contact support team.

  • INVALID_REQUEST_METHODHTTP 400

    The http request method type is not a valid one
    Resolution: You have specified an invalid HTTP method to access the API URL. Specify a valid request method. Refer to endpoints section above.

  • AUTHORIZATION_FAILEDHTTP 400

    User does not have sufficient privilege to create records
    Resolution: The user does not have the permission to create records. Contact your system administrator.

  • INVALID_DATAHTTP 202

    invalid data
    Resolution: The input specified is incorrect. Specify valid input.

Sample Respnse

Copied{
    "data": [
       {
            "Contacts": "4000000372131",
            "Deals": "4000000377192",
            "Accounts": "4000000373187"
        }
    ]
}