How to use the Zoho Desk Invoke API (Proxy) to call the Zoho Desk Push-Data to Desk (aka Import) endpoint? - axios

I am trying to use the Zoho Desk Invoke API (Proxy) to call the Zoho Desk Push-Data to Desk (aka Import) endpoint.
This is what my code looks like:
// Build the payload
const invokeApiRequestPayload = {
"securityContext":"edbsnc50b85a3cd964126073f50499ae29a3d6ed3c31123e535e901cdda1b2a312dc0a66c638e2beb2724fffc355faebabf1acd65c3883227c2d329d0c9f62cbbdf26ba4553375b5b11cab90c57590c6b48a3",
"requestURL":"https://desk.zoho.com.au/api/v1/channels/{{installationId}}/import",
"headers":{
"Content-Type":"application/json"
},
"postBody":{
"data":{
"tickets":[
{
"actor":{
"email":"test#gmail.com",
"name":"Tom Billy",
"extId":"NjPk2E6J83g41uDKsD6DznLzz323"
},
"subject":"testing new ticket",
"createdTime":"2022-07-24T01:13:44.419Z",
"status":"Open",
"extId":"YCdHTnu93pQbyNoyZzId"
}
],
"threads":[
{
"contentType":"text/html",
"createdTime":"2022-07-24T01:13:44.419Z",
"extId":"YGrfU6quGoDESjX5HEZM",
"extParentId":"YCdHTnu93pQbyNoyZzId",
"actor":{
"extId":"NjPk2E6J83g41uDKsD6DznLzz323",
"name":"Tom Billy",
"email":"test#gmail.com"
},
"canReply":true,
"content":"testing one two three<br>"
}
]
}
},
"connectionLinkName":"zohodesk",
"requestType":"POST",
"queryParams":{
"orgId":"7002257443"
}
};
// Generate the Hmac
const stringToHash = 'requestURL=https://desk.zoho.com.au/api/v1/channels/{{installationId}}/import&requestType=POST&queryParams={"orgId":"7002257443"}&postBody={"data":{"tickets":[{"extId":"YCdHTnu93pQbyNoyZzId","status":"Open","subject":"testing new ticket","createdTime":"2022-07-24T01:13:44.419Z","actor":{"extId":"NjPk2E6J83g41uDKsD6DznLzz323","name":"Tom Billy","email":"test#gmail.com"}}],"threads":[{"extId":"YGrfU6quGoDESjX5HEZM","extParentId":"YCdHTnu93pQbyNoyZzId","actor":{"extId":"NjPk2E6J83g41uDKsD6DznLzz323","name":"Tom Billy","email":"test#gmail.com"},"content":"testing one two three<br>","createdTime":"2022-07-24T01:13:44.419Z","canReply":true,"contentType":"text/html"}]}}&headers={"Content-Type":"application/json"}&connectionLinkName=zohodesk';
const hmac = crypto
.createHmac('sha256', 'mysecret123')
.update(stringToHash)
.digest('hex');
// The hmac created from the above code is '2aa21d41882223e2e23ad7004cfdc5a0317db5192fdff84431f0515d4f4e004b'
// Make the Invoke API request using Axios
const axiosOptions = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
hash: hmac,
},
params: {
orgId: '7002257443',
},
};
return await axios
.post(
'https://desk.zoho.com.au/api/v1/invoke',
invokeApiRequestPayload,
axiosOptions
)
.catch((error) => {
functions.logger.error(error);
throw new functions.https.HttpsError('unknown', error.message, error);
});
But I always get back Error 422 UNPROCESSABLE_ENTITY:
{
"errorCode":"UNPROCESSABLE_ENTITY",
"message":"`Extra query parameter '{\"securityContext\":\"edbsnc50b85a3cd964126073f50499ae29a3d6ed3c31123e535e901cdda1b2a312dc0a66c638e2beb2724fffc355faebabf1acd65c3883227c2d329d0c9f62cbbdf26ba4553375b5b11cab90c57590c6b48a3\",\"requestURL\":\"https://desk.zoho.com.au/api/v1/channels/{{installationId}}/import\",\"requestType\":\"POST\",\"postBody\":{\"data\":{\"tickets\":[{\"extId\":\"YCdHTnu93pQbyNoyZzId\",\"status\":\"Open\",\"subject\":\"testing new ticket\",\"createdTime\":\"2022-07-24T01:13:44.419Z\",\"actor\":{\"extId\":\"NjPk2E6J83g41uDKsD6DznLzz323\",\"name\":\"Tom Billy\",\"email\":\"test#gmail.com\"}}],\"threads\":[{\"extId\":\"YGrfU6quGoDESjX5HEZM\",\"extParentId\":\"YCdHTnu93pQbyNoyZzId\",\"actor\":{\"extId\":\"NjPk2E6J83g41uDKsD6DznLzz323\",\"name\":\"Tom Billy\",\"email\":\"test#gmail.com\"},\"content\":\"testing one two three<br>\",\"createdTime\":\"2022-07-24T01:13:44.419Z\",\"canReply\":true,\"contentType\":\"text/html\"}]}},\"headers\":{\"Content-Type\":\"application/json\"},\"queryParams\":{\"orgId\":\"7002257443\"},\"connectionLinkName\":\"zohodesk\"}' is present in the input.`"
}
The Zoho Desk docs have this explanation for the UNPROCESSABLE_ENTITY error code:
This errorCode value appears if the input does not fulfil the
conditions necessary for successfully executing the API.
And looking at the returned error message details it seems to be complaining that I have an "Extra query parameter". That does not make sense to me, because I included it as the payload required by the Zoho Desk Invoke API (Proxy).
Can anyone see what I am doing wrong?

