Skip to main content

I am trying make a http callout to the genAndConvertEnvelopes Api to generate a document and save it back to Salesforce and it is failing to due to the below error:

System.StringException: Unrecognized base64 character:

Apex code below can anyone help?

public class docusignGen_And_API {
   
    @InvocableMethod(label='docusignGen_And_API')
    public static List<String> sendEnvelope(List<String> record) {
        System.debug(record);  
        Id recordId = recorde0];
        System.debug(recordId);
        gen_and_convert(recordId);
        return Null;
    }    

    @future(callout = true)  
    public static void gen_and_convert(Id recordId){
       
        
        String jsonBody = bodyJSON(recordId);  
        System.debug(jsonBody); 
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:{namedCredential/restapi/v2.1/accounts/{accountId}/envelopes/generate_and_convert');


        req.setHeader('Content-Type', 'application/json');
        req.setMethod('POST');
        req.setBody(jsonBody); 
        Http http = new Http();
        HTTPResponse res = http.send(req);
        String base64Content = (String) JSON.deserialize( response.getBody(), String.class ); 
                    System.debug(base64Content);
                    Blob blobContent = EncodingUtil.base64Decode(base64Content);

        
        DateTime now = System.now();
        String s = string.valueof(now); 
        
        // Save generated document to Files
        ContentVersion v = new ContentVersion();
        v.VersionData = blobContent;
        v.Title = 'Gen API Doc '+ s;
        v.PathOnClient =v.title;
        insert v;
        v = .SELECT ContentDocumentId FROM ContentVersion WHERE Id =: v.Id];
        ContentDocumentLink objCDL = new ContentDocumentLink(
            ContentDocumentId = v.ContentDocumentId,
            LinkedEntityId = recordId,
            Visibility = 'AllUsers'
        );
        insert objCDL;         
    }  
    
    public static String bodyJSON(Id recordId){
        
        
        ContentVersion file =  SELECT VersionData FROM ContentVersion WHERE IsLatest = TRUE AND ContentDocumentId  = '069Qz000001HRT3IAO' LIMIT 1];
        Blob fileBlob = file.VersionData;           
        String fileBase64 = EncodingUtil.base64Encode(fileBlob);       
        
       // Create the JSON body for the Document Generation API call
        JSONGenerator jsGen = SYSTEM.JSON.createGenerator(true);
        jsGen.writeStartObject();  
        jsGen.writeFieldName('generateProperties');
            jsGen.writeStartArray(); 
                jsGen.writeStartObject(); 
                jsGen.writeStringField('dataJson', opportunityRecord(recordId));  // Record Data
                jsGen.writeBlobField('base64GenerateTemplateDocument', fileBlob);  // Template Document
                jsGen.writeStringField('archiveDocumentType', 'PDF');  
                jsGen.writeEndObject(); 
            jsGen.writeEndArray(); 
        jsGen.writeEndObject();
        String jsonData = jsGen.getAsString();
        return jsonData;
    }      

    
    public static String opportunityRecord(Id recordId){
        // SOQL Opportunity fields you would like to make accessible creating the JSON
        Opportunity oppRec = s
        SELECT Id, Account.Name, Account.Trading_name__c, Account.Registered_Number__c,
Account.BillingStreet, Account.BillingCity, Account.BillingPostalCode, 
        Account.ShippingStreet, Account.ShippingCity, Account.ShippingPostalCode,
Account.Phone, Account.Industry,
        Scheme_Type__c, Funding__c, Payment_Frequency__c, Payment_Method__c,
Start_Date__c, Price_Fix__c, X6_Month_Waiver_Required__c,
Catchment_Waiver_Required__c, 
        Account.Group_Secretary__r.Title, Account.Group_Secretary__r.FirstName,
Account.Group_Secretary__r.LastName, Account.Group_Secretary__r.Salutation,
Account.Group_Secretary__r.Email, Account.Group_Secretary__r.Phone, 
        Account.Finance_Contact__r.Title, Account.Finance_Contact__r.FirstName,
Account.Finance_Contact__r.LastName, Account.Finance_Contact__r.Salutation,
Account.Finance_Contact__r.Email, Account.Finance_Contact__r.Phone,
        Account.Scheme_Admin__r.Title,  Account.Scheme_Admin__r.FirstName,
Account.Scheme_Admin__r.LastName, Account.Scheme_Admin__r.Salutation,
Account.Scheme_Admin__r.Email, Account.Scheme_Admin__r.Phone
        FROM Opportunity 
        WHERE Id = : recordId LIMIT 1]; 
        JSONGenerator jsGen = SYSTEM.JSON.createGenerator(true);
       
        jsGen.writeStartObject();    
            jsGen.writeFieldName('Opportunity');
                jsGen.writeStartObject();
                jsGen.writeStringField('Account Name', oppRec.Account.Name);
                jsGen.writeStringField('Trading name (if different',
oppRec.Account.Trading_name__c);
                jsGen.writeStringField('Registered Number',
oppRec.Account.Registered_Number__c);
                jsGen.writeStringField('Registered Street', oppRec.Account.BillingStreet);
                jsGen.writeStringField('Registered City', oppRec.Account.BillingCity);
                jsGen.writeStringField('Registered Post Code',
oppRec.Account.BillingPostalCode);
                jsGen.writeStringField('Correspondence Street',
oppRec.Account.ShippingCity);
                jsGen.writeStringField('Correspondence Post Code',
oppRec.Account.ShippingPostalCode);
                jsGen.writeStringField('Account Phone', oppRec.Account.Phone);
                jsGen.writeStringField('Industry', oppRec.Account.Industry);
                
                jsGen.writeStringField('Scheme Type', oppRec.Scheme_Type__c);
                jsGen.writeStringField('Funding', oppRec.Funding__c);
                jsGen.writeStringField('Payment Frequency', oppRec.Payment_Frequency__c);
                jsGen.writeStringField('Payment Method', oppRec.Payment_Method__c);
                jsGen.writeDateField('Scheme Start Date', oppRec.Start_Date__c);
        
                
                jsGen.writeStringField('Job Title',
oppRec.Account.Group_Secretary__r.Title);
                jsGen.writeStringField('First Name',
oppRec.Account.Group_Secretary__r.FirstName);
                jsGen.writeStringField('Last Name',
oppRec.Account.Group_Secretary__r.LastName);
                jsGen.writeStringField('Salutation',
oppRec.Account.Group_Secretary__r.Salutation);
                jsGen.writeStringField('Email', oppRec.Account.Group_Secretary__r.Email);
                jsGen.writeStringField('Business Phone',
oppRec.Account.Group_Secretary__r.Phone);
        
                jsGen.writeStringField('Job Title',
oppRec.Account.Finance_Contact__r.Title);
                jsGen.writeStringField('First Name',
oppRec.Account.Finance_Contact__r.FirstName);
                jsGen.writeStringField('Last Name',
oppRec.Account.Finance_Contact__r.LastName);
                jsGen.writeStringField('Salutation',
oppRec.Account.Finance_Contact__r.Salutation);
                jsGen.writeStringField('Email', oppRec.Account.Finance_Contact__r.Email);
                jsGen.writeStringField('Business Phone',
oppRec.Account.Finance_Contact__r.Phone);
        
                
                jsGen.writeStringField('Job Title', oppRec.Account.Scheme_Admin__r.Title);
                jsGen.writeStringField('First Name',
oppRec.Account.Scheme_Admin__r.FirstName);
                jsGen.writeStringField('Last Name',
oppRec.Account.Scheme_Admin__r.LastName);
                jsGen.writeStringField('Salutation',
oppRec.Account.Scheme_Admin__r.Salutation);
                jsGen.writeStringField('Email', oppRec.Account.Scheme_Admin__r.Email);
                jsGen.writeStringField('Business Phone',
oppRec.Account.Scheme_Admin__r.Phone);
        
        
        jsGen.writeEndObject();
        
        String jsonData = jsGen.getAsString();
        System.debug('JSON Data: ' + jsonData);
        return jsonData;
    }                                   
    
}

 

The error System.StringException: Unrecognized base64 character: typically occurs when you’re trying to decode a string that is not properly formatted in Base641. Base64 encoding uses the characters 1. If your string contains characters outside this range, you’ll encounter this error.

In your case, it seems like you’re trying to decode a JSON response directly into a Base64 string. However, the JSON response itself is not Base64 encoded, but it may contain some Base64 data2. You need to properly deserialize the JSON response first to get the data inside of it2.

Here’s how you can do it:

Java

 

String responseBody = response1.getBody();
Map<String, Object> responseMap = (Map<String, Object>) JSON.deserializeUntyped(responseBody);
String base64Content = (String) responseMap.get('your_base64_field');
Blob blobContent = EncodingUtil.base64Decode(base64Content);

AI-generated code. Review and use carefully. More info on FAQ.

In the code above, replace 'your_base64_field' with the actual field name in the JSON response that holds the Base64 content1.

Please note that this is a general solution. You might need to adjust the code according to the actual structure of your JSON response. If you’re still encountering issues, I recommend checking the documentation of the genAndConvertEnvelopes API or contacting their support for more specific guidance.

I hope this helps! Let me know if you have any other questions.


Reply