Skip to main content
A Trailblazer Community no Slack está agora em beta aberto. Participe e interaja em tempo real. Junte-se a nós no Slack

Create Apex Classes

Learning Objectives

After completing this unit, you’ll be able to:

  • Explain the role of Apex classes in this solution.
  • Create Apex classes that call the Document AI API and parses the JSON result.

What the Apex Classes Do

You now create three Apex classes, each with their own role. The flow can’t call Document AI directly and has limited JSON processing capabilities, so you use Apex to bridge the gap.

  • DocumentAICaller: Authenticates with OAuth, then calls Document AI with the file and returns the raw JSON.
  • PODetailsExtractor: Parses the JSON into typed variables (Date, Decimal, String) that the flow can drop straight onto the Opportunity.
  • DocumentAICallerTest: Tests the two classes above so you can confirm their performance before calling them in the flow. You won’t actually call this class in the flow.

We don’t cover Apex programming skills in this badge. Learn more in Apex Basics & Database.

Create Apex Classes

First, create the DocumentAICaller class.

  1. Click the gear icon and launch Setup.
  2. In the Quick Find box, search for and select Apex Classes.
  3. Click New.
  4. Copy and paste the following text.
public with sharing class DocumentAICaller {
     @InvocableMethod(label='Run Document AI Image/File Recognition with Schema Configuration')
     public static List<Result> runImageProcessing(List<Request> requests) {
         List<Result> results = new List<Result>();
         for (Request req : requests) {
             Result result = new Result();
             try {
                 String token = getAccessToken(req.Org_Domain, req.Client_Id, req.Client_Secret);
                 String orgDomain   = req.Org_Domain;
                 String llmModel    = req.LLM_Model;
                 String idpConfigId = req.IDPConfigId;
                 ContentVersion cv = [
                     SELECT Id
                     FROM ContentVersion
                     WHERE ContentDocumentId = :req.ContentDocumentId
                     ORDER BY VersionNumber DESC
                     LIMIT 1
                 ];
                 String fileId = cv.Id;
                 String finalResponse;
                 if (String.isBlank(idpConfigId)) {
                     String schemaJson = getSchemaJson(token, fileId, orgDomain, llmModel);
                     finalResponse = extractData(token, fileId, schemaJson, orgDomain, llmModel, null);
                 } else {
                     finalResponse = extractData(token, fileId, null, orgDomain, llmModel, idpConfigId);
                 }
                 result.Status = 'Success';
                 result.ExtractedDataJson = finalResponse;
             } catch (Exception e) {
                 result.Status = 'Failed';
                 result.ErrorMessage = e.getMessage();
             }
             results.add(result);
         }
         return results;
     }
     public class Request {
         @InvocableVariable(label='Org Domain' required=true)    public String Org_Domain;
         @InvocableVariable(label='Client Id' required=true)     public String Client_Id;
         @InvocableVariable(label='Client Secret' required=true) public String Client_Secret;
         @InvocableVariable(label='LLM Model')                   public String LLM_Model;
         @InvocableVariable(label='Content Document Id' required=true) public Id ContentDocumentId;
         @InvocableVariable(label='IDPConfigId')                 public String IDPConfigId;
     }
     public class Result {
         @InvocableVariable(label='Status')                     public String Status;
         @InvocableVariable(label='Extracted Data (JSON)')      public String ExtractedDataJson;
         @InvocableVariable(label='Error Message (if any)')     public String ErrorMessage;
     }
     @TestVisible
     private static String getAccessToken(String orgDomain, String clientId, String clientSecret) {
         HttpRequest req = new HttpRequest();
         req.setEndpoint(orgDomain + '/services/oauth2/token');
         req.setMethod('POST');
         req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
         req.setBody('grant_type=client_credentials&client_id=' + clientId
                     + '&client_secret=' + clientSecret);
         HttpResponse res = new Http().send(req);
         if (res.getStatusCode() == 200) {
             Map<String,Object> resp = (Map<String,Object>) JSON.deserializeUntyped(res.getBody());
             return (String) resp.get('access_token');
         }
         throw new CalloutException('Access Token Error: ' + res.getBody());
     }
     @TestVisible
     private static String getSchemaJson(String accessToken, String fileId,
                                         String orgDomain, String llmModel) {
         HttpRequest req = new HttpRequest();
         req.setEndpoint(orgDomain
             + '/services/data/v66.0/ssot/document-processing/actions/generate-schema?htmlEncode=false');
         req.setMethod('POST');
         req.setHeader('Authorization', 'Bearer ' + accessToken);
         req.setHeader('Content-Type', 'application/json');
         req.setTimeout(120000);
         if (String.isBlank(llmModel)) llmModel = 'llmgateway__VertexAIGemini20Flash001';
         Map<String,Object> payload = new Map<String,Object>{
             'mlModel' => llmModel,
             'files'   => new List<Object>{ new Map<String,Object>{ 'fileId' => fileId } }
         };
         req.setBody(JSON.serialize(payload));
         HttpResponse res = new Http().send(req);
         if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
             Map<String,Object> bodyMap = (Map<String,Object>) JSON.deserializeUntyped(res.getBody());
             return (String) bodyMap.get('schema');
         }
         throw new CalloutException('Schema Error: ' + res.getBody());
     }
     @TestVisible
     private static String extractData(String accessToken, String fileId, String schemaJson,
                                       String orgDomain, String llmModel, String idpConfigId) {
         HttpRequest req = new HttpRequest();
         req.setEndpoint(orgDomain
             + '/services/data/v66.0/ssot/document-processing/actions/extract-data?htmlEncode=false');
         req.setMethod('POST');
         req.setHeader('Authorization', 'Bearer ' + accessToken);
         req.setHeader('Content-Type', 'application/json');
         req.setTimeout(120000);
         Map<String,Object> payload = new Map<String,Object>{
             'files' => new List<Object>{ new Map<String,Object>{ 'fileId' => fileId } }
         };
         if (!String.isBlank(schemaJson)) {
             payload.put('mlModel', llmModel);
             payload.put('schemaConfig', schemaJson);
         } else {
             payload.put('idpConfigurationIdOrName', idpConfigId);
         }
         req.setBody(JSON.serialize(payload));
         HttpResponse res = new Http().send(req);
         if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
             Map<String,Object> bodyMap = (Map<String,Object>) JSON.deserializeUntyped(res.getBody());
             return JSON.serialize(bodyMap.get('data'));
         }
         throw new CalloutException('Extract Error: ' + res.getBody());
     }
 }
  1. Click Save. Confirm the class name is DocumentAICaller.

