Get Zendesk tickets in Salesforce using Lightning Web Component

Posted on December 30, 2021 Post Thumbnail

Welcome Back, Trailblazers {-_-}

In this blog post, We are going to create a Lightning Web Component, With the help of this component, We can login Zendesk details and Access Zendesk tickets, after selecting some tickets, We can save in Salesforce.

For Demo, Please have a look at this video.

https://youtu.be/j5s_rq-3TCk

Adding some screenshots.

LoginAccess Tickets

Let's Start, 

Before start, In my previous blog post. We were able to fetch tickets daily bases.

Please have a look at this blog post.

https://heysalesforce.org/posts/integrate-zendesk-with-salesforce

Setup your account and enable Apis.

1. First of all create an account on Zendesk.

https://www.zendesk.com/register/?ref=341#step-1

2. After creating an account.

Enable following settings.

Enable Api & Password Access.

apiApi

Now we are able to make callout.

But for making callout, We need to look into Zendesk Developer Guide.

https://developer.zendesk.com/api-reference/ticketing/introduction/

Endpont Url: https://{subdomain}.zendesk.com/api/v2/tickets.json

Sample response.

{
  "assignee_id": 235323,
  "collaborator_ids": [
    35334,
    234
  ],
  "created_at": "2009-07-20T22:55:29Z",
  "custom_fields": [
    {
      "id": 27642,
      "value": "745"
    },
    {
      "id": 27648,
      "value": "yes"
    }
  ],
  "description": "The fire is very colorful.",
  "due_at": null,
  "external_id": "ahg35h3jh",
  "follower_ids": [
    35334,
    234
  ],
  "group_id": 98738,
  "has_incidents": false,
  "id": 35436,
  "organization_id": 509974,
  "priority": "high",
  "problem_id": 9873764,
  "raw_subject": "{{dc.printer_on_fire}}",
  "recipient": "[email protected]",
  "requester_id": 20978392,
  "satisfaction_rating": {
    "comment": "Great support!",
    "id": 1234,
    "score": "good"
  },
  "sharing_agreement_ids": [
    84432
  ],
  "status": "open",
  "subject": "Help, my printer is on fire!",
  "submitter_id": 76872,
  "tags": [
    "enterprise",
    "other_tag"
  ],
  "type": "incident",
  "updated_at": "2011-05-05T10:38:52Z",
  "url": "https://company.zendesk.com/api/v2/tickets/35436.json",
  "via": {
    "channel": "web"
  }
}

3. Let's Create Lightning Web Component.

We are creating a button, "Get Zendesk Tickets". After click on this button it launches login screen and a list of Tickets from Zendesk to Save in Salesforce.

Zendesktickets.html

<template>
    <button class="slds-button slds-button_brand" onclick={loginscreen}>Get Zendesk Tickets</button>
    <template if:true={loginFlag}>
        <section role="dialog" tabindex="-1" class="slds-modal slds-fade-in-open slds-modal_small "
            aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1">

            <div class="slds-modal__container">
                <header class="slds-modal__header">
                    <h2 id="modal-heading-01" class="slds-modal__title slds-hyphenate">Login Zendesk Account</h2>
                </header>
                <div class="whitebg slds-p-around_medium">
                    <lightning-input type="email" label="Email" name="email" onchange={onchangehandler}
                        placeholder="type here..." required></lightning-input>
                    <lightning-input type="password" label="Password" onchange={onchangehandler} name="password"
                        required value="initial value"></lightning-input>
                </div>
                <footer class="slds-modal__footer">
                    <button class="slds-button slds-button_brand" onclick={loginaction}>Login</button>
                    <button class="slds-button slds-button_brand" onclick={closeModal}>Close</button>
                </footer>
            </div>

        </section>
        <div class="slds-backdrop slds-backdrop_open"></div>
    </template>
    <template if:true={allTickets}>
        <section role="dialog" tabindex="-1" class="slds-modal slds-fade-in-open slds-modal_small "
            aria-labelledby="modal-heading-02" aria-modal="true" aria-describedby="modal-content-id-1">

            <div class="slds-modal__container">
                <header class="slds-modal__header">
                    <h2 id="modal-heading-02" class="slds-modal__title slds-hyphenate">Zendesk Tickets</h2>
                </header>
                <div class="whitebg slds-p-around_medium">
                    <lightning-datatable data={allTickets} columns={columns} key-field="Id">
                    </lightning-datatable>
                </div>
                <footer class="slds-modal__footer">
                    <button class="slds-button slds-button_brand" onclick={saveSelectedTickets}>Save in Salesforce</button>
                    <button class="slds-button slds-button_brand" onclick={closeModal}>Close</button>
                </footer>
            </div>

        </section>
        <div class="slds-backdrop slds-backdrop_open"></div>
    </template>
</template>

Zendesktickets.js

