I'm trying to create a payment token for the payment gateway (Paymob Accept). When I check my browser console I get a loop POST error 401. I've attached two screenshots.
My code is:
const API = 'APK_KEY'
async function firstStep() {
let data = {
"api_key": API
}
let request = fetch('https://accept.paymob.com/api/auth/tokens', {
method: 'post',
headers: {'content-type' : 'application/json'},
body: JSON.stringify(data)
})
let response = (await request).json()
let token = (await response).token
secondStep(token)
}
async function secondStep(token) {
let data = {
"auth_token": token,
"delivery_needed": "false",
"amount_cents": "100",
"currency": "EGP",
"items": [],
}
let request = await fetch('https://accept.paymob.com/api/ecommerce/orders', {
method : 'POST',
headers: {'content-type' : 'application/json'},
body: JSON.stringify(data)
})
let response = request.json()
let id = (await response).id
secondStep()
}
async function thirdStep(token, id) {
let data = {
"auth_token": token,
"amount_cents": "100",
"expiration": 3600,
"order_id": id,
"billing_data": {
"apartment": "803",
"email": "claudette09#exa.com",
"floor": "42",
"first_name": "Clifford",
"street": "Ethan Land",
"building": "8028",
"phone_number": "+86(8)9135210487",
"shipping_method": "PKG",
"postal_code": "01898",
"city": "Jaskolskiburgh",
"country": "CR",
"last_name": "Nicolas",
"state": "Utah"
},
"currency": "EGP",
"integration_id": 13034
}
let request = fetch('https://accept.paymob.com/api/acceptance/payment_keys', {
method: 'post',
headers: {'content-type' : 'application/json'},
body: JSON.stringify(data)
})
let response = (await request).json()
let finalToken = (await response).token
cardPayment(finalToken)
}
async function cardPayment() {
let iframeURL = `https://accept.paymob.com/api/acceptance/iframes/18922?payment_token=${finalToken}`
console.log(iframeURL)
}
firstStep()
I tried each step in the console, stepOne and stepTwo work fine. After I added stepThree I get the error.
What am I missing?
Thanks in advance for your support!
Like said in the comment section, the secondStep is calling itself recursively, also without any arguments. This will cause an infinite loop. We fix it by calling thirdStep.
Also in the cardPayment function, you are using finalToken, which is not defined in the function. We fix it that by making it the argument.
const API = 'APK_KEY'
async function firstStep() {
let data = {
"api_key": API
}
let request = fetch('https://accept.paymob.com/api/auth/tokens', {
method: 'post',
headers: {'content-type' : 'application/json'},
body: JSON.stringify(data)
})
let response = (await request).json()
let token = (await response).token
secondStep(token)
}
async function secondStep(token) {
let data = {
"auth_token": token,
"delivery_needed": "false",
"amount_cents": "100",
"currency": "EGP",
"items": [],
}
let request = await fetch('https://accept.paymob.com/api/ecommerce/orders', {
method : 'POST',
headers: {'content-type' : 'application/json'},
body: JSON.stringify(data)
})
let response = request.json()
let id = (await response).id
thirdStep(token, id)
}
async function thirdStep(token, id) {
let data = {
"auth_token": token,
"amount_cents": "100",
"expiration": 3600,
"order_id": id,
"billing_data": {
"apartment": "803",
"email": "claudette09#exa.com",
"floor": "42",
"first_name": "Clifford",
"street": "Ethan Land",
"building": "8028",
"phone_number": "+86(8)9135210487",
"shipping_method": "PKG",
"postal_code": "01898",
"city": "Jaskolskiburgh",
"country": "CR",
"last_name": "Nicolas",
"state": "Utah"
},
"currency": "EGP",
"integration_id": 13034
}
let request = fetch('https://accept.paymob.com/api/acceptance/payment_keys', {
method: 'post',
headers: {'content-type' : 'application/json'},
body: JSON.stringify(data)
})
let response = (await request).json()
let finalToken = (await response).token
cardPayment(finalToken)
}
async function cardPayment(finalToken) {
let iframeURL = `https://accept.paymob.com/api/acceptance/iframes/18922?payment_token=${finalToken}`
console.log(iframeURL)
}
firstStep()
Related
Assume that this is the changelog of a Jira issue
{
"expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
"id": "72194",
"self": "https://jira.instance.net/rest/api/2/issue/72194",
"key": "TII-627",
"changelog": {
"startAt": 0,
"maxResults": 1,
"total": 1,
"histories": [
{
"id": "12345",
"author": {
"self": "https://jira.instance.net/rest/api/2/user?accountId=xxxxxxxxxxx",
"accountId": "xxxxxxxxxxxx",
"emailAddress": "xxx#yy.com",
"avatarUrls": {},
"displayName": "John Doe",
"active": true,
"timeZone": "Anywhere",
"accountType": "atlassian"
},
"created": "2023-02-07T10:30:02.897+0530",
"items": [
{
"field": "status",
"fieldtype": "jira",
"fieldId": "status",
"from": "10000",
"fromString": "To Do",
"to": "5",
"toString": "Resolved"
}
]
}
]
},
"fields": {
"status": {
"self": "https://jira.instance.net/rest/api/2/status/5",
"description": "A resolution has been taken, and it is awaiting verification by reporter. From here issues are either reopened, or are closed.",
"iconUrl": "something",
"name": "Resolved",
"id": "5",
"statusCategory": {
"self": "https://jira.instance.net/rest/api/2/statuscategory/3",
"id": 3,
"key": "done",
"colorName": "green",
"name": "Done"
}
}
}
}
In this changelog you can see that the issue with "key": "TII-627" was first transition to done statuscategory aka Resolved status on "created": "2023-02-07T10:30:02.897+0530"
I want to get this first transition to done and print it in a table for all issues in the project like this
issue_key, first_resolved_at
for the eg. above it would look like this
TII-627, 2023-02-07T10:30:02.897+0530
I have tried using the following ruby script but I am getting the first resolved date empty please let me know what can I do
require 'jira-ruby'
# JIRA API credentials
jira_username = '<your-jira-username>'
jira_token = '<your-jira-api-token>'
jira_domain = '<your-jira-instance-domain>'
# initialize client
options = {
:username => jira_username,
:password => jira_token,
:site => "https://#{jira_domain}",
:context_path => '',
:auth_type => :basic
}
client = JIRA::Client.new(options)
# Define the issue key as a command line argument
issue_key = ARGV[0]
# Log the start time of the script
start_time = Time.now
puts "Start time: #{start_time}"
# Get the issue information
begin
issue = client.Issue.find(issue_key)
issue_status_category = issue.fields['status']['statusCategory']['name']
# If issue has already reached done status, retrieve the transitions
if issue_status_category == 'Done'
transitions = issue.transitions
first_resolved_at = nil
last_resolved_at = nil
# Retrieve the first and last resolved dates
transitions.each do |transition|
transition_status_category = transition['to']['statusCategory']['name']
if transition_status_category == 'Done'
transition_created_at = DateTime.parse(transition['created'])
if first_resolved_at.nil?
first_resolved_at = transition_created_at
end
last_resolved_at = transition_created_at
end
end
# Print the results
puts "Issue Key: #{issue.key}"
puts "First Resolved At: #{first_resolved_at}"
puts "Last Resolved At: #{last_resolved_at}"
else
puts "Issue has not yet reached Done status."
end
rescue Exception => e
# Log the error
puts "Error: #{e}"
end
# Log the end time of the script
end_time = Time.now
puts "End time: #{end_time}"
I am closing the question. I was able to figure out another way using JS
const axios = require("axios");
async function getFirstResolvedDate(jiraUsername, jiraToken, jiraDomain, issues) {
for (const issue of issues) {
let changelogs = [];
let url = jiraDomain + "/rest/api/2/issue/" + issue + "?expand=changelog";
let response = await axios({
method: "get",
url: url,
headers: {
"Authorization": "Basic " + Buffer.from(jiraUsername + ":" + jiraToken).toString("base64"),
"Content-Type": "application/json",
}
});
let data = response.data;
let changelog = data.changelog.histories;
if (!Array.isArray(changelog)) {
changelog = [changelog];
}
for (const history of changelog) {
let items = history.items;
for (const item of items) {
if (item.field === "status" && (item.toString === "Resolved" || item.toString === "Invalid")) {
let firstResolvedAt = history.created;
changelogs.push({
issue_key: issue,
first_resolved_at: firstResolvedAt
});
break;
}
}
}
let earliestDate = new Date(Math.min.apply(null, changelogs.map(function(c) {
return new Date(c.first_resolved_at);
})));
let formattedDate = earliestDate.toISOString();
url = jiraDomain + "/rest/api/2/issue/" + issue;
let body = {
fields: {
customfield_xxx: formattedDate
}
};
response = await axios({
method: "put",
url: url,
headers: {
"Authorization": "Basic " + Buffer.from(jiraUsername + ":" + jiraToken).toString("base64"),
"Content-Type": "application/json",
},
data: body
});
if (response.status === 200 || response.status === 204) {
console.log("Successfully updated first resolved date for issue " + issue);
} else {
console.error(response);
}
}
}
const jiraUsername = 'xxx';
const jiraToken = "xxx";
const jiraDomain = "https://xxx";
const issues = ['xxx-1'];
getFirstResolvedDate(jiraUsername, jiraToken, jiraDomain, issues)
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});
I'm having hard time on thinking how will I populate hooks with API response(json)
see below codes
cosnt [loginResponse, setloginResponse] = useState({
Token: '',
UserID: '', //from user-id
UserName: '', //from user-userName
firstName: '', //from user-firstName
rcCode: '' //from attributes-rcCode
})
const login = async () => {
await axios.get('/API')
.then(response => {
console.log('response.data', response.data.resp)
});
}
here's the result of console.log(response.data.resp)
{
"data": {
"token": "abcd",
"user": {
"id": "123456",
"userName": "uname",
"firstName": "FNAME",
"lastName": "MNAME",
"email": "email#email.com",
"attributes": {
"favorites": ["FAV"],
"rcCode": ["123"]
},
"requiredActions": [],
"roles": ["ROLE"]
},
"modulePermissions": []
}
}
for console.log(response.data):
"resp": {
"data": {
"token": "abcd",
"user": {
"id": "123456",
"userName": "uname",
"firstName": "FNAME",
"lastName": "MNAME",
"email": "email#email.com",
"attributes": {
"favorites": ["FAV"],
"rcCode": ["123"]
},
"requiredActions": [],
"roles": ["ROLE"]
},
"modulePermissions": []
}
},
"success": true
I want to populate my hooks with those datas for me to utilize it on my page.
I got undefined if I tried to console.log(response.data.resp.data)
On console.log(response), I got:
Thank you.
Don't use async/await and .then() together. Use either of those.
const login = async () => {
const response = await axios.get('/API');
const parsedData = JSON.parse(response.data.resp);
const userData = parsedData.data;
setLoginResponse({
Token: userData.token,
UserID: userData.user.id,
UserName: userData.user.userName,
firstName: userData.user.firstName,
rcCode: userData.user.attributes.rcCode
});
}
In the .then
setLoginResponse({...loginResponse, Token: response.data.resp.data.token, UserId: response.data.resp.data.user.id, ...}
You can destructure your response object first and store values in variables to make the setLoginResponse more easy to read.
https://reactjs.org/docs/hooks-state.html
my script connects to a graphql API by fetch and inserts the JSON return in the postgresql database, however when I insert the primaryLabels parameter into the query, it returns that my JSON is broken by a token>.
If I remove this parameter, everything goes perfectly, any solution?
I tried to turn the query into a string, but the code still fails
Code
let queryAPI = {"query": `{squads {name cards(includedOnKanban: true, closed: false, archived: false, cancelled: false, updatedSince: \"2020-01-01T00:00:00-0300\") { identifier title description status priority assignees { fullname email } secondaryLabel primaryLabels swimlane workstate}}}`};
(async () => {
try {
const rawResponse = await fetch('https://www.bluesight.io/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Bluesight-API-Token': 'token-here'
},
body: JSON.stringify(queryAPI)
});
const content = await rawResponse.json();
OUTPUT
at async C:\Users\Documents\Autoportal\Bluesight\index.js:35:25 {
name: 'FetchError',
message: 'invalid json response body at https://www.bluesight.io/graphql reason: Unexpected token < in JSON at position 0',
type: 'invalid-json'
JSON result example:
{
"data": {
"squads": [
{
"name": "SUPPORT IT",
"cards": [
{
"identifier": "06x38y",
"title": "ALL - Validate data",
"description": "review database.",
"status": null,
"priority": "medium",
"assignees": [
{
"fullname": "Carlos",
"email": "carlos#br.it.com",
}
],
"secondaryLabel": null,
"primaryLabels": [
"CLIENT"
]
}
]
}
]
} }
CONTENT
{
squads: [ { name: 'SUPPORT IT', cards: [Array] } ]
}
this is my json response
{
"sessid": "some_value",
"session_name": "some_vvalue",
"token": "some_vvalue",
"user": {
"uid": "12125",
"name": "some_vvalue",
"mail": "some_vvalue",
"theme": "",
"signature": "",
"signature_format": "filtered_html",
"created": "1486476553",
"access": "1489577945",
"login": 1489585116,
"status": "1",
"timezone": "Asia/Kolkata",
"language": "",
"picture": "0",
"data": false,
"roles": {
"2": "authenticated user"
},
"rdf_mapping": {
"rdftype": ["sioc:UserAccount"],
"name": {
"predicates": ["foaf:name"]
},
"homepage": {
"predicates": ["foaf:page"],
"type": "rel"
}
}
}
}
i just want to get first three values that is session_name,session_id and token, And i am getting this value during post request,here is my code for parsing.
async onPressLogin() {
try {
loaderHandler.showLoader("Please wait!!!");
let response = await fetch(
'http://some_url/api/user/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': this.state.token,
},
body: JSON.stringify({
username: this.state.name,
password: this.state.password,
})
});
let responseText = await response.text();
let responseJson = await response.json();
if (response.status >= 200 && response.status < 300){
await AsyncStorage.setItem(SESSION_TOKEN, responseJson.token);
await AsyncStorage.setItem(SESSION_NAME,responseJson.session_name);
await AsyncStorage.setItem(SESSION_ID,responseJson.sessid);
Alert.alert('Store Token', 'Session Token'+responseJson.token)
/// Alert.alert('Server response', responseJson)
loaderHandler.hideLoader();
Actions.Documents();
}
else {
loaderHandler.hideLoader();
let error = responseText;
Alert.alert('Login', error)
}
} catch(errors) {
loaderHandler.hideLoader();
Alert.alert('Login_server', errors)
loaderHandler.hideLoader();
}
}
I am trying to store these three values in async storage for further use. Please help me tried everything but could not solve the error. Let me know if you will need any other code. Thanks
This is the error which i am getting
TypeError: expected dynamic type'string',but had type'object'
I'm trying to return a list of flights from Google's QPX Express API, howver I'm stumped on a bad request response:
{ StatusCodeError: 400 - {"error":{"errors":[{"domain":"global","reason":"badRequest","message":"Invalid inputs: received empty request."}],"code":400,"message":"Invalid inputs: received empty request."}}
Is there something wrong with how I'm approaching the structure of the request? I'm using the request-promise library
const options = {
method: 'POST',
uri: 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXX',
qs: {
"request": {
"passengers": {
"adultCount": 1 },
"slice": [{"origin": "BOS",
"destination": "LAX",
"date": "2017-03-01"
}]
}
},
json: true
}
request(options)
.then(function (response) {
console.log(response)
})
.catch(function (err) {
console.log(err)
})
I have solved the issue. The request needed to include the data in the body key with the content-type set to JSON.
This now returns data from the API as expected.
const options = {
method: 'POST',
uri: 'https://www.googleapis.com/qpxExpress/v1/trips/search?&key=XXXXXXXXXXXXXXXXXXXX',
body: {
"request": {
"passengers": {
"adultCount": "1"
},
"slice": [
{
"origin": "SFO",
"destination": "LAX",
"date": "2017-06-19"
}
],
"solutions": "1"
}
},
json: true
}
request(options)
.then(function (response) {
console.log(response.trips.tripOption[0].saleTotal)
})
.catch(function (err) {
console.log(err)
})
Check it:
const options = {
method: 'POST',
uri: 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXX',
qs: {
"request": {
"passengers": {
"adultCount": 1 },
"slice": [{"origin": "BOS",
"destination": "LAX",
"date": "2017-03-01"
}]
}
},
json: true
};
request(options)
.then(function (response) {
console.log(response);
})
.catch(function (err) {
console.log(err);
});
You forgot to end the uri string. Also please don't forget the semicolons.
Edit:
Try:
request({
url: (your url here),
method: "POST",
json: requestData
},
where requestData will be your qs.