How can I update a case in Salesforce using twilio functions? - javascript

I am using Twilio to integrate Salesforce with Whatsapp. When I get a message I create a case in Salesforce, how can I update the same case with 'closed' status?
I am trying to use this code, but I receive a error message
exports.handler = function(context, event, callback) {
const requestPayload = `{"Status":"Closed"}`;
const stts = JSON.parse(requestPayload);
getTokenInformation()
.then(token => {
const options = {
Authorization: 'Bearer ' + token.access_token,
'Content-Type': 'application/json'
};
return got(`${token.instance_url}/services/data/v56.0/sobjects/Case/${event.caseId}`, {
headers: options,
json: true,
method: 'PATCH',
body: stts,
});
Error message:
SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at /var/task/handlers/ZF17ec8620a9320c740bb2f847bb1240b1.js:79:31
at processTicksAndRejections (internal/process/task_queues.js:95:5)

Related

Bad respond when trying to get authentication token for Reddit api 'Application Only OAuth'

So i been trying to get access to the reddit api.
I registered to reddit. verified my mail. opened an app and got my credentials.
Followed this official documentation and also came across to this tutorial
All my efforts have failed and don't get any respond.
I am using nodejs. but also tried in postman and failed.
Tried 2 options using fetch and using axios:
const axios = require('axios');
const fetch = require('node-fetch')
const { URLSearchParams } = require('url')
class RedditApi {
clientId2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
clientSecret2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
authenticationUrl = `https://www.reddit.com/api/v1/access_token`;
BASE_URL = 'https://www.reddit.com/';
tokenAuth = null;
tokenExpirationTime = null;
currencyObj = null;
constructor(currencyObj) {
this.currencyObj = currencyObj;
console.log("constructor service")
}
async getAuthToken() {
const bodyParams = new URLSearchParams({
grant_type: "https://oauth.reddit.com/grants/installed_client",
device_id: "DO_NOT_TRACK_THIS_DEVICE"
});
console.log(this.clientId2, 'this.clientId');
debugger;
const headersObj = {
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}`,
'Content-Type': 'application/x-www-form-urlencoded',
};
let response = null;
try {
response = await axios.post(this.authenticationUrl,
bodyParams,
{
headers: headersObj
});
debugger;
} catch (error) {
debugger;
console.error(error);
console.log(error.stack);
return null;
}
}
async getAuthToken2() {
try {
// Creating Body for the POST request which are URL encoded
const params = new URLSearchParams()
params.append('grant_type', 'https://www.reddit.com/api/v1/access_token')
params.append('device_id', 'DO_NOT_TRACK_THIS_DEVICE')
// Trigger POST to get the access token
const tokenData = await fetch('https://oauth.reddit.com/grants/installed_client', {
method: 'POST',
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}` // Put password as empty
}
}).then(res => {
debugger;
return res.text()
})
debugger;
if (!tokenData.error) {
debugger;
res.send(trendingResult)
}
res.status(tokenData.error).send(tokenData.message)
} catch (error) {
debugger;
console.log(error)
}
}
}
module.exports = RedditApi;
when using axios i get this respond: "Request failed with status code 401"
When using fetch i get this respond: "'403 Forbidden\nRequest forbidden by administrative rules.\n\n'"
Anybody knows what is the problem and how can i fix it?
Many thanks!

Invalid or Unexpected Token

I'm trying to set u a telegram bot whereby when someone makes a post on facebook, the post will be sent to telegram as well. Is there anything wrong with this code in general? I keep getting invalid or unexpected or token even after I have the correct API token and chat ID.
*API token and chat ID must be kept secret
const fetch = require('node-fetch');
let token = "<token*>";
let data = {
chat_id: "<chat ID*>",
text: "text"
};
​
(async () => {
await fetch(`https://api.telegram.org/bot${token}/sendMessage`,
{
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
}
}
)
})();

"grant_type parameter is missing": Spotify API PKCE OAuth Flow Troubles