Next, create the PODetailsExtractor class.

  1. Click Apex Classes. Click New.
  2. Copy and paste the following.
public with sharing class PODetailsExtractor {
     public class PODetails {
         @InvocableVariable(label='PO Number')         public String  po_number;
         @InvocableVariable(label='Close Date')        public Date    close_date;
         @InvocableVariable(label='Total Amount')      public Decimal total_amount;
         @InvocableVariable(label='Payment Terms')     public String  payment_terms;
         @InvocableVariable(label='Line Item Summary') public String  line_item_summary;
     }
     public class POInput {
         @InvocableVariable(label='Extracted Data JSON' required=true)
         public String extractedDataJson;
     }
     @InvocableMethod(label='Extract PO Details from Document AI JSON')
     public static List<PODetails> extractDetails(List<POInput> requests) {
         List<PODetails> results = new List<PODetails>();
         for (POInput req : requests) {
             PODetails output = new PODetails();
             try {
                 String rawJson = req.extractedDataJson == null ? '' : req.extractedDataJson;
                 rawJson = decodeHtml(rawJson);
                 List<Object> dataList = (List<Object>) JSON.deserializeUntyped(rawJson);
                 if (dataList == null || dataList.isEmpty()) {
                     results.add(output);
                     continue;
                 }
                 Map<String, Object> docData = (Map<String, Object>) dataList[0];
                 Map<String, Object> fieldsMap = null;
                 // New format: docData.data is a stringified JSON object keyed by field name
                 Object dataObj = docData.get('data');
                 if (dataObj instanceof String) {
                     fieldsMap = (Map<String, Object>) JSON.deserializeUntyped(
                         decodeHtml((String) dataObj));
                 } else if (dataObj != null) {
                     try {
                         fieldsMap = (Map<String, Object>) dataObj;
                     } catch (Exception castEx) {
                         fieldsMap = null;
                     }
                 }
                 if (fieldsMap != null) {
                     for (String rawKey : fieldsMap.keySet()) {
                         String key = rawKey.toLowerCase().trim()
                                           .replace(' ', '_').replace('-', '_');
                         Object valueObj = fieldsMap.get(rawKey);
                         String value = '';
                         if (valueObj instanceof Map<String, Object>) {
                             Object v = ((Map<String, Object>) valueObj).get('value');
                             if (v != null) value = String.valueOf(v).trim();
                         } else if (valueObj != null) {
                             value = String.valueOf(valueObj).trim();
                         }
                         if (String.isBlank(value)) continue;
                         assignField(output, key, value);
                     }
                 } else {
                     // Legacy format: docData.fields is a list of {label, value}
                     List<Object> fields = (List<Object>) docData.get('fields');
                     if (fields != null) {
                         for (Object fieldObj : fields) {
                             Map<String, Object> field = (Map<String, Object>) fieldObj;
                             String label = (String) field.get('label');
                             if (label == null) continue;
                             String key = label.toLowerCase().trim().replace(' ', '_');
                             String value = field.get('value') != null
                                 ? String.valueOf(field.get('value')).trim() : '';
                             if (String.isBlank(value)) continue;
                             assignField(output, key, value);
                         }
                     }
                 }
             } catch (Exception e) {
                 System.debug('Error extracting PO details: ' + e.getMessage());
             }
             results.add(output);
         }
         return results;
     }
     private static void assignField(PODetails output, String key, String value) {
         if ('po_number'.equalsIgnoreCase(key) || 'ponumber'.equalsIgnoreCase(key)) {
             output.po_number = value;
         } else if ('order_date'.equalsIgnoreCase(key) || 'orderdate'.equalsIgnoreCase(key)
                 || 'po_date'.equalsIgnoreCase(key) || 'issue_date'.equalsIgnoreCase(key)) {
             try { output.close_date = Date.valueOf(value); }
             catch (Exception de) { System.debug('Could not parse date value: ' + value); }
         } else if ('total_amount'.equalsIgnoreCase(key) || 'totalamount'.equalsIgnoreCase(key)
                 || 'amount'.equalsIgnoreCase(key)) {
             try { output.total_amount = Decimal.valueOf(value.replaceAll('[^0-9.]', '')); }
             catch (Exception ne) { System.debug('Could not parse amount value: ' + value); }
         } else if ('payment_terms'.equalsIgnoreCase(key) || 'paymentterms'.equalsIgnoreCase(key)) {
             output.payment_terms = value;
         } else if ('line_item_summary'.equalsIgnoreCase(key)
                 || 'lineitemsummary'.equalsIgnoreCase(key)
                 || 'line_items_summary'.equalsIgnoreCase(key)) {
             output.line_item_summary = value;
         }
     }
     private static String decodeHtml(String s) {
         if (s == null) return '';
         return s.replace('&quot;', '"').replace('&amp;', '&').replace('&apos;', '\'')
                 .replace('&lt;', '<').replace('&gt;', '>');
     }
 }
  1. Click Save. Confirm the name is PODetailsExtractor.

