Citi Bank Open API Authorization - javascript

I am trying to use the Citi Bank Open API in my React Native mobile app. I was able to call the API to let user sign in with their Citi Bank account and get the client authorization code. However, when I was trying to call another API for validating the code I got, it returned a weird error without any description.
I suspect problems may be caused by:
my app is still in development stage
I didn't do the calling on the redirect uri, but the domain is definitely the same
The API is supposed to return an access token for further interaction, but all I got is the error. I wanna know what might be the possible mistakes.
This is my first time trying to use an open API inside my app. Any suggestion will be much appreciated.
Official docs from Citi (may need to register an account):
https://sandbox.developerhub.citi.com/api/hong-kong/retail-bank/identity-security/authorize/documentation
Calling the API:
fetch(
"https://sandbox.apihub.citi.com/gcb/api/authCode/oauth2/token/hk/gcb",
{
method: "POST",
body: new URLSearchParams({
grant_type: "authorization_code",
code: auth_code,//got from the response of GET /authCode/oauth2/authorize
redirect_uri: "http://localhost:19000/redirect",
}),
headers: new Headers({
"Cross-Domain": true,
Accept: "application/json",
Authorization:
"Basic " + btoa(CITI_CLIENT_ID + ":" + CITI_CLIENT_SEC),
"Content-Type": "application/x-www-form-urlencoded",
}),
}
)
.then((data) => {
console.log(data);
data.json();
})
.then((result) => {
console.log(result);//undefined
});
Response:
Response {
"_bodyBlob": Blob {
"_data": Object {
"__collector": null,
"blobId": "f09ce99b-1a3b-4251-9a73-5a4a809a6296",
"offset": 0,
"size": 88,
},
},
"_bodyInit": Blob {
"_data": Object {
"__collector": null,
"blobId": "f09ce99b-1a3b-4251-9a73-5a4a809a6296",
"offset": 0,
"size": 88,
},
},
"bodyUsed": false,
"headers": Headers {
"map": Object {
"access-control-allow-credentials": "true",
"access-control-allow-headers": "",
"access-control-allow-methods": "",
"access-control-allow-origin": "",
"access-control-expose-headers": "",
"connection": "close",
"content-length": "88",
"content-type": "application/json",
"date": "Thu, 24 Mar 2022 06:37:39 GMT",
"set-cookie": "CITI_SITE=gtdc; expires=Thu, 24-Mar-2022 06:57:39 GMT; path=/; domain=sandbox.apihub.citi.com; secure; HttpOnly",
"x-akamai-citisite": "GTDC",
"x-backside-transport": "FAIL FAIL,FAIL FAIL",
"x-global-transaction-id": "6e68aa42623c11b387504e5d",
},
},
"ok": false,
"status": 400,
"statusText": "",
"type": "default",
"url": "https://sandbox.apihub.citi.com/gcb/api/authCode/oauth2/token/hk/gcb",
}

Related

Wait for specific response in XHR polling with Cypress

I have a cypress spec with which I want to test a function on my site which polls a third party API until it receives a correct answer and then shows more information for the user to continue with the function.
I start my spec with
cy.server();
cy.route('GET', '**/that-other-api/**').as('otherApi');
I know that this part works. The route is listed in the top of the Cypress test GUI, and my otherApi alias is attached to the XHR requests when they are listed in the command list when running.
When the user (or my test) clicks a button the site will start polling that endpoint. When I receive a status: success in the response, the user (or my test) is provided with a filled dropdown of options and can continue.
How can I get Cypress to wait until I get that specific response from the XHR request (or reaches a cypress timeout) and then continue onwards?
The Network request documentation doesn't explain if this is possible or not. I have tried
cy.wait('#billectaAccounts').should('have.property', 'response.body.status', 'success');
and just to see if stuff works
cy.wait('#billectaAccounts').should('have.property', 'status', 201);
which both throw an error:
InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'json').
Logging the response with
cy.wait('#billectaAccounts').then(console.log);
logs the response and shows that my status variable is there, but is pending since it's only on the first request.
{
"xhr": {
"method": "GET",
"url": "https://myapi/longToken",
"id": "xhr193"
},
"id": "xhr193",
"url": "https://myapi/longToken",
"method": "GET",
"status": 200,
"statusMessage": "200 (OK)",
"request": {
"headers": {
"Accept": "application/json, text/plain, */*"
},
"body": null
},
"response": {
"headers": {
"cache-control": "max-age=0, private, must-revalidate",
"connection": "close",
"content-type": "application/json; charset=utf-8",
"date": "Tue, 24 Mar 2020 08:32:09 GMT",
"etag": "W/\"f0d6999f3be78c3dc8eab419745ec489\"",
"referrer-policy": "strict-origin-when-cross-origin",
"server": "Cowboy",
"vary": "Origin",
"via": "1.1 vegur",
"x-content-type-options": "nosniff",
"x-download-options": "noopen",
"x-frame-options": "SAMEORIGIN",
"x-permitted-cross-domain-policies": "none",
"x-request-id": "id",
"x-runtime": "0.006788",
"x-xss-protection": "1; mode=block"
},
"body": {
"id": 721,
"public_id": "longTokenId",
"bank": "bank-id",
"ssn": "ssn-number",
"status": "pending",
"created_at": "2020-03-24T09:32:05.362+01:00",
"updated_at": "2020-03-24T09:32:06.028+01:00",
"account_numbers": [],
"token": "pollingToken"
}
},
"duration": 230
}
I would prefer to not stub the response, It's nice to have the end to end test to that API.
Any help appreciated!

