Salesforce and Youtube Integration | LWC | Lightning web component

 
Salesforce and Youtube Integration

Salesforce and Youtube Integration


Hello Kid, hope you and your family is healthy and safe!! While the market demand is increasing for the salesforce developer we need to more focus on advanced skills like integration as well.

Earlier we have learnt about the basics of integration. Today we are going to build something wonderful recipe i.e. salesforce and most popular youtube platform integration with a very easy process.

Salesforce and youtube integration will help the users to search for knowledge videos within the platform as well as you can play music and continue your work. 

HOW IT WILL LOOK LIKE ?? 👇  Isn't it cool kid?? 😎
====
Salesforce and youtube Integration
====

So let's get started...


Pre-requisites :
- First thing first, in order to integrate the platform we will be using YouTube Data API to receive the video data from the youtube platform.
- For this, we need to create an API key and EndPoint from the google cloud console.

Now just follow me Kid 🏃🏻‍♂️

STEP 1 :

- Go to below google cloud console to generate your YouTube API key :

- Create a new YoiuTube Integration project just like below :

Salesforce and Youtube Integration

STEP 2 :

- Once you have selected the project, Now on the left side you click on the Library :

Salesforce and Youtube Integration

- Now search for Youtube Data API :

Salesforce and Youtube Integration
Now select the First result YouTube Data API V3 and now enable it on the next screen 


Salesforce and Youtube Integration


- Then click on the Manage button 

STEP 3 :

- Now select the Credentials tab on left side  :

Salesforce and Youtube Integration

- Here, you will get that magical API Key 🪄 . PLEASE COPY THIS API KEY SOMEWHERE IN NOTEPAD. We will be using it in a later part.

- Also, please note the ENDPOINT URL is :
https://www.googleapis.com/youtube/v3/search


Good job kid!! These both API Key and EndPoint which we have created will be just like your school Id card where your teachers will not allow you without your Id card 😄.

STEP 4 :

Now, it's time to hit this endpoint URL and make an API callout from your apex class right ??

Let's do it...⏭

- Create an Apex class called YTController 
- Please note that we will be creating the wrapper class here get all those required data into the wrapper so that further we will be using this in our lightning web component.

YTController.cls
====
public with sharing class YTController {
        private static final String SEARCH_URL = 'https://www.googleapis.com/youtube/v3/search';
        private static final String API_KEY = 'XXXXXXXXXXX'; //Put your API_KEY here 
    
        @AuraEnabled(cacheable=true)
        public static list<mywrapper> getYTVideos(string searchKey){
            searchKey = searchKey == null ? 'salesforce' : searchKey;
            // YouTube API Callouts
            Http http = new Http();
            HttpRequest req = new HttpRequest();
            Httpresponse res = null;
            String endpoint  = SEARCH_URL +
            '?part=snippet' +
            '&maxResults=20' +
            '&type=video' +
            '&q=' + EncodingUtil.urlEncode(searchKey, 'UTF-8') +
            '&key=' + API_KEY;
    
            req.setEndPoint(endpoint);
            req.setMethod('GET');
            res = http.send(req);
    
            //Deserializing json data
            YouTubeResult.Response response = (YouTubeResult.Response)JSON.deserialize(res.getBody(), YouTubeResult.Response.class);
            List<YouTubeResult.Item> items  =  response.items;
    
            //Filling Wrapper Data for lightning component
            List<mywrapper> wrp  = new List<mywrapper>();
    
            for (YouTubeResult.Item itemObj : items) {
                mywrapper YTWrap = new mywrapper();
                YTWrap.videoId = itemObj.id.videoId;
                YTWrap.description = itemObj.Snippet.description;
                YTWrap.thumbnails = itemObj.Snippet.thumbnails.medium.url;
                YTWrap.title = itemObj.Snippet.title;
                YTWrap.channelTitle = itemObj.Snippet.channelTitle;
    
                wrp.add(YTWrap);
            }
            return wrp;
    
        }
        public class mywrapper{
            @AuraEnabled public string videoId {get;set;}
            @AuraEnabled public string description {get;set;}
            @AuraEnabled public String thumbnails {get;set;}
            @AuraEnabled public String title {get;set;}
            @AuraEnabled public String channelTitle {get;set;}
            @AuraEnabled public String publishedAt  {get;set;}
        }
}
====

- In the above code, you need to put your API key which you have received or copied in 'XXXXXXXXXXX' here in the above code. This was the major secret of that secret API key kid 😅.

- Next, we have created the endpoint URL in the format in which youtube is excepting the request from our end.

- Further, we are just hitting the endpoint using HTTP callout.

This pattern is just like this kid :
Salesforce hitting endpoint -> YouTube will receive the request -> It will respond to the request as per the search query -> Response received at salesforce end.