Next, create the DocumentAICallerTest class.

  1. Click Apex Classes. Click New.
  2. Copy and paste the following.
@IsTest
private class DocumentAICallerTest {
    public class FlowMock implements HttpCalloutMock {
        public HttpResponse respond(HttpRequest req) {
            HttpResponse res = new HttpResponse();
            res.setHeader('Content-Type', 'application/json');
            if (req.getEndpoint().contains('/services/oauth2/token')) {
                res.setStatusCode(200);
                res.setBody('{"access_token":"fake-token","instance_url":"https://example"}');
                return res;
            }
            if (req.getEndpoint().contains('document-processing/actions/extract-data')) {
                res.setStatusCode(200);
                res.setBody(
                    '{"data":[{"data":"{\\"po_number\\":{\\"value\\":\\"PO-12345\\"},'
                    + '\\"order_date\\":{\\"value\\":\\"2026-04-15\\"},'
                    + '\\"total_amount\\":{\\"value\\":\\"125000.00\\"},'
                    + '\\"payment_terms\\":{\\"value\\":\\"Net 60\\"},'
                    + '\\"line_item_summary\\":{\\"value\\":\\"5 laptops + accessories\\"}}"}]}'
                );
                return res;
            }
            res.setStatusCode(404);
            res.setBody('{"error":"unmocked endpoint"}');
            return res;
        }
    }
    public class FailMock implements HttpCalloutMock {
        public HttpResponse respond(HttpRequest req) {
            HttpResponse res = new HttpResponse();
            res.setStatusCode(401);
            res.setBody('{"error":"invalid_client"}');
            return res;
        }
    }
    private static Id createPdfFile() {
        ContentVersion cv = new ContentVersion(
            Title          = 'Test PO',
            PathOnClient   = 'test-po.pdf',
            VersionData    = Blob.valueOf('%PDF-1.4 fake test bytes'),
            IsMajorVersion = true
        );
        insert cv;
        return [SELECT ContentDocumentId FROM ContentVersion WHERE Id = :cv.Id].ContentDocumentId;
    }
    @IsTest
    static void runImageProcessing_success() {
        Id contentDocId = createPdfFile();
        Test.setMock(HttpCalloutMock.class, new FlowMock());
        DocumentAICaller.Request r = new DocumentAICaller.Request();
        r.Org_Domain        = 'https://example.my.salesforce.com';
        r.Client_Id         = 'CK';
        r.Client_Secret     = 'CS';
        r.ContentDocumentId = contentDocId;
        r.IDPConfigId       = 'po_config';
        Test.startTest();
        List<DocumentAICaller.Result> results =
            DocumentAICaller.runImageProcessing(
                new List<DocumentAICaller.Request>{ r });
        Test.stopTest();
        System.assertEquals(1, results.size());
        System.assertEquals('Success', results[0].Status);
        System.assertNotEquals(null, results[0].ExtractedDataJson);
    }
    @IsTest
    static void runImageProcessing_authFails() {
        Id contentDocId = createPdfFile();
        Test.setMock(HttpCalloutMock.class, new FailMock());
        DocumentAICaller.Request r = new DocumentAICaller.Request();
        r.Org_Domain        = 'https://example.my.salesforce.com';
        r.Client_Id         = 'CK';
        r.Client_Secret     = 'CS';
        r.ContentDocumentId = contentDocId;
        r.IDPConfigId       = 'po_config';
        Test.startTest();
        List<DocumentAICaller.Result> results =
            DocumentAICaller.runImageProcessing(
                new List<DocumentAICaller.Request>{ r });
        Test.stopTest();
        System.assertEquals('Failed', results[0].Status);
        System.assertNotEquals(null, results[0].ErrorMessage);
    }
    @IsTest
    static void extractDetails_parsesAllFields() {
        PODetailsExtractor.POInput inp = new PODetailsExtractor.POInput();
        inp.extractedDataJson =
            '[{"data":"{\\"po_number\\":{\\"value\\":\\"PO-9999\\"},'
            + '\\"order_date\\":{\\"value\\":\\"2026-05-01\\"},'
            + '\\"total_amount\\":{\\"value\\":\\"42000.50\\"},'
            + '\\"payment_terms\\":{\\"value\\":\\"Net 30\\"},'
            + '\\"line_item_summary\\":{\\"value\\":\\"Demo line\\"}}"}]';
        Test.startTest();
        List<PODetailsExtractor.PODetails> details =
            PODetailsExtractor.extractDetails(
                new List<PODetailsExtractor.POInput>{ inp });
        Test.stopTest();
        System.assertEquals('PO-9999', details[0].po_number);
        System.assertEquals(Date.newInstance(2026, 5, 1), details[0].close_date);
        System.assertEquals(42000.50, details[0].total_amount);
        System.assertEquals('Net 30', details[0].payment_terms);
        System.assertEquals('Demo line', details[0].line_item_summary);
    }
    @IsTest
    static void extractDetails_emptyJson_returnsEmpty() {
        PODetailsExtractor.POInput inp = new PODetailsExtractor.POInput();
        inp.extractedDataJson = '[]';
        List<PODetailsExtractor.PODetails> details =
            PODetailsExtractor.extractDetails(
                new List<PODetailsExtractor.POInput>{ inp });
        System.assertEquals(1, details.size());
        System.assertEquals(null, details[0].po_number);
    }
}
  1. Click Save. Confirm the name is DocumentAICallerTest.

Finally, test the classes.

  1. From Setup, in the Quick Find box, search for and select Application Test Execution.
  2. Click Select Tests.
  3. Check DocumentAICallerTest, then click Run.
  4. Wait a few seconds, then click View Test History. Confirm that all four tests passed.

Now you have a Document AI schema configuration that extracts PO details, an Apex class that calls Document AI, and an Apex class that parses the JSON. In the next unit, you tie it all together with a flow.

Resources

Compartilhe seu feedback do Trailhead usando a Ajuda do Salesforce.

Queremos saber sobre sua experiência com o Trailhead. Agora você pode acessar o novo formulário de feedback, a qualquer momento, no site Ajuda do Salesforce.

Saiba mais Continue compartilhando feedback