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
klthawklthaw 

Using sdk library in apex

Hi there, can we use static resource sdk js library in apex?



 
RituSharmaRituSharma
You can't use js libraries in APEX. 
klthawklthaw
Thanks,

I want to use aws sdk (s3, connect) in apex that is why I asked.
Is there anyway to implement it please share.
I tried it in vf page, it works but for security I want to try it in apex.
if there is no way to use sdk in apex, i have plan with rest api for aws service in apex.
Is there is best way for REST API with s3 and connect please share here. Thanks.

Regards,
LinThaw
RituSharmaRituSharma
You don't need SDK for this. You may push files from Salesforce to S3 using S3 API. Refer the URL for details: https://salesforcecodex.com/2020/01/uploading-files-to-s3-server-using-apex/

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.
klthawklthaw

Thanks, how about amazon connect? I want to try it look like s3 api.

https://www.any-api.com/amazonaws_com/connect/docs/_users_InstanceId_UserId_/DescribeUser

RituSharmaRituSharma
I have not used the connect but I have used the API and it's very easy to use.
RituSharmaRituSharma
Try below code. FileUploadService is another class that reads the AWS attributes(stored in metadata settings). You may create FileUploadService  
   
//To upload file to amazon S3
    public static String uploadToAmazonS3 (String fileName, Blob attachmentBody, String fileContentType) {    
        String uploadFileName = fileName.replace(' ','_');
        String formattedDateStr = Datetime.now().formatGMT('EEE, dd MMM yyyy HH:mm:ss z');
        String signed = FileUploadService.generateSignedPolicy(FileUploadService.AWS_BUCKET_NAME, formattedDateStr);
        
        String uploadedFileURL ='FileUploadError';
        String enCodedFileName = EncodingUtil.urlEncode(uploadFileName, 'UTF-8');
        HttpRequest req = new HttpRequest();
        req.setMethod('PUT');
        req.setHeader('Host', FileUploadService.AWS_HOST);
        String finalURL = 'https://' + FileUploadService.AWS_HOST + '/' + enCodedFileName;
        req.setEndpoint(finalURL); 
        req.setHeader('Content-Length','50' );//String.valueOf(attachmentBody.toString().length())
        req.setHeader('Content-Type', fileContentType);
        req.setHeader('Connection', 'keep-alive');
        req.setHeader('date', formattedDateStr);  
        req.setHeader('x-amz-acl', 'public-read'); 
        
        //get signature string
        String stringToSign = 'PUT\n\n'+
                            fileContentType + '\n' +                         
                            formattedDateStr+'\nx-amz-acl:public-read\n/'+
                            FileUploadService.AWS_BUCKET_NAME+'/'+
                            enCodedFileName;
        string sig;
        Blob mac = Crypto.generateMac('HMACSHA1', blob.valueof(stringToSign),blob.valueof(FileUploadService.AWS_SECRET_KEY));
        sig = EncodingUtil.base64Encode(mac); 
        String authHeader = 'AWS' + ' ' + FileUploadService.AWS_ACCESS_KEY + ':' + sig;
        req.setHeader('Authorization',authHeader);
           req.setBodyAsBlob(attachmentBody);       
        
        Http http = new Http();
        HTTPResponse res = new HTTPResponse();
        try {
            //Execute web service call
            res = http.send(req);    
            
            if(res.getStatusCode()==200){
                uploadedFileURL = finalURL;
            } else{
                SystemLogHelper.insertLog('S3FileUpload',false,'', 'Error occured - ' + res.getStatus(), '',null,true);
            }
            return uploadedFileURL;

        } catch(System.CalloutException e) {
            system.debug('AWS Service Callout Exception: ' + e.getMessage());
            uploadedFileURL = 'FileUploadError';
            SystemLogHelper.insertLog('S3FileUpload',false,'', 'Error occured - ' + e.getMessage(), '',null,true);
            return uploadedFileURL;
        }   
    }