- Now here is the tricky part where most of the people are stuck i.e. managing the JSON response received. (The response is in JSON format hope you remember this).

- Sample response reference from the YouTube API documentation :

Salesforce and youtube integration


Above is the sample response format you will your video details. 


Now, as you are smart enough to understand that we have to retrieve the required data from this JSON and store it in variables in the apex class.

This is why we need class YouTuberesult so that that JSON response can be further fetched from that JSON tree and map to a variable so that we can use it further to map to the wrapper as you can see in filling wrapper data section.

Now let's take a look at YouTubeResult apex class.


YouTubeResult.cls
====
public class YouTubeResult{
    public List<YouTubeResult.Item> items { get; set; }    
    public class Response {
        public String kind { get; set; }
        public String etag { get; set; }
        public String nextPageToken { get; set; }
        public String prevPageToken { get; set; }
        public YouTubeResult.PageInfo pageInfo { get; set; }
        public List<YouTubeResult.Item> items { get; set; }
    }
    
    public class PageInfo {
        public Integer totalResults { get; set; }
        public Integer resultsPerPage { get; set; }
    }
    
    public class Item {
        public String kind { get; set; }
        public String etag { get; set; }
        public YouTubeResult.Id id { get; set; }
        public YouTubeResult.Snippet snippet { get; set; }
    }
    
    public class Id {
        public String kind { get; set; }
        public String videoId { get; set; }
    }
    
    public class Snippet {
        public Datetime publishedAt { get; set; }
        public String channelId { get; set; }
        public String title { get; set; }
        public String description { get; set; }
        public YouTubeResult.Thumbnails thumbnails { get; set; }
        public String channelTitle { get; set; }
        public String liveBroadcastContent { get; set; }
    }
    
    public class Thumbnails {
        public YouTubeResult.Thumbnail medium { get; set; }
        public YouTubeResult.Thumbnail high { get; set; }
    }
    
    public class Thumbnail {
        public String url { get; set; }
    }
}
====

In the above class, you can see we are retrieving the required data from the JSON response tree as there are multi-level we have to deep dive to get the Thumbnail, id, page info etc.

So this is how we are making a callout and managing our response in apex.

Now, the next part is our LWC component. Here we are just taking the input string entered by the user and passing it to apex so that :
1. we can make a callout from our apex class for the search string
2. we can retrieve the response and map that too wrapper variable and return that wrapper.

Let's check the below 


STEP 5 :

- Lightning web component


yTSearchPlayer.html 
====
<template>
    <lightning-card>
        <center style="font-size: 2rem; background-color:#f0f0f0;"><img src="https://upload.wikimedia.org/wikipedia/commons/0/09/YouTube_full-color_icon_%282017%29.svg" width="65" height="60"><b> YouTube Search</b></center>
          <!-- Default/basic -->
          <div class="slds-p-around_medium lgc-bg">
            <div class="slds-grid slds-gutters">
                <div class="slds-col slds-size_2-of-3">
                    <lightning-input type="text" placeholder="type here..." value={searchInput} onchange={handleSearch}></lightning-input>
                </div>
                <div class="slds-col slds-size_1-of-3" style="padding-top: 19px;">
                    <lightning-button variant="brand" title="Let's Go Go" label="Search Video On Youtube" onclick={handleSubmit} ></lightning-button>
                </div>
              </div>
          </div>
     </lightning-card>
     
    <lightning-card title="Results">
          <template for:each={finalresult} for:item="acc">
               <div key={acc.Id}>
                    {acc.Name}
               </div>
          </template>
    <div class="slds-grid slds-gutters">
        <div class="slds-col slds-size_2-of-3">
    <article class="slds-card" style="margin: 5px;">
        <div class="slds-card__body slds-card__body_inner" style="padding: 0px;margin: 3px;">
            <iframe style="height:400px;width:100%;border-radius: 2px;" allowfullscreen src={viewUrl}></iframe>
        </div>
    </article>
    </div>
    <div class="slds-border_left">
    <div style="height: 400px; width:auto" class="slds-scrollable_y slds-col slds-size_1-of-3">
       
        <template for:each={videoResults} for:item="item">
            <span key={item.id}>
                <div class="slds-box">
            <article class="slds-card" style="margin: 5px;">
                <div class="slds-card__header slds-grid">
                    <header class="slds-media slds-media_center slds-has-flexi-truncate">
                        <div class="slds-media__figure">
                            <img style="width: 50px;height: 50px;border-radius: 9px;" src={item.thumbnails}/>
                        </div>
                        <div class="slds-media__body">
                            <h2 class="slds-card__header-title">
                                <a onclick={watchVideo} class="slds-card__header-link" data-id={item.videoId}>
                                    <span>{item.title}</span>
                                </a>
                            </h2>
                        </div>
                    </header>
                </div>
                <div class="slds-card__body slds-card__body_inner ">
                    <span style="font-weight: bold;">By: {item.channelTitle}</span> <br>
                    <span>{item.description}</span> --> 
                </div>
            </article>
       </div>
        </span>
        </template>
    
    </div>
    </div>
    </div>
</lightning-card>
</template>
====

In the above code, we have created the search box and below the result section for the response of callout.

The important thing here to notice is "data-id={item.videoId}" where this data-id will actually help you to identify on which video you have clicked and give you that particular record in your javascript code (we will see that don't;t worry in JS code 👨‍💻)


To view UI you need to deploy this kid let's quickly check the JS code and then we will see the complete framework we have built at the end.


yTSearchPlayer.js
====
import { LightningElement ,track} from 'lwc';
import getVideos from '@salesforce/apex/YTController.getYTVideos';
export default class YTSearchPlayer extends LightningElement {
    @track finalresult = [];
    @track finalError = '';
    @track searchInput = 'salesforce trailblazer';
    @track videoResults = [];
    @track viewUrl = '';
  //Below method will be called on load of component 
    connectedCallback(){
         this.handleSubmit();
    }
  // If you wanted to do something when user is entering the string
    handleSearch(event){
         this.searchInput = event.target.value;
         console.log('This is searchInput::'+ this.searchInput);
    }
  //To map the videoResults to iframe and related list 
    handleSubmit(){
         getVideos({searchKey:this.searchInput})
         .then ((results)=>{
              this.videoResults = results;
              console.log('This is final video results ::'+ JSON.stringify(this.videoResults));

              if (this.videoResults.length > 0) {
                   this.showVideoInIframe(this.videoResults[0].videoId);
              }
         })
         .catch((error)=>{
              this.finalError = error.body.message;
              console.log('This is final video results ::'+ this.finalError);
         })

    }

    //To show youtube video
    showVideoInIframe(videoId){
         this.viewUrl = 'https://www.youtube.com/embed/'+videoId;
     }
     // Play video from related results
    watchVideo(event){
         let slt = event.currentTarget.dataset.id;
         console.log('This is selected video:'+ slt);
         this.viewUrl = 'https://www.youtube.com/embed/'+slt;
    }
}
====

In the above code, we are mapping the searchInput field and sending it to the server-side controller (apex) to get related youtube video results for it and storing all the results in videoResults and finally we are iterating those results received in this video results in .HTML file for:each section and displaying the youtube video.

Also, for the main iframe screen, we have this viewURL in youTube video URL link format.

All other sections are self-explanatory where we are just handling the onclick events.

Now as mentioned in the above you will have question that how to identify on which video you have clicked ?

Here is the answer kid, event.currentTarget.dataset.id; in above code will give you current videoID. 

How ??
Do you remember the important point in HTML file above, yess!! that's correct its data-id which will tell you the current item id from the loop.

This will be helpful for you in future as well. Hence please make a note of this kid. High five ✋ 

yTSearchPlayer.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__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
         <target>lightning__Tab</target>
     </targets>
</LightningComponentBundle>
====


Further, we need to add this component anywhere on the page. I used this in the lightning tab but its my style of putting it. Please don't copy my style kid. Everyone's life exams are different hence you have to think differently than others and create in your own way. Shhhhh!! OKEY..too much talking sorry! 🤭

IMPORTANT :
====
Now the very very important to get your YouTube API allow to make callout is by adding it to the Remote Site Settings without this your endpoint will not work.

To add this go to Setup -> Remote Site Settings 

Just like below. :
====
Salesforce and Youtube Integration


====

Now it's showtime to check our recipe what we have created. Hence just deploy the component


OUTPUT :
====

====


Yieeee!! Kid party time finally you are now able to search and watch videos inside your salesforce org. You can use this as a knowledge base for your salesforce user specially the service agents who are looking for some extra knowledge related to the topic or issues.

Hope you liked it!! See you in the next episode Kid 😉

WOHOOO !! YOU HAVE JUST COMPLETED SALESFORCE AND YOUTUBE INTEGRATION WITH LWC EPISODE
If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you all
Happy Learning ☁️⚡️ (Learn. Help. Share.) 😊


Salesforce and Youtube Integration on play store

Salesforce and Youtube Integration | LWC | Lightning web component Salesforce and Youtube Integration | LWC | Lightning web component Reviewed by on Rating: 5

1 comment:

  1. How to auto Pause the YouTube video when the we move from one tab to another tab.
    Problem is if we change the tab then also the video is getting played in the background.

    ReplyDelete

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.