I'm developing a React app that uses the Spotify API I can't figure out why I'm getting this error when trying to get an access token with the API's PKCE OAuth flow.
{
error: "unsupported_grant_type",
error_description: "grant_type parameter is missing"
}
I'm following the directions from the guide exactly and I'm able to obtain an auth code just fine. Here's my call trying to get the token.
let res = await axios.post("https://accounts.spotify.com/api/token", {}, {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
params: {
"grant_type": "authorization_code",
"code": data.code,
"redirect_uri": redirectUri,
"code_verifier": verifier,
"client_id": clientId
}
}).catch(err => console.error(err));
I've tried passing the params in the body of the post request and as url params and both produce the same results. As you can see, I'm clearly providing a grant_type and I'm using the value that the guide said to use.
I've tried every method I was able to find on the internet, nothing seemed to be working, but after a few hours, this succeeded:
const headers = {
Authorization:
'Basic ' +
new Buffer(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64'),
}
const { data } = await axios.post(
'https://accounts.spotify.com/api/token',
'grant_type=client_credentials',
headers: { headers },
)
this.token = data.access_token
After this, you can simply use any endpoint as seen in the Spotify API examples.
Use querystring npm package to parse the data since we're using application/x-www-form-urlencoded in the header
And change the grant_type to grant_type: "client_credentials"
var querystring = require('querystring');
const headers = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
};
let data = {
grant_type: "client_credentials",
code: data.code,
redirectUri: "http://localhost:8000/callback",
client_id: your_client_id,
client_secret: your_client_secret,
};
we use query.stringify() for the data because the content type is application/x-www-form-urlencoded also don't use params since its a post request
axios
.post(
"https://accounts.spotify.com/api/token",
querystring.stringify(data),
headers
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
This works for me:
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
'Basic ' +
Buffer.from(this.clientId + ':' + this.clientSecret).toString('base64'),
};
this.http.post(
'https://accounts.spotify.com/api/token',
'grant_type=client_credentials',
{ headers },
).subscribe(data => {
console.log(data);
});
I have the same issue, and it's resolved with stringfying request body data
const requestAccessToken = ({
code,
grantType = "authorization_code",
redirectUri = `${APP_BASE_URL}/callback`,
}) => {
const data = qs.stringify({ //query-string library
code,
grant_type: "client_credentials",
redirect_uri: redirectUri,
});
return axios.post(
[SPOTIFY_ACCOUNTS_BASE_URL, SPOTIFY_ACCOUNTS_TOKEN_URI].join(""),
data,
{
headers: {
Authorization: `Basic ${Buffer.from(
`${SPOTIFY_CLIENT_ID}:${SPOTIFY_CLIENT_SECRET}`,
).toString("base64")}`,
"Content-Type": "application/x-www-form-urlencoded",
},
},
);
};
Have you traced the message and verified that the request body is definitely as expected? Your OAuth fields look totally correct so I suspect this could just be an axios syntax issue.
I could be wrong but should the 'params' field be called 'data' instead, as in this class of mine.

How to post a data using Plain Javascript fetch on Laravel?

I made this method on my javascript to post data into my database:
if(document.getElementById('approve_leave_request')){
document.getElementById('approve_leave_request').addEventListener('click', ()=>{
const urlReq = window.location.origin+"/leave/customize";
const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
const leave = {
status: 'Approved',
};
const request = new Request(urlReq, {
method: 'POST',
body: JSON.stringify(leave),
headers: new Headers({
'Content-Type': 'application/json',
"X-CSRF-TOKEN": token
})
});
fetch(request).then(res => res.json()).then(res => console.log(res));
})
}
and this is my controller function:
public function customize_update(Request $request){
return response()->json(['message'=>'Called successfully.']);
}
and on my api:
Route::post('leave/customize', 'LeaveController#customize_update')->name('api.leave.customize');
but during execution i am getting this error:
POST http://127.0.0.1:8000/leave/customize 405 (Method Not Allowed)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Request-Promise throws "no auth mechanism defined" using async/await

I was just trying out async/await with request-promise and ran into this error:
RequestError: Error: no auth mechanism defined
at new RequestError (node_modules/request-promise-core/lib/errors.js:14:15)
at Request.plumbing.callback (node_modules/request-promise-core/lib/plumbing.js:87:29)
at Request.RP$callback [as _callback] (node_modules/request-promise-core/lib/plumbing.js:46:31)
at self.callback (node_modules/request/request.js:188:22)
at Auth.onRequest (node_modules/request/lib/auth.js:133:18)
at Request.auth (node_modules/request/request.js:1360:14)
at Context.<anonymous> (test/routes.js:37:41)
From previous event:
at Request.plumbing.init (node_modules/request-promise-core/lib/plumbing.js:36:28)
at Request.RP$initInterceptor [as init] (node_modules/request-promise-core/configure/request2.js:41:27)
at new Request (node_modules/request/request.js:130:8)
at request (node_modules/request/index.js:54:10)
at Context.<anonymous> (test/routes.js:37:24)
It is an API endpoint that I built recently that's supposed to create a new user in MongoDB. It uses Basic Auth provided by Passport strategy, and I've tested with Postman that it works. I'm not exactly sure why this error is being thrown.
My request code (using Mocha):
it("creates a new user", async () => {
const options = {
method: "POST",
uri: `http://localhost:${process.env.PORT}/api/users`,
headers: {
"User-Agent": "Request-Promise",
"Content-Type": "application/json"
},
body: {
email: "test#domain.com",
password: "password",
firstName: "John",
lastName: "Smith"
},
json: true
};
const resp = await request(options).auth(APP_ID, SIGNATURE, false);
expect(resp).to.be.an("object");
});
Edit: I should probably also add that I'm using node 8.2.1 and npm 5.3.0.
Solved for me by changing from:
auth: { Bearer: token }
to:
auth: { bearer: token }
Note the case difference on 'bearer'.
This is usually caused by not providing suitable credentials. The code raising the error can be found here. Have you verified that APP_ID and SIGNATURE are not undefined in your test?
This solution works for me. I have needed to put the token inside the headers :
var rp = require('request-promise');
var uri = 'uri_for_my_post_request';
var token = 'access_token';
var body = {
title: 'My Title',
content : 'My content'
};
var sendPost = async(my_uri,my_token,my_body)=>{
var options = {
method: 'POST',
headers:{
Authorization: ' Bearer ' + my_token
},
uri: my_uri,
body: my_body,
json: true
};
const response = await rp(options);
console.log(response);
}
sendPost(uri,token,body);

Categories