Different response from Spotify API when calling endpoints from Javascript vs REST client

I'm working on implementing some Spotify calls into a project using the Spotify API and the first thing I have to do is authenticate. I tested out the Spotify API endpoint by using Restlet (a REST API client) and my call is successful with the response of:
{ "access_token":
"BQC2PbOsWsnkfzcMUMW5YeJh9VGgE7uSQ-ubpO5kekyn3IIq0yVqoIW6Rx-5sQLJyH8R8wik6PzcFfzFDCU",
"token_type": "Bearer", "expires_in": 3600, "scope": "" }
I then implemented the POST call in my React app using javascript and it worked!
async function getSpAccessToken(component) {
const [initSpotResponse] = await Promise.all([
axios.post("https://accounts.spotify.com/api/token",
querystring.stringify({
grant_type: 'client_credentials'
}),
{
headers: {
'Authorization': `Basic ${encodedString}`,
'Content-type': 'application/x-www-form-urlencoded'
}
}
).catch((error) => {
console.log("getSpAccessToken ERROR = " + JSON.stringify(error))
})
]);
const spAccessToken = await initSpotResponse.data.access_token
}
But eventually when the token expires, my calls to Spotify respond with a "access_token expired" message, as expected. I go back and re-authenticate using the same getSpAccessToken() function but I get this as a response:
{
"data": "",
"status": 200,
"statusText": "OK",
"headers": {},
"config": {
"transformRequest": {},
"transformResponse": {},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic ZmY1NmFiZTc3OTJmNDI2ZWE0MWE3NzFkNzA3ZDY2OTaA6YjJjY2EyZGVkZDM5NDliMGE2YzVlMTU4MjQ0NmM5YzU="
},
"method": "post",
"url": "https://accounts.spotify.com/api/token",
"data": "grant_type=client_credentials"
},
"request": {}
}
The response is confusing because a) the status code is OK and b) because the data field is empty (this is where the access token resides). I then try to use my REST client, Restlet, to try the same call again and I get an access_token in my response! Then I go back and refresh my page and my getSpAccessToken() function gets called and this time it returns a data object:
{
"data": {
"access_token": "BQCuvTWeJlixkOsuAhKPClKWaXTaSPiuycNY6Z2EKKQLqsDyGyXdDcn4RR4tVq6--1HHJ_l1ViDlCi_mN_bk",
"token_type": "Bearer",
"expires_in": 3600,
"scope": ""
},
"status": 200,
"statusText": "OK",
"headers": {
"content-type": "application/json"
},
"config": {
"transformRequest": {},
"transformResponse": {},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic ZmY1NmFiZTc3OTJmNDI2ZWE0MWE3NzFkNzA3ZDY2OaTA6YjJjY2EyZGVkZDM5NDliMGE2YzVlMTU4MjQ0NmM5YzU="
},
"method": "post",
"url": "https://accounts.spotify.com/api/token",
"data": "grant_type=client_credentials"
},
"request": {}
}
My question: Why is it that when I need to refresh my token, my javascript getSpAccessToken() call returns a response with an empty data field until after I use my REST client to make that same call?

how do I grab data from an API that returns CSV file