Related

How to tell auth0 im authenticated in req.rest file

So I want to make a post request to my nextJS backend and the route i am making the req to a protected route so in my Rest client file (req.rest) I need to tell auth0 im authenticated but i do not know how to do that.
req.rest
POST http://localhost:3000/api/video
Content-Type: application/json
Authorization: Bearer cookie
{
"title": "Video",
"description": "Video description"
}
api/video.js
import { withApiAuthRequired, getSession } from "#auth0/nextjs-auth0";
import Video from "../../database/models/Video";
export default withApiAuthRequired(async function handler(req, res) {
if (req.method === "POST") {
try {
const { user } = getSession(req, res);
const newVideo = new Video({
title: req.body.title,
description: req.body.description,
ownerId: user.sub,
});
await newVideo.save();
res.json(newVideo);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
});
I'm not sure I understand your question. Your API should determine if the user is authenticated by validating the bearer token value you are passing through the Authorization request header, you shouldn't need to pass additional data as separate parameters to authorize the API. If you do need additional data to determine if the user is authorized to consume the API, that should be included inside of the bearer token as a claim.
So I haven't really found a solution but I do have a workaround which is to just make new page on the frontend for requests and send the requests from there.

Axios error when sending api request to Discord

I'm trying to send an automated message to discord from my account token using the axios client, it worked on a different project of mine but it doesn't work on a brand new project for some reason. Here is the code so far:
const axios = require('axios').default;
async function Post() {
const URL = `https://discord.com/api/v9/channels/${process.env.CHANNEL}/messages`
const payload = { content: "This message has been sent using axios!" }
await axios.post(URL, payload, { headers: { 'authorization': process.env.TOKEN } })
}
Post();
This is the error I'm getting:
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
TypeError [ERR_HTTP_INVALID_HEADER_VALUE]: Invalid value "undefined" for header "authorization"
at ClientRequest.setHeader (node:_http_outgoing:579:3)
at new ClientRequest (node:_http_client:256:14)
at Object.request (node:https:353:10)
at RedirectableRequest._performRequest (/home/nonce/Documents/Repositories/test/node_modules/follow-redirects/index.js:279:24)
at new RedirectableRequest (/home/nonce/Documents/Repositories/test/node_modules/follow-redirects/index.js:61:8)
at Object.request (/home/nonce/Documents/Repositories/test/node_modules/follow-redirects/index.js:482:14)
at dispatchHttpRequest (/home/nonce/Documents/Repositories/test/node_modules/axios/lib/adapters/http.js:232:25)
at new Promise (<anonymous>)
at httpAdapter (/home/nonce/Documents/Repositories/test/node_modules/axios/lib/adapters/http.js:48:10)
at dispatchRequest (/home/nonce/Documents/Repositories/test/node_modules/axios/lib/core/dispatchRequest.js:58:10) {
code: 'ERR_HTTP_INVALID_HEADER_VALUE'
}
And for the record, I'm not trying to create a spammer or anything that breaks Discord's API rules.
Here are the versions I'm using, if it helps in any way:
node: v16.13.2
npm: v8.1.2
axios: v0.25.0
Found the error, I forgot to add the dotenv package all along.

GraphQL query to GitHub failing with HTTP 422 Unprocessable Entity

I am currently working on a simple GitHub GraphQL client in NodeJS.
Given that GitHub GraphQL API is accessible only with an access token, I set up an OAuth2 request to grab the access token and then tried to fire a simple GraphQL query.
OAuth2 flow gives me the token, but when I send the query, I get HTTP 422.
Here below simplified snippets from my own code:
Prepare the URL to display on UI side, to let user click it and perform login with GitHub
getGitHubAuthenticationURL(): string {
const searchParams = new URLSearchParams({
client_id,
state,
login,
scope,
});
return `https://github.com/login/oauth/authorize?${searchParams}`;
}
My ExpressJs server listening to GitHub OAuth2 responses
httpServer.get("/from-github/oauth-callback", async (req, res) => {
const {
query: { code, state },
} = req;
const accessToken = await requestGitHubAccessToken(code as string);
[...]
});
Requesting access token
async requestToken(code: string): Promise<string> {
const { data } = await axios.post(
"https://github.com/login/oauth/access_token",
{
client_id,
client_secret,
code
},
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
}
);
return data.access_token;
}
Firing simple graphql query
const data = await axios.post(
"https://graphql.github.com/graphql/proxy",
{ query: "{ viewer { login } }"},
{
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
}
);
Do you guys have any clue?
Perhaps I am doing something wrong with the OAuth2 flow? As in most of the examples I found on the web, a personal token is used for this purpose, generated on GitHub, but I would like to use OAuth2 instead.
Thanks in advance for any help, I really appreciate it!
EDIT
I changed the query from { query: "query { viewer { login } }"} to { query: "{ viewer { login } }"}, nonetheless, the issue is still present.
I finally found the solution:
Change the URL from https://graphql.github.com/graphql/proxy to https://api.github.com/graphql, see here
Add the following HTTP headers
"Content-Type": "application/json"
"Content-Length"
"User-Agent"
Hope this will help others out there.

Using Axios as an Alternative to request in nodejs

I am building a flutter application that requires oauth 1 authorization for one of the third party services I am using. Because flutter oauth 1 package is restricted I decided to use the oauth 1 package that npm provides. This is the code that is used to access the user generated access token from the site.
I previously used request to make a call to the api endpoint first, to access the token and secondly to use the token recieved to make another call to a different resource endpoint
How can I use axios to make the same request, emphasis on the fact that each request needs a hmac-sha1 signed signature in the header.
Thank you.
consumer: {
key: CONSUMER KEY,
secret: CONSUMER SECRET,
},
signature_method: 'HMAC-SHA1',
hash_function(base_string, key) {
return crypto
.createHmac('sha1', key)
.update(base_string)
.digest('base64')
},
})
const request_data = {
url: 'https://www.instapaper.com/api/1/oauth/access_token/',
method: 'POST',
data: { x_auth_username : USERNAME , x_auth_password : PASSWORD , x_auth_mode : 'client_auth' },
}
request(
{
url: request_data.url,
form: request_data.data,
method: request_data.method,
headers: oauth.toHeader(oauth.authorize(request_data)),
},
function(error, response, body) {
// Process your data here
console.log(error);
console.log(response);
console.log(body);
}
)
Finally found the answer for this link to the issue created on github
https://github.com/axios/axios/issues/2771

