400 Error Code on callout using User-Password oAuth FLow - salesforce

I am getting bad request error while trying to get token using this piece of code:
String clientId = '3MVG9t0sl2P.pByrrjfFFCVMbFHMMMm.qRQK6yRQw8Mg0rfs1s_.x2q1TuhonbyuxNJlugwGXKIvGmFEJ';
String clientSecret = '0ABB12793CB8CEB88DCFC9103DE2867A72642025E5F7DC40CB77B5A986404';
String username='mp7mp#gmail.com';//salesforce username
String password='Yg8#';//EUe4eHjMxXb8UFco1SPcpsZL9';//salesforce password
// Generating the Access Token
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('https://login.salesforce.com/services/oauth2/token');// this is the OAuth endpoint where this request will be hit
req.setBody('grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password);
Http http = new Http();
HTTPResponse response = http.send(req);
if(response.getStatusCode() == 200){
system.debug('## Successfully retrieving access token' );
map<string,Object> resultMap = (map<string,Object>)JSON.deserializeUntyped(response.getBody());
accesstoken = (String)resultMap.get('access_token');
instanceURL = (String)resultMap.get('instance_url');
system.debug('Accesstoken'+ accesstoken );
system.debug('instanceURL'+ instanceURL);
//step 2 : use the token for the salesforce api call
}
else{
system.debug('## Could not retrieve the access token' + response.getStatusCode() + '--'+ response.getStatus());
system.debug('## response status :' + response.getStatus());
system.debug('## response message :' + response.getBody());
}
This is the request:
grant_type=password&client_id=3MVG9t0sl2P.pByrrjfFFCm.qRQK6yo58pRQw8Mg0rfs1s_.x2q1TuhonbyuxNJlugwGXKIvGmFEJ&client_secret=0ABB12793738CEB88DCFC9103DE2867A72642025E5F7DC40CB77B5A986404&username=mp7504.mp#com&password=Ygua8#

Related

Cannot upload a file in blob in sharefile

I am trying to upload a file in Citrix ShareFile via REST API. There are four requests
Get the access_token
Get the folder URI's to decide n which I am going to upload the file.
Get chunk Uri
Upload the file in that chunk Uri
The first three steps work perfectly. When I am trying to POST a request for the no 4. part,
it is creating a file in sharefile but with size of 0.
I have tried that with POSTMAN, and with form-data and the selection of a file, it is working fine. The file is uploaded in sharefile.
The problem arises when I am trying to upload blob data.
I am calling this methods from Salesforce Platform and in Salesforce, I cannot get the physical file in a physical location. I have blob file data stored in salesforce database.
The below part works well.
String fileName_m = 'a12.pdf';
// Get Authentication Token
HttpRequest req = new HttpRequest();
req.setEndpoint('https://{server}.sf-api.com/oauth/token?grant_type=password&client_id={client_id}&client_secret={secret}&username={user_name}&password={password}!');
req.setMethod('GET');
Http http = new Http();
HttpResponse response = http.send(req);
System.Debug(response.getBody());
Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());
String token = '';
String refreshtoken = '';
if(response.getStatusCode() == 200){
token = (String)results.get('access_token');
refreshtoken = (String)results.get('refresh_token');
}
system.debug('token=' + token);
// Get Folder ID
HttpRequest req1 = new HttpRequest();
req1.setEndpoint('https://{server}.sf-api.com/sf/v3/Items?$expand=Children');
req1.setMethod('GET');
req1.setHeader('Authorization','Bearer ' + token);
Http http1 = new Http();
HttpResponse response1 = http1.send(req1);
System.Debug(response1.getBody());
Map<String, Object> results1 = (Map<String, Object>)JSON.deserializeUntyped(response1.getBody());
String url = '';
if(response1.getStatusCode() == 200){
url = (String)results1.get('url');
}
System.Debug('Folder Url ' + url);
// Get Chunk URI
HttpRequest req2 = new HttpRequest();
String endPoint = url + '/Upload2';
req2.setEndpoint(endPoint);
req2.setMethod('POST');
req2.setHeader('Authorization','Bearer ' + token);
req2.setHeader('Content-Type', 'application/x-www-form-urlencoded');
String payload1 = 'FileName='+fileName_m;
req2.setBody(payload1);
Http http2 = new Http();
HttpResponse response2 = http2.send(req2);
Map<String, Object> results2 = (Map<String, Object>)JSON.deserializeUntyped(response2.getBody());
String ChunkUri = '';
if(response2.getStatusCode() == 200){
ChunkUri = (String)results2.get('ChunkUri');
}
System.Debug('ChunkUri' + ChunkUri);
But, when I am trying to upload blob file data in sharefile, the API responds with a 200 status code. In sharefile, the file is created, but the size of the file is 0.
// Problem is here, it is not working
// Upload File
Attachment att = [SELECT Id, Body, Name, ContentType FROM Attachment WHERE Id='00P3p00001XNLOHEA5'];
String body = EncodingUtil.base64Encode(att.body);
List<Attachment> cvList = [SELECT Id, Body, Name, ContentType FROM Attachment WHERE Id='00P3p00001XNLOHEA5'];
String attachmentBody = EncodingUtil.base64Encode(cvList[0].Body);
Blob pdfBlob = EncodingUtil.base64Decode(attachmentBody);
system.debug('pdfBlob' + pdfBlob);
HttpRequest req3 = new HttpRequest();
req3.setEndpoint(ChunkUri);
req3.setMethod('POST');
req3.setHeader('Authorization','Bearer ' + token);
req3.setHeader('Content-Length', String.valueOf(attachmentBody.length()));
req3.setHeader('Content-Encoding', 'UTF-8');
req3.setHeader('Content-type', 'application/pdf');
req3.setHeader('Connection', 'keep-alive');
req3.setBodyAsBlob(pdfBlob);
Http http3 = new Http();
HttpResponse response3 = http3.send(req3);
System.Debug(response3.getBody());
How to solve the issue?

