[SalesForce] Live Agent Post Chat Page getting the Id of the Case inserted by the Pre Chat Page

I'm creating a Pre Chat and Post Chat page for Live Agent. The Pre Chat page inserts a Case. I need the Post Chat page to access that Case or get its Id. How do I do that?

Thanks in advance.

Best Answer

In post chat page the Case Id is available through a page parameter named as attachedRecords. It is a JSON string and for me it is coming as {"ContactId":"003i000002nB9wFAAS","Case":"500i000000hkMtSAAU"}. You have to parse this JSON to get the Case ID.

I have created JSON2Apex class using https://json2apex.herokuapp.com/ to parse the JSON.

Here is my VF page and controller class code as below.

VF Page

<apex:page controller="PostChatController" showHeader="false" >
    CaseID : {!caseId}
</apex:page>

Controller

public class PostChatController {
    public String caseId {get;set;}
    public String attachedRecords {get;set;}
    public PostChatController() {
        attachedRecords = ApexPages.currentPage().getParameters().get('attachedRecords');
        caseId = JSON2Apex.parse(attachedRecords).Case_Z;
    }    
}

JSON2Apex Class

//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//
// The supplied json has fields with names that are reserved words in apex
// and so can only be parsed with explicitly generated code, this option
// was auto selected for you.

public class JSON2Apex {
    public static void consumeObject(JSONParser parser) {
        Integer depth = 0;
        do {
            JSONToken curr = parser.getCurrentToken();
            if (curr == JSONToken.START_OBJECT || 
                curr == JSONToken.START_ARRAY) {
                depth++;
            } else if (curr == JSONToken.END_OBJECT ||
                curr == JSONToken.END_ARRAY) {
                depth--;
            }
        } while (depth > 0 && parser.nextToken() != null);
    }

    public String ContactId {get;set;} 
    public String Case_Z {get;set;} // in json: Case

    public JSON2Apex(JSONParser parser) {
        while (parser.nextToken() != JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != JSONToken.VALUE_NULL) {
                    if (text == 'ContactId') {
                        ContactId = parser.getText();
                    } else if (text == 'Case') {
                        Case_Z = parser.getText();
                    } else {
                        System.debug(LoggingLevel.WARN, 'Root consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }


    public static JSON2Apex parse(String json) {
        return new JSON2Apex(System.JSON.createParser(json));
    }
}