Angular7 Consume Mailchimp RESTFUL API

I'm trying to make HTTP POST request to consume Mailchimp API (From Angular7 code)
but i'm getting this response:
Access to XMLHttpRequest at 'https://us12.api.mailchimp.com/3.0/lists/ddddddd/members' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
From REST client i'm able to make insert in Mailchimp without having this CROS issue
export class MyService {
constructor(public httpRequestsService: HttpRequestsService) { }
private async getHttpHeader() {
const rheaders = new HttpHeaders({
'Content-Type': 'application/json' ,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Headers':'X-Requested-With',
'Authorization': 'apikey ' + MailchimpSettings.API_KEY
});
return { headers: rheaders };
}
public async AddNewMember(email: string, language = 'en', status = , mergeFields?: any) {
var url = MailchimpSettings.URL;
var body = {
"email_address": email,
"status": MailchimpSettings.SUBSCRIBED_STATUS,
"language": language
};
var httpOptions = await this.getHttpHeader();
var _body = JSON.stringify(body);
var result = await this.post(url, _body, httpOptions);
}
public async post(url: string, body: string | {} = {}, requestHeaders?: any): Promise<Response> {
return this.http.post(url, body, requestHeaders).toPromise()
.then((res: any) => {
return res;
})
.catch((err) => {
return this.handleErrorPromise(err);
});
}
}
Anyone who can help me with right HTTP headers (or any required change) to reproduce exactly REST client behavior and be able to make a successful POST.
Thanks for your help
Unfortunately, the answer is you can't. Mailchimp does not support CORS because that would require passing API credentials, and that is not secure.
The option is to make requests from another server like you mentioned from the REST client or make a custom signup form that will use more restricted API call.
Or use jsonp request for mailchimp form clients.
See this