Forbidden 403 response from Google Calendar API while calling from Salesforce Using Server-to-Server

I'm trying to insert an event on Google Calendar using REST API, I'm using JWT to get the access token as I don't want user to login into google account to get token. I'd performed below steps, but still getting the error:
I've created one service account
I'm getting a Token from google to send the request
I've shared the calendar with Service Account email address as well.
Please see below code:
public class GoogleCalendarSynchronization {
public static void addEvent (){
String accessToken = GenerateJWTBearerToken.generateTokenforGoogleCalendarServices();
system.debug(accessToken);
String createEventEndPoint = 'https://www.googleapis.com/calendar/v3/calendars/primary/events/';
String createEventBody = '{' +
'"attendees": ['+
'{'+
'"email": "abc#gmail.com"'+
'},'+
'{'+
'"email": "abc#gmail.com"'+
'}'+
'],'+
'"end": {'+
'"dateTime": "2019-12-27T03:30:00-07:00"'+
'},'+
'"start": {'+
'"dateTime": "2019-12-27T03:30:00-06:00"'+
'},'+
'"summary": "Appointment has been confirmed..!!",'+
'"location": "TEST",'+
'"sendUpdates": "all"'+
'}';
//system.debug(createEventBody);
Http http = new Http();
HttpRequest httpReq = new HttpRequest();
HttpResponse HttpRes = new HttpResponse();
httpReq.setEndpoint(createEventEndPoint);
httpReq.setMethod('POST');
httpReq.setBody(createEventBody);
httpReq.setHeader('Content-Type', 'application/json');
httpReq.setHeader('Authorization','Bearer ' + accessToken);
try{
HttpRes = http.send(httpReq);
if(HttpRes.getStatusCode() == 200){
String response = HttpRes.getBody();
system.debug(response);
Map<String, Object> responseMap = (Map<String, Object>)JSON.deserializeUntyped(response);
system.debug(responseMap.get('id'));
system.debug('calendar is saved successfully..!!');
}else{
String errorMessage = 'Unexpected Error while communicating with Google Calendar API. '
+'Status '+HttpRes.getStatus()+' and Status Code '+HttpRes.getStatuscode();
system.debug(errorMessage);
}
} catch(system.Exception e){
System.debug('#### Exception Executed : '+e.getMessage() + ' ' + e.getStackTraceString() + ' ' +e.getLineNumber());
}
}
}

Salesforce test web service call