import { LightningElement, track } from 'lwc';
import getCases from '@salesforce/apex/zendeskcases.getCases';
import createCases from '@salesforce/apex/zendeskcases.createCases'
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class Zendesktickets extends LightningElement {
    loginFlag = false;
    @track allTickets;
    email;
    password;
    columns = [{
        label: 'Subject',
        fieldName: 'subject',
        type: 'text',
        sortable: true
    },
    {
        label: 'Priority',
        fieldName: 'priority',
        type: 'text',
        sortable: true
    },
    {
        label: 'Status',
        fieldName: 'status',
        type: 'text',
        sortable: true
    },
    {
        label: 'Description',
        fieldName: 'description',
        type: 'text',
        sortable: true
    }
    ];
    closeModal() {
        this.loginFlag = false;
        this.allTickets = undefined;
    }
    loginscreen() {
        this.loginFlag = true;
    }
    onchangehandler(event) {
        if (event.target.name === 'email')
            this.email = event.target.value;
        if (event.target.name === 'password')
            this.password = event.target.value;
    }
    loginaction() {
        getCases({ email: this.email, password: this.password })
            .then(data => {
                this.data = data;
                //console.log(data);
                if (data === 'Invalid Creds') {
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Login failed !!!',
                            message: 'Incorrect login details',
                            variant: 'error',
                        }),
                    );
                }
                if (data !== 'Invalid Creds') {
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Login success !!!',
                            message: 'Now you can access Cases.',
                            variant: 'success',
                        }),
                    );
                    const obj = JSON.parse(data);

                    this.allTickets = obj.tickets;
                    this.loginFlag = false;
                }
            })
            .catch(error => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error!!',
                        message: error.message,
                        variant: 'error',
                    }),
                );
            });
    }
    saveSelectedTickets(event) {
        var selectedRecords =
            this.template.querySelector("lightning-datatable").getSelectedRows();
        //console.log('selectedRecords are ' + selectedRecords.length);
        var selectedCases = [];
        for (var i = 0; i < selectedRecords.length; i++) {
            selectedCases.push(selectedRecords[i]);
        }
        //console.log(selectedCases);
        let strCases = JSON.stringify(selectedCases);
        //console.log(strCases);
        createCases({ caseList: strCases }).then(result => {
            this.error = undefined;
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success !!!',
                    message: 'Tickets Saved in Salesforce.',
                    variant: 'success',
                }),
            );
            console.log(result);
        })
            .catch(error => {
                console.log(error);
            });
    }
}   

Zendesktickets.css

.whitebg{
    background-color: white;
}

Zendesktickets.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__HomePage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__RecordAction</target>
    </targets>
</LightningComponentBundle>

Zendeskcases.apxc

public class zendeskcases {
    @auraEnabled
    public static String getCases(String email, String password){
        String username = email;
        String pword = password;
        Blob headerValue = Blob.valueOf(username + ':' + pword);
        String authorizationHeader = 'BASIC ' +
            EncodingUtil.base64Encode(headerValue);
        HttpRequest req = new HttpRequest();
        req.setHeader('Authorization', authorizationHeader);
        req.setEndpoint('https://heysalesforce.zendesk.com/api/v2/tickets.json');
        //req.setBody(jsonBody);
        req.setMethod('GET');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        if(res.getStatusCode() == 401)
            return 'Invalid Creds';
        //system.debug(res.getBody());
        return res.getBody();
    }  
    @auraEnabled
    public static void createCases(String caseList) {
        list<TicketsParser> allSelectedCases = (list<TicketsParser>)JSON.deserialize(caseList, list<TicketsParser>.class);
        //system.debug(allSelectedCases);
        list<case> allCases = new list<case>();
        for(TicketsParser t:allSelectedCases)
        {
            case c = new case();
            c.Status = t.status;
            c.Subject = t.subject;
            c.Description = t.description;
            c.Origin = 'Phone';
            allCases.add(c);	
        }
        insert allCases;
    }
}

TicketsParser.apxc

public class TicketsParser{
		public Decimal assignee_id{get;set;}
		public list<String> collaborator_ids{get;set;}
		public list<String> follower_ids{get;set;}
		public Decimal group_id{get;set;}
		public list<String> email_cc_ids{get;set;}
		public String organization_id{get;set;}
		public String forum_topic_id{get;set;}
		public Decimal submitter_id{get;set;}
		public String problem_id{get;set;}
		public Decimal requester_id{get;set;}
		public Boolean has_incidents{get;set;}
		public String recipient{get;set;}
		public Boolean is_public{get;set;}
		public String status{get;set;}
		public String due_at{get;set;}
		public String priority{get;set;}
		public list<String> tags{get;set;}
		public String description{get;set;}
		public list<String> custom_fields{get;set;}
		public String raw_subject{get;set;}
		public String satisfaction_rating{get;set;}
		public String subject{get;set;}
		public list<String> sharing_agreement_ids{get;set;}
		public String type{get;set;}
		public list<String> fields{get;set;}
		public String updated_at{get;set;}
		public list<String> followup_ids{get;set;}
		public String created_at{get;set;}
		public Decimal ticket_form_id{get;set;}
		public Decimal brand_id{get;set;}
		public String external_id{get;set;}
		public Boolean allow_channelback{get;set;}
		public Integer id{get;set;}
		public Boolean allow_attachments{get;set;}
		public String url{get;set;}
}

After creating above classes and Component.

Add it on Cases Record Page.

cases

For Demo, Please have a look at this video.

https://youtu.be/j5s_rq-3TCk

If you have any question Ask Me

Thanks for Reading :)

Write a comment for suggestions and hit the heart icon.


634
0

Tags: #salesforce #lightningComponent #salesforceIntegration

Comments

There are no comments yet.
Your message is required.

Get notified of new posts