RituSharmaRituSharma
Please refer the code from here -> https://salesforcecodex.com/2020/01/uploading-files-to-s3-server-using-apex/
klthawklthaw
Hi Ritu, Thanks I got s3. above error is for amazon connect.
RituSharmaRituSharma
Please mark my answer as the best answer if that was helpful. This will help others in future.
klthawklthaw
let me close this thread after amazon connect rest api solve! (not using sdk and lambda).
klthawklthaw
I am trying to access Amazon Connect api (GetDescribeUser) from Apex with REST API but I got following error.
403 Forbidden Unable to determine service/operation name to be authorized
public void GetDescribeUser(){
    
    String path = 'users/' + InstanceId + '/' + ACUserId;
    String exipredFormat = '800';
    Datetime currentDate = Datetime.now();         
    String todayformat =  currentDate.formatGMT('yyyyMMdd'); 
    Blob b = Blob.valueOf('UNSIGNED-PAYLOAD');   
    string amz_content_sha256 = EncodingUtil.convertToHex(Crypto.generateDigest('SHA-256', b)); 
    
    /* Send to Amazon Connect */
    HttpRequest req = new HttpRequest();          
                 
    /*Set HTTPRequest Method*/
    req.setMethod('GET');         
    
    /*Set HTTPRequest header properties*/
    req.setHeader('content-type', 'application/json;charset=utf-8');
    req.setHeader('Content-Length',String.valueOf(b.size()));
    req.setHeader('Host','connect.ap-northeast-1.amazonaws.com');
    req.setHeader('x-amz-content-sha256',amz_content_sha256);   
    req.setHeader('Date',currentDate.formatGMT('EEE, d MMM yyyy HH:mm:ss Z')); 
    req.setHeader('x-amz-date',currentDate.formatGMT('yyyyMMdd')+'T'+currentDate.formatGMT('HHmmss')+'Z'); 
    
    String key = 'AWS4' + AWSSecretAccessKey;        
    Blob DateKey                 = Crypto.generateMac('hmacSHA256',Blob.valueOf(todayformat),Blob.valueOf(key));
    Blob DateRegionKey           = Crypto.generateMac('hmacSHA256',Blob.valueOf('ap-northeast-1'),DateKey);
    Blob DateRegionServiceKey    = Crypto.generateMac('hmacSHA256',Blob.valueOf('connect'),DateRegionKey);
    Blob SigningKey              = Crypto.generateMac('hmacSHA256',Blob.valueOf('aws4_request'),DateRegionServiceKey);        
    String canonical =  'GET\n'+
        '/'+ path +'\n\n'+                
        'date:' + currentDate.formatGMT('EEE, d MMM yyyy HH:mm:ss Z')+'\n'+
        'host:connect.ap-northeast-1.amazonaws.com\n'+
        'x-amz-content-sha256:'+amz_content_sha256+'\n'+
        'x-amz-expires:'+exipredFormat +'\n'+
        'x-amz-date:'+currentDate.formatGMT('yyyyMMdd')+'T'+currentDate.formatGMT('HHmmss')+'Z'+'\n'+          
        'date;host;x-amz-content-sha256;x-amz-expires;x-amz-date\n'
        +amz_content_sha256;
    
    Blob canonicalsign = Crypto.generateDigest('SHA-256', Blob.valueOf(canonical));  
    Blob StringToSign = Blob.valueOf('AWS4-HMAC-SHA256\n'+
                                     currentDate.formatGMT('yyyyMMdd')+'T'+currentDate.formatGMT('HHmmss')+'Z'+'\n'+
                                     currentDate.formatGMT('yyyyMMdd')+'/ap-northeast-1/connect/aws4_request\n'+
                                     EncodingUtil.convertToHex(canonicalsign));        
    Blob bsig =  Crypto.generateMac('hmacSHA256',StringToSign,SigningKey);        
    req.setHeader('Authorization', 'AWS4-HMAC-SHA256 Credential='+ AWSAccessKeyId +'/'+todayformat+'/ap-northeast-1/connect/aws4_request,SignedHeaders=date;host;x-amz-content-sha256;x-amz-expires;x-amz-date,Signature='+EncodingUtil.convertToHex(bsig));
    String docBody = EncodingUtil.convertToHex(b);
    
    /*Set the HTTPRequest body */   
    req.setBodyAsBlob(b);  
    
    /*Set the HTTPRequest endpoint */   
    req.setEndpoint('https://connect.ap-northeast-1.amazonaws.com/'+ path);
    
    Http http = new Http();        
    try {   
        HTTPResponse res = http.send(req); 
        System.debug('res BODY : ' + res.getBody());    
        System.debug('res STATUS : '+res.getStatus());            
        System.debug('STATUS_CODE : '+res.getStatusCode());                        
    } catch(System.CalloutException e) {           
        System.debug('err : ' + e);
    }             
    
}

Anyone help will be appreciated.
Regards,
LinThaw