function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Manu Yadav 25Manu Yadav 25 

component.get("page reference ") is not working in lightning

Hi,

Apex Controller
===============================
public class GoogleDriveController
{
    private static String key = '1030522894057-aoqqrckioqgqpljnh277n5cr8hqfhd0s.apps.googleusercontent.com';
    private Static String secert = 'plgBENpw7SMXGCvCpwDWEmdf';
    private Static string redirect_uri = 'https://manuyadav-dev-ed.lightning.force.com/lightning/o/Account/list';
    //private Static string redirect_uri = 'https://manuyadav-dev-ed.lightning.force.com/0016F00002RFSohQAH';
    private String accessToken;
    
    @AuraEnabled
    public static String createAuthURL() {
        String key = EncodingUtil.urlEncode(key,'UTF-8');
        String uri = EncodingUtil.urlEncode(redirect_uri,'UTF-8');
        String authuri = '';
        system.debug('++++++Authstart+++++++'+authuri);
        authuri = 'https://accounts.google.com/o/oauth2/auth?'+
            'client_id='+key+
            '&response_type=code'+
            '&scope=https://www.googleapis.com/auth/drive'+
            '&redirect_uri='+uri+
            '&state=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' +
            +
            '&access_type=offline';
        system.debug('++++++AuthUri+++++++'+authuri);
        return authuri;
    }
    
    @AuraEnabled
    public static String getaccessToken(String code)
    { 
        // String authurl=createAuthURL();
        //Getting access token from google
        HttpRequest req = new HttpRequest();
        System.debug('++AsscessToken++'+req);
        req.setMethod('POST');
        req.setEndpoint('https://accounts.google.com/o/oauth2/token');
        req.setHeader('content-type', 'application/x-www-form-urlencoded');
        String messageBody ='code='+code+'client_id='+key+'&client_secret='+secert+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code';
        req.setHeader('Content-length', String.valueOf(messageBody.length()));
        req.setBody(messageBody);
        req.setTimeout(60*1000);
        
        Http h = new Http();
        String resp;
        system.debug('++token string resp++'+resp);
        HttpResponse res = h.send(req);
        system.debug('++tokenresp++'+res);
        resp = res.getBody();
        system.debug('++tokenrespgetbody++'+resp);
        Map<String,object> responseMap =(Map<String,object>)JSON.deserializeUntyped(res.getBody()) ;  
        String token =  String.valueOf(responseMap.get('access_token'));
        system.debug('++token++'+Token);
        return token;
        
    }
    
    @AuraEnabled
    public static String uploadFile(String attachmentId, String accessToken) {
        List<ContentVersion> cvFile = [SELECT VersionData,FileType,ContentDocumentId FROM ContentVersion WHERE ContentDocumentId =: attachmentId];
        Blob myBlob = cvFile[0].VersionData;
        String url = 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media';
        string authorizationHeader = 'Bearer ' + accessToken; 
        Integer contentSize = myBlob.size();
        HttpRequest req = new HttpRequest();
        system.debug('++++++++Filereq+++++++'+req);
        req.setheader('Authorization',authorizationHeader);
        req.setheader('Content-Length',String.valueOf(contentSize));
        req.setheader('Content-Type','image/'+cvFile[0].FileType);
        req.setMethod('POST'); 
        req.setEndpoint(url); 
        req.setBodyAsBlob(myBlob); 
        Http h = new Http(); 
        system.debug('++++++++FileHTTP+++++++'+h);
        Httpresponse resp = h.send(req);
        system.debug('++++++++File+++++++'+resp);
        //After file was successfully upload we delete the file
        delete new ContentDocument(Id = cvFile[0].ContentDocumentId);
        return String.valueOf(resp.getStatuscode());
    }
}