I am working with Pluralsight API and their API responds CSV files as results, which I would like to grab this data from response and print out.
this is the URL of the Pluralsight API:
https://app.pluralsight.com/plans/api/reports/docs
and this is the code I am trying to do:
request
.get('https://api.pluralsight.com/api-v0.9/users?planId=x&token=y')
.on('response', function (response) {
res.json(response);
})
The response does not show any data except for the data as below:
{
"statusCode": 200,
"headers": {
"cache-control": "private",
"content-disposition": "attachment; filename=Users.csv",
"content-type": "text/csv",
"date": "Fri, 27 May 2016 03:42:06 GMT",
"ps-build": "2016.5.1849.0",
"ps-node": "0Q5JR",
"ps-responsetime": "00:00:00.1406230",
"content-length": "11391",
"connection": "Close"
},
"request": {
"uri": {
"protocol": "https:",
"slashes": true,
"auth": null,
"host": "api.pluralsight.com",
"port": 443,
"hostname": "api.pluralsight.com",
"hash": null,
"search": "?planId=x&token=y",
"query": "planId=x&token=y",
"pathname": "/api-v0.9/users",
"path": "/api-v0.9/users?planId=x&token=y",
"href": "https://api.pluralsight.com/api-v0.9/users?planId=x&token=y",
},
"method": "GET",
"headers": {}
}
}
Is there anyway that I get get the file from attachment and extract it?
Thanks
Request body is accessible through data and end events.
var body = [];
request
.get('https://api.pluralsight.com/api-v0.9/users?planId=x&token=y')
.on('data', function (chunk) {
body.push(chunk);
})
.on('end', function () {
body = body.join('');
// body now contains csv contents as a string
});

AJAX POST , having problems with "data" field

I am using auto generated the ajax with Postman 3, so you can tell if it's the correct way to do it, but this isn't my main question. Now, when I type the "data" field like this, it works
var settings = {
"async": true,
"crossDomain": true,
"url": "https://baas.kinvey.com/appdata/kid_B1BHxEN7/people/",
"method": "POST",
"headers": {
"authorization": "Basic Z2VzaGE6MTIzNA==",
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "8de908df-f970-524c-eb8b-d2f7f621a3ac"
},
"processData": false,
"data": "{\"name\":\"Peter\",\"id\":11}"
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Now my question is, how do I put custom parameters in the "data" field.
I want something like this
var arr = [{"name": "Peter", "id": 12}, {"name": "Demeter", "id": 15}];
var settings = {
"async": true,
"crossDomain": true,
"url": "https://baas.kinvey.com/appdata/kid_B1BHxEN7/people/",
"method": "POST",
"headers": {
"authorization": "Basic Z2VzaGE6MTIzNA==",
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "e37d3063-406d-02c3-803f-0f32666b9d70"
},
"processData": false,
data: {"name": arr[0].name, "id": arr[0].id}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
When i send this POST request it gives me back 400(Bad request)
jQuery does not format your request as JSON but only as data url. You have to do this yourself:
data: JSON.stringify({"name": arr[0].name, "id": arr[0].id})
You need to convert the string to JSON format using stringify. Here is link to explanation:
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Problems using api auth with Google Calendar JS API

I'm working on a small website that can do stuff with the Google Calendar API. I've posted it over here: http://evansiroky.com/temp-gcal-question/tests/ Whenever I try to authorize, it doesn't seem to matter what clientId I use, it always says it is authorized. Also, it doesn't seem to matter if immediate is set to true or false. Here is the authorization code:
gapi.auth.authorize({
client_id: clientId,
scope: ['https://www.googleapis.com/auth/calendar'],
immediate: immediate
}, function(authResult) {
if(authResult && !authResult.error) {
isAuthorized = true;
} else {
isAuthorized = false;
}
if(callback) {
var out = isAuthorized ? null : authResult;
callback(out);
}
});
However, once I try to list events of a calendar, I get a dailyLimitExceededUnreg error. Here is the code for listing events:
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list(_.extend({
calendarId: 'primary',
orderBy: 'starttime',
singleEvents: true,
showDeleted: true,
}, options.data));
request.then(function(resp) {
options.success(resp);
}, function(reason) {
options.failure(reason);
});
});
And here is the error that is returned:
{
"result": {
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "dailyLimitExceededUnreg",
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"extendedHelp": "https://code.google.com/apis/console"
}
],
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
},
"body": "{\n \"error\": {\n \"errors\": [\n {\n \"domain\": \"usageLimits\",\n \"reason\": \"dailyLimitExceededUnreg\",\n \"message\": \"Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.\",\n \"extendedHelp\": \"https://code.google.com/apis/console\"\n }\n ],\n \"code\": 403,\n \"message\": \"Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.\"\n }\n}\n",
"headers": {
"date": "Fri, 02 Oct 2015 19:08:41 GMT",
"content-encoding": "gzip",
"server": "GSE",
"vary": "Origin, X-Origin",
"content-type": "application/json; charset=UTF-8",
"cache-control": "private, max-age=0",
"content-length": "215",
"expires": "Fri, 02 Oct 2015 19:08:41 GMT"
},
"status": 403,
"statusText": "OK"
}
What am I doing wrong?

Categories

Resources