Here is the code for a helper function
public class SalesforceHelper {
public static void waitCall(String timeout){
System_Settings__c lnpSetting = System_Settings__c.getValues('System Properties');
String endpoint=lnpSetting.Base_Endpoint_URL__c + 'salesforceHelper/wait?timeout=' + timeout;
system.debug('====endpoint======'+endpoint);
HttpRequest httpReq=new HttpRequest();
HttpResponse httpResp = new HttpResponse();
Http http = new Http();
httpReq.setMethod('GET');
httpReq.setEndpoint(endpoint);
String username=lnpSetting.Endpoint_Username__c;
String password=lnpSetting.Endpoint_Password__c;
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
httpReq.setHeader('Authorization', authorizationHeader);
httpReq.setHeader('content-type','application/json; charset=utf-8');
httpReq.setTimeout(120000);
try{
httpResp = http.send(httpReq);
System.debug('Wait response' + httpResp);
} catch (Exception e) {
system.debug(LoggingLevel.Error, 'Error HTTP response code = ' + httpResp.getStatusCode() + '; calling '+endpoint );
}
}
}
Basically this method just using HttpRequest and HttpResponse to call the endpoint URL, and the endpoint URL is web service, and it will just return 200 after the timeout that specified in the parameter.
Now the question is, I need to write a test case to cover this method, and I don't know how to write it.. I don't know how to mock the httpcallout properly, because this method doesn't return HttpResponse, and since the code is freeze right now, I cannot modified my class to make the test case work.
So any other way I can create the test class for this method?
You should definitely be able to use standard Http Callout Mock:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm
The only difference would be that you'd only set stats code:
// Create a fake response
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
return res;
and check for response code:
System.assertEquals(200, res.getStatusCode());

Login to Docusign API through apex

I am trying to connect to Docusign REST API making 'login_information' call from the Salesforce developers console, but having an issue:
'The URL provided does not resolve to a resource'.
Here is my code:
private static final string TOKEN_URL = 'https://demo.docusign.net/restapi/v2/login_information';
private static final string userName = 'username';
private static final string password = 'password';
private static final string integrationKey = 'integrationKey';
string authenticationHeader =
'<DocuSignCredentials>' +
'<Username>' + userName+ '</Username>' +
'<Password>' + password + '</Password>' +
'<IntegratorKey>' + integrationKey + '</IntegratorKey>' +
'</DocuSignCredentials>';
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setEndpoint(TOKEN_URL);
req.setHeader('Content-Type', 'application/json');
req.setHeader('Accept', 'application/json');
req.setHeader('X-DocuSign-Authentication', authenticationHeader);
req.setMethod('GET');
req.setBody('');
res = http.send(req);
I am able to log in to Docusign Console using my credentials, so all is correct. But can't do the same through Apex. Could it be lack of permissions?
req.setBody(''); should be removed from code. It fixed the problem.

using HTTPRequest setPayload in google app engine

I am trying to do HTTPRequest Post via Google App Engine.
This is what I have so far
URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(########);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
Here I need to put some paired values (ie. "email","hi#example.com" etc)
Since setPayload accept byte[] I have no idea how to convert my paired values
into byte.
I have searched other posts but I am very stuck.
EDIT:
I have changed to this but it is still not working
byte[] data = ("EMAIL=bo0#gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000;").getBytes();
try {
URL url = new URL("http://www.bo.x10.mx/nPost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
This is what I have on php website.
<?php
include "path/conf.php"; //logging into database works
$tb_name = 'Post';
$EMAIL=$_POST['EMAIL'];
$TITLE =$_POST['TITLE'];
$COMMENT =$_POST['COMMENT'];
$PRICE =$_POST['PRICE'];
if(!isset($EMAIL) || !isset($TITLE ) || !isset($PRICE )|| !isset($COMMENT)){
header('HTTP/1.0 412 Precondition Failed', true, 412);
die('Bad data');
}
$sql="INSERT INTO $tb_name(EMAIL, TITLE, COMMENT, PRICE) VALUES ('$EMAIL', '$TITLE ', '$COMMENT ', '$PRICE ')";
$result=mysql_query($sql);
if($result==TRUE){
echo "successfully inserted into table!";}
else{
echo "error in inserting into table!";
header('HTTP/1.0 500 Internal Server Error', true, 500);}
ob_end_flush();
exit();
?>
EDIT2: This is a working code
try{
byte[] data = ("EMAIL=bo0#gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000").getBytes("UTF-8");
URL url = new URL("http://www.box.com/nost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
}
My database string field is of type UTF-8
You create a String with the request body, and then you get the byte array. For example we have:
URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
String body = "email=" + email + "&mpla=" + mpla;
request.setPayload(body.getBytes("UTF-8"));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
Hope this helps!

Resources