My problem is exactly same as this one.
The fact is, it's answer didn't worked for me. It is still showing "wrong code".
{ message: 'Access denied: Invalid token, wrong code' }
headers are
headers: {
'Content-Type': 'application/json',
Authorization: 'Basic bW9oaXRrdW1hcnNpbmdoMTIzNDRAZ21haWwuY29tOjE1NDg3NjY3Njg='
}
Here is the code used
import axios from 'axios';
import base64 from 'base-64';
import utf8 from 'utf8';
import { totp } from 'otplib';
const reqJSON =
{
github_url: GITHUB_URL,
contact_email: EMAIL
}
const stringData = JSON.stringify(reqJSON);
const URL = API_URL;
const sharedSecret = reqJSON.contact_email + "SOME_STRING";
totp.options = { digits: 10, algorithm: "sha512", epoch: 0 }
const myTotp = totp.generate(sharedSecret);
const isValid = totp.check(myTotp, sharedSecret);
console.log("Token Info:", { myTotp, isValid });
const authStringUTF = reqJSON.contact_email + ":" + myTotp;
const bytes = utf8.encode(authStringUTF);
const encoded = base64.encode(bytes);
console.log('encoded ->', encoded);
const createReq = async () => {
try {
const config = {
headers: {
'Content-Type': 'application/json',
'Authorization': "Basic " + encoded
}
};
console.log("Making req", { URL, reqJSON, config });
const res = await axios.post(URL, stringData, config);
console.log(res.data);
}
catch (err) {
console.error(err.response.data);
}
};
createReq();
EDIT - Added current code for generating Basic HTTP RFC2617 Authentication Code
Thanks you so much!
Related
A post request with axios get http error 500.
This is the code:
async function getUserTokenByRefresh(refreshToken) {
const encodedStr = base64Encode(`${process.env.EBAY_SANDBOX_APPID}:${process.env.EBAY_SANDBOX_CERTID}`);
const auth = `Basic ${encodedStr}`;
const options = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: auth
}
};
const data = {
grant_type: "refresh_token",
refresh_token: refreshToken
};
const testing = true;
const url = testing
? "https://api.sandbox.ebay.com/identity/v1/oauth2/token"
: "https://api.ebay.com/identity/v1/oauth2/token";
try {
const response = await axios.post(
url,
data,
options
);
console.log(JSON.stringify(response));
}
catch (e) {
console.log(JSON.stringify(e));
}
}
This is the error message:
{
"message": "Request failed with status code 500",
"code": "ERR_BAD_RESPONSE",
"status": 500
}
This is the error message in json format.
I don't know what's wrong in the code.
Can you check it?
Data should be encoded.
async function getUserTokenByRefresh(refreshToken) {
const encodedStr = base64Encode(`${process.env.EBAY_SANDBOX_APPID}:${process.env.EBAY_SANDBOX_CERTID}`);
const auth = `Basic ${encodedStr}`;
const options = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: auth
}
};
const data = {
grant_type: "refresh_token",
refresh_token: refreshToken
};
const testing = true;
const url = testing
? "https://api.sandbox.ebay.com/identity/v1/oauth2/token"
: "https://api.ebay.com/identity/v1/oauth2/token";
try {
const response = await axios.post(
url,
//ENCODED DATA
new URLSearchParams(data),
options
);
console.log(JSON.stringify(response));
}
catch (e) {
console.log(JSON.stringify(e));
}
}
in Node.js, I am trying to send a POST request with Axios to Twilio and send an SMS message to my phone. But I am getting an 'error: Authentication Error - No credentials provided ? Here is the code:
const body = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Body: 'hi from vsc',
To: toNumber,
From: fromNumber,
};
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Authorization: `Basic ${accountSID}:${authToken}`,
};
exports.axios = () => axios.post(`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`, body, headers).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
I also tried to use the same parameters with POSTMAN and the POST request is successful. I also tried to encode my authorization username and password to Base 64, but with no success.
I wrote to Twilio customer help but haven`t received any replies yet.
Axios makes an auth option available that takes an object with username and password options. You can use this with the username set to your account SID and password set to your auth token.
The headers object should be sent as the headers parameter of a config object in the third parameter to axios.post. Like so:
const params = new URLSearchParams();
params.append('Body','Hello from vcs');
params.append('To',toNumber);
params.append('From',fromNumber);
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
};
exports.axios = () => axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`,
params,
{
headers,
auth: {
username: accountSID,
password: authToken
}
}
}).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
Headers is actually a field of config, try something like this:
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Authorization: `Basic ${accountSID}:${authToken}`,
}
}
axios.post(URL, data, config).then(...)
Or this (general example calling a Twilio endpoint)
const axios = require('axios');
const roomSID = 'RM1...';
const participantSID = 'PA8...';
const ACCOUNT_SID = process.env.ACCOUNT_SID;
const AUTH_TOKEN = process.env.AUTH_TOKEN;
const URL = "https://insights.twilio.com/v1/Video/Rooms/"+roomSID+"/Participants/"+participantSID;
axios({
method: 'get',
url: URL,
auth: {
username: ACCOUNT_SID,
password: AUTH_TOKEN
}
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
Working code:
const params = new URLSearchParams();
params.append('Body','Hello from vcs');
params.append('To',toNumber);
params.append('From',fromNumber);
exports.axios = () => axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`,
params,
{
auth: {
username: accountSID,
password: authToken,
},
},
).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
The previous solutions did not work for me. I encountered either the Can't find variable: btoa error or A 'To' phone number is required..
Using qs worked for me:
import qs from 'qs';
import axios from 'axios';
const TWILIO_ACCOUNT_SID = ""
const TWILIO_AUTH_TOKEN = ""
const FROM = ""
const TO = ""
const sendText = async (message: string) => {
try {
const result = await axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${TWILIO_ACCOUNT_SID}/Messages.json`,
qs.stringify({
Body: message,
To: TO,
From: FROM,
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
auth: {
username: TWILIO_ACCOUNT_SID,
password: TWILIO_AUTH_TOKEN,
},
},
);
console.log({result});
} catch (e) {
console.log({e});
console.log({e: e.response?.data});
}
};
I'm new on Nodejs and all the modules related with Node. I've been trying to use axios for send a Oauth1.0 Autorization signature, but i'm getting: response: { status: 400, statusText: 'Bad Request', ...}
import { BASE_URL } from '../../../config/config.js';
import axios from 'axios';
import status from 'http-status';
import OAuth from 'oauth-1.0a';
import { createHmac } from 'crypto';
import dotenv from 'dotenv';
dotenv.config();
const CONSUMERKEY = process.env.consumer_key;
const CONSUMERSECRET = process.env.consumer_secret;
const TOKENKEY = process.env.access_token;
const TOKENSECRET = process.env.token_secret;
export const oauth = OAuth({
consumer: {
key: CONSUMERKEY,
secret: CONSUMERSECRET,
},
signature_method: 'HMAC-SHA1',
hash_function(base_string, key) {
return createHmac('sha1', key)
.update(base_string)
.digest('base64')
},
})
export const token = {
key: TOKENKEY,
secret: TOKENSECRET,
}
const doRequest = async (query) => {
const request_data = {
url: `${BASE_URL}`,
method: 'GET',
params: { q: `${query}` },
};
const authHeader = oauth.toHeader(oauth.authorize(request_data, token));
return await axios.get(request_data.url, request_data.params, { headers: authHeader });
};
const searchU = async (term) => {
return await doRequest(`${term}`);
};
export const userS = async (req, res, next) => {
try {
const { query } = req;
const { data } = await searchU(query.q);
const string = JSON.stringify(data);
const Rs = JSON.parse(string);
const response = {
code: 1,
message: 'sucess',
response: Rs
};
res.status(status.OK).send(response);
} catch (error) {
next(error);
if (error.response){
console.log("Response: ");
console.log(error.response);
} else if(error.request){
console.log("Request: ");
console.log(error.request)
} else if(error.message){
console.log("Message: ");
console.log(error.message)
}
}
};
I've been also trying the solution given On this post: but there's no way I can make this work, no idea what i could be doing wron...
When i try the following code (see below), using Request module (which is deprecated) works well, but I really need to do it with Axios...
const request_data = {
url: `${BASE_URL}`,
method: 'GET',
params: { q: `${query}` },
};
const authHeader = oauth.toHeader(oauth.authorize(request_data, token));
request(
{
url: request_data.url,
method: request_data.method,
form: request_data.params,
headers: authHeader,
},
function(error, response, body) {
console.log(JSON.parse(body));
}
)
Any thoughts on what I'm doing wrong on this?? Thank you very much!!
Refer to the following link for the Request Config for Axios. I believe you need to have the query params after the header in the axios.get()
Axios Request Config
Try, the following and see how it goes:-
return await axios.get(request_data.url, { headers: authHeader }, request_data.params);
Initiating an HTTP post request I am getting an error:
'Access Denied: Invalid token, wrong code'. I have tried every possible solution but I can't pass this error.
Details for this challenge:
Authorization
The URL is protected by HTTP Basic Authentication, which is explained on Chapter 2 of RFC2617, so you have to provide an Authorization: header field in your POST request
For the userid of HTTP Basic Authentication, use the same email address you put in the JSON string.
For the password, provide a 10-digit time-based one time password conforming to RFC6238 TOTP.
Authorization password
For generating the TOTP password, you will need to use the following setup:
You have to read RFC6238 (and the errata too!) and get a correct one time password by yourself.
TOTP's Time Step X is 30 seconds. T0 is 0.
Use HMAC-SHA-512 for the hash function, instead of the default HMAC-SHA-1.
Token shared secret is the userid followed by ASCII string value "HENNGECHALLENGE003" (not including double quotations).
const axios = require('axios');
const base64 = require('base-64');
const utf8 = require('utf8');
const { totp } = require('otplib');
const ReqJSON = {
"github_url": "ABC",
"contact_email": "ABC"
}
const stringData = JSON.stringify(ReqJSON);
const URL = "ABC";
const sharedSecret = ReqJSON.contact_email + "HENNGECHALLENGE003";
totp.options = { digits: 10, algorithm: "sha512", epoch: 0 };
const MyTOTP = totp.generate(sharedSecret);
const isValid = totp.check(MyTOTP, sharedSecret);
console.log("Token Info:", {MyTOTP, isValid});
const authStringUTF = ReqJSON.contact_email + ":" + MyTOTP;
const bytes = utf8.encode(authStringUTF);
const encoded = base64.encode(bytes);
const createReq = async () => {
try {
const config = {
headers: {
'Content-Type': 'application/json',
"Authorization": "Basic " + encoded
}
};
console.log("Making request", {URL, ReqJSON, config});
const response = await axios.post(URL, stringData, config);
console.log(response.data);
} catch (err) {
console.error(err.response.data);
}
};
createReq();
Try this one by changing necessary fields!
const axios = require('axios');
const base64 = require('base-64');
const utf8 = require('utf8');
const hotpTotpGenerator = require('hotp-totp-generator');
const ReqJSON = {
github_url: '',
contact_email: '',
};
const stringData = JSON.stringify(ReqJSON);
const URL = '';
const sharedSecret = ReqJSON.contact_email + '';
const MyTOTP = hotpTotpGenerator.totp({
key: sharedSecret,
T0: 0,
X: 30,
algorithm: 'sha512',
digits: 10,
});
const authStringUTF = ReqJSON.contact_email + ':' + MyTOTP;
const bytes = utf8.encode(authStringUTF);
const encoded = base64.encode(bytes);
const createReq = async () => {
try {
const config = {
withCredentials: true,
headers: {
'Content-Type': 'application/json',
Authorization: 'Basic ' + encoded,
},
};
console.log('Making request', { URL, ReqJSON, config });
const response = await axios.post(URL, stringData, config);
console.log(response.data);
} catch (err) {
console.error(err.response.data);
}
};
createReq();
Use php install the dependencies and write this
<?php
require_once 'vendor/autoload.php';
use OTPHP\TOTP;
$email = 'Email';
$secret = "{$email}HENNGECHALLENGE003";
$totp = TOTP::create(ParagonIE\ConstantTime\Base32::encode($secret), 30, 'sha512', 10, 0);
$token = $totp->now();
$token = base64_encode( utf8_encode("{$email}:{$token}") );
$url = 'https://api.challenge.hennge.com/challenges/003';
$data = [
'github_url' => 'URL',
'contact_email' => $email
];
$headers = [
//'Accept' => '/',
'Content-Type' => 'application/json',
//'Content-Length' => strlen(json_encode( $data )),
'Authorization' => 'Basic '. $token
];
PostRequest($url, $data, $headers);
function PostRequest($url, $data, $headers = [])
{
$context = curl_init($url);
curl_setopt($context, CURLOPT_POST, true);
curl_setopt($context, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($context, CURLOPT_RETURNTRANSFER, true);
$h = [];
foreach ($headers as $key => $value) {
$h[] = "{$key}: {$value}";
}
echo "- Headers".PHP_EOL;
var_dump($h);
echo "- Data".PHP_EOL;
var_dump($data);
curl_setopt($context, CURLOPT_HTTPHEADER, $h);
$ret = curl_exec($context);
curl_close($context);
var_dump($ret);
return ($ret);
}
?>
I'm trying to use 2checkout REST API
https://knowledgecenter.2checkout.com/API-Integration/REST_5.0_Reference#/introduction/authentication/json-encoded-requests
Here's a snippet of how i try to request
const axios = require('axios')
const moment = require('moment')
const saltedMd5 = require('salted-md5');
let now = moment().format('YYYY-MM-DD HH:MM:SS')
let vendorCode = '250207358831'
let toHash = vendorCode.length + vendorCode + now.length + now
let salt = '~0CSl)!M#4rZ|zX5QR&s'
const hash = saltedMd5(toHash, salt)
axios.get('https://api.2checkout.com/rest/5.0/subscriptions/?Email=customer%40email.com&AvangateCustomerReference=1234567&ExternalCustomerReference=abcdefg&Page=1&Limit=10&PurchasedBefore=2015-12-29&PurchasedAfter=2015-01-15&ExpireBefore=2016-05-22&ExpireAfter=2015-07-23&Type=regular&Aggregate=false', {
headers: {
'X-Avangate-Authentication': `code="${vendorCode}" date="${now}" hash="${hash}"`,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
It returns status code 500. Does someone know how to retrieve subscriptions using the 2checkout API?
class TwoCheckoutService {
tco: {
domain:string;
apiUrl: string,
apiUser:string,
apiPass:string,
sellerId:string,
privateKey:string,
secretKey:string,
demo:boolean,
};
constructor(private userService: UserService) {
this.tco = {=
apiUrl: 'https://api.2checkout.com/rest/6.0',
apiUser: "=",
apiPass: "=",
sellerId: "=",
privateKey: "=",
secretKey: "=",
demo: true,
// sandbox: false
};
}
private async _getAuthHeaders(): Promise<{[key:string]: string}> {
var code = this.tco.sellerId;
var date = moment().utc().format('YYYY-MM-DD hh:mm:ss');
var stringToHash = code.toString().length + code + date.toString().length + date;
var hmac = crypto.createHmac('md5', this.tco.secretKey);
hmac.update(stringToHash, 'utf8');
var hash = hmac.digest('hex')
var authHeader = `code="${code}" date="${date}" hash="${hash}"`
return {
'X-Avangate-Authentication': authHeader,
'Content-Type': 'application/json',
'Accept': 'application/json'
};
}
async getProducts() {
var url = this.tco.apiUrl + '/products/';
var headers = await this._getAuthHeaders();
console.log(headers);
var res = await Axios.get(url, {
headers: headers,
params: {
'Limit': 10,
'Page': 1,
},
validateStatus: (status)=>true
});
if(res.status === 200) return res.data;
return {
error: true,
data: res.data,
url: url,
headers: headers
}
}
}
#This is an example in typescript nodejs
##requirements
crypto
axios
2checkout api credentials