Component
=============================
<aura:component controller="GoogleDriveController" implements="lightning:isUrlAddressable,force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
      <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="accessToken" type="String" />
    <aura:attribute name="myRecordId" type="String" default="0016F000024M3iGQAS" description="This is the record where we will temproary store the file"/>
    
    <lightning:card title="Google Drive Demo">
        <lightning:button variant="brand" label="Google Drive Auth" title="Google Drive Auth" onclick="{! c.doAuth }" />
        <hr/>
        <p class="slds-p-horizontal_small">
            <!--file upload part -->
            <lightning:fileUpload label="upload file to Drive" name="fileUploader"
                multiple="false" accept=".jpg, .png" recordId="{!v.myRecordId}" onuploadfinished="{!c.handleFilesChange}" />
          </p>
    </lightning:card>
</aura:component>

Js Component
=====================
({
    
    doInit : function(component, event, helper) {
        
       //if(component.get("v.pageReference") != undefined && component.get("v.pageReference") != 'undefined') 
       if(component.get("v.pageReference") != undefined && component.get("v.pageReference") != 'undefined'){
        var code = component.get("v.pageReference").state.c__code;
           console.log('test');
        console.log('code',code);
        if(code != undefined)
            var action  = component.get("c.getaccessToken");
            console.log('actioncheckinggg',action);
            action.setParams({
                "code" : code
                           });
            action.setCallback(this, function(response){
            var status = response.getState();
                console.log('checkinggg',status);
            if(status === "SUCCESS"){
                var accessToken = response.getReturnValue();
                console.log('tokennn',accessToken)
                component.set("v.accessToken", accessToken);
                
            }
        });
        
        $A.enqueueAction(action);
        }
      },
    
    doAuth : function(component, event, helper) {
        
        var action  = component.get("c.createAuthURL");
        action.setCallback(this, function(response){
            var status = response.getState();
            console.log('checkinggg auth****',status);
            if(status === "SUCCESS"){
                console.log('response',response.getReturnValue());
                var authUrl = response.getReturnValue();
                window.location.href = response.getReturnValue();
                
                
                //if you want to use standard method use below code. But it will open in new tab.
                /* var urlEvent = $A.get("e.force:navigateToURL");
                urlEvent.setParams({
                  "url": authUrl
                });
                urlEvent.fire();*/
                
            }
        });
        
        $A.enqueueAction(action);
    },
    
    handleFilesChange : function(component, event, helper) {
        var uploadedFiles = event.getParam("files");
        var attachmentId = uploadedFiles[0].documentId;
        var code = component.get("v.accessToken");
        
        var action  = component.get("c.uploadFile");
        action.setParams({
            "attachmentId": attachmentId,
            "accessToken" : code
        });
        action.setCallback(this, function(response){
            var status = response.getState();
            
            if(status === "SUCCESS"){
                var responseCode = response.getReturnValue();
                console.log('checkinggg+++upload',responseCode);
                if(responseCode == '200')
                    alert('File Uploaded successfully');
                else
                    alert('There was some error');
            }
        });
        
        $A.enqueueAction(action);
    }
})

In the above code, I could not get token access from the external application then I tried to start debugging even doinit method is not calling from the component. 
Sachin HoodaSachin Hooda
Hi Manu,
Are you using the component on lighting page?
If you've the parameters in the URL , you can use get them like
doInit : function (c,e,h){
   if(window.location.href.includes('&access_code=')){
    let parameters = window.location.href.split('&'); 
    let accessToken = parameters [0].split('=');
    c.set('v.accessToken', accessToken);
    }

}
If you need any other help. Please post your queries here.

_______
Regards,
Sachin
(:

 
David Zhu 🔥David Zhu 🔥
I think this aura component is open through Navigation. In that case, you may need to change this line to 
var code = component.get("v.pageReference.state.code");

Also, make sure case of  property "code" matches the one in the navigation component.
Manu Yadav 25Manu Yadav 25
Hi David, 
thanks for responding but It's not working still...
David Zhu 🔥David Zhu 🔥
@Manu, what is the attribute you assigned you the parent component. It should be like below. Make sure it is "c__code", not "code".
handleClick : function(component, event, helper) {

        component.find("navigationService").navigate({
            type: "standard__component",
            attributes: {
                componentName: "c__GoogleDrive"   //your component
            },
            state: {
                "c__code": "foo"   //assign record id.
            }
        });

    }