myDHL express api - javascript

i'm trying to use the mydhl express api but i can't seem to understand how the authorization works?
they have a small code that explains how it works. I tried to follow the steps and encode the basic auth in base64 but it doesn't seem to work.
did anyone ever work with this api because there is not much info nor videos on the internet to explain this specifici API.
here i tried to get the tracking of the shipping (example code of DHL)
const options = {
method: 'GET',
headers: {
'Message-Reference': 'SOME_STRING_VALUE',
'Message-Reference-Date': 'SOME_STRING_VALUE',
'Accept-Language': 'SOME_STRING_VALUE',
'Plugin-Name': 'SOME_STRING_VALUE',
'Plugin-Version': 'SOME_STRING_VALUE',
'Shipping-System-Platform-Name': 'SOME_STRING_VALUE',
'Shipping-System-Platform-Version': 'SOME_STRING_VALUE',
'Webstore-Platform-Name': 'SOME_STRING_VALUE',
'Webstore-Platform-Version': 'SOME_STRING_VALUE',
Authorization: 'Basic REPLACE_BASIC_AUTH'
}
};
fetch('https://api-mock.dhl.com/mydhlapi/shipments/1234567890/tracking', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err))
i have my own test enviroment with the API key and secret code.
(https://developer.dhl.com/api-reference/dhl-express-mydhl-api#operations-tracking-exp-api-shipments-tracking) < link to api
we tried to apply basic auth but like i said it gives us an error.
this error is given when i use my DHL api key and secre
TypeError: fetch failed at Object.fetch (node:internal/deps/undici/undici:14152:11) { cause: Error: read ECONNRESET at TLSWrap.onStreamRead (node:internal/stream_base_commons:217:20) { errno: -4077, code: 'ECONNRESET', syscall: 'read' } }
and if i tried to use my DHL dev account it gives me this
{
reasons: [ { msg: 'Invalid Credentials' } ],
details: { msgId: 'Id-a5f4e4639291c4f137e97598' }
}

Related

Bad Request when fetching id token from Google

This may be a newbiew question (I haven't used the fetch api before), but I can't figure out what wrong with my request.
fetch('https://securetoken.googleapis.com/v1/token?key=' + API_KEY, {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'grant_type=refresh_token&refresh_token=' + refreshToken
})
.then(response => console.log(response))
.catch(error => console.error(error))
I'm trying to exchange a refresh token for an id token following the guidelines here, but for some reason I'm getting a Bad Request response...
Response { type: "cors", url: "https://securetoken.googleapis.com/v1/token?key=[API_KEY]", redirected: false, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }
My key is correct, and the refreshToken is also straight from a response from a service on Firebase SDK.
Where exactly is my mistake?
UPDATE
Showing the context where fetch is executed in a Next.js app:
I'm running this code in dev (localhost) using Firebase Emulators.
I managed to find additional error logs that state { code: 400, message: "INVALID_REFRESH_TOKEN", status: "INVALID_ARGUMENT" }.
So, this indeed seems to be an issue with the refresh_token. Can it be because it has been emitted by Firebase Emulators?
useEffect(() => {
return firebase.auth().onIdTokenChanged(async user => {
if (user) {
fetch('https://securetoken.googleapis.com/v1/token?key=' + process.env.NEXT_PUBLIC_FIREBASE_API_KEY, {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'grant_type=refresh_token&refresh_token=' + user.refreshToken
})
.then(response => console.log(response))
.catch(error => console.error(error))
}
})
}, [])
In the end the cause for the issue was the fact that the refreshToken issued when using Firebase Emulators is not valid when exchanging for an idToken.
Quite an edge case, but perhaps someone may find this helpful.

Auth0 React Native patch user by Management API

I want to patch the user_metadata of a user in my Auth0 Authentication in react native but I get the following error:
{"error": "Unauthorized", "message": "Missing authentication", "statusCode": 401}
So I am importing Auth0 in my react native:
import Auth0 from "react-native-auth0";
const auth0 = new Auth0({
domain: Config.AUTH0_DOMAIN,
clientId: Config.AUTH0_CLIENT_ID
});
I use the constants Config.AUTH0_DOMAIN and Config.AUTH0_CLIENT_ID from my dashboard from my application.
As a next step I execute the following code:
login = () => {
auth0.webAuth
.authorize({
scope: Config.AUTHO_SCOPE,
audience: Config.AUTH0_AUDIENCE,
device: DeviceInfo.getUniqueID(),
prompt: "login"
})
.then(res => {
auth0.auth
.userInfo({token: res.accessToken})
.then(data => {
fetch(`https://<MY_AUTH_DOMAIN>/api/v2/users/${encodeURIComponent(data.sub)}`, {
method: "PATCH",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"metadata": {first_name: 'John', last_name: 'Doe', skillLevel: 'PRO!'}
})
}).then(res => res.json())
.then(async (data) => {
try {
console.log('user stored', data);
} catch (e) {
console.log("error while user storing", e)
}
})
})
})
}
Whereby Config.AUTHO_SCOPE and Config.AUTH0_AUDIENCE is also from my auth0's app dashboard.
Am I missing some authentication in my headers or is the Management API the wrong choice? Do I need to to this query probably from my Back-End?
Resources:
Official API Doc from the Management API: https://auth0.com/docs/api/management/v2?_ga=2.147997749.368915485.1617866251-2089752765.1617460658#!/Users/patch_users_by_id
Official react-native-auth0 doc: https://auth0.github.io/react-native-auth0/src_management_users.js.html
Thanks for the help!
I was having this issue and I got it working after a little work.
First, I had to configure my project to give metadata write permission in Auth0's dashboard at Applications/Apis.
The two I added were read:current_user and update:current_user_metadata.
Then, in my authorize request, I modified both scope and audience.
audience: 'https://<MY APP DOMAIN>/api/v2/'
scope: 'read:current_user update:current_user_metadata openid profile offline_access'
Next, I got the userId by passing my authentication token to auth.userInfo like so.
auth0.auth.userInfo({token: authToken}).then((response)=>{
return response.sub;
})
Finally, I used the value returned from response.sub along with the authToken that I had setup with special audience and scope to patch the user, and it worked successfully. UserId is what response.sub returned.
auth0.users(authToken).patchUser({id: userId, metadata: newUserMetadata});
EDIT:
One other issue I see with your code snippet, if you want to use fetch, is you didn't put a bearer authorization token in the header. Your fetch response will probably return with a 401 error if that's the case. The code should look something like this:
const serverResponse = await fetch('https://<MYAPP>.auth0.com/api/v2/users/' + user.sub,{
headers:{
Authorization: 'Bearer ' + accessToken
}
})

POSTing a request via AXIOS in Vue always returns a 405 and CORS error

I know this error has multiple solutions and honestly I have tried all of them but it didn't work at all. I am building a Vue App which I am testing in loclahost to send SMS on a button click. Below is the code;
const headers = {
headers: {
"content-type": "application/json",
"Access-control-allow-origin": "*",
authorization: basicAuthHeader(username, upassword),
"account-id": Buffer.from(acc_id, "utf8").toString("base64"),
},
};
function basicAuthHeader(uname, upass) {
let base64String = Buffer.from(
`${uname}:${upass}`,
"utf8"
).toString("base64");
return `Basic ${base64String}`;
}
axios
.post(
`https://www.echomobile.org/api/messaging/send?phone=${phone}&message=${message}`,
headers
)
.then((res) => console.log(res))
.catch((err) => console.error(err));
Another reason why I am stuck is because of the lack of documentation. No matter what I do, I always end up with a CORS and a 405 error. Please help me out.

Feedly API is returning session expired instead of letting me access the API from local node environment

Using feedlys api with a node wrapper suggested from feedly to access its api. I am not getting successful logins. I have scoured the docs and any resources available and cannot find any answers so I'm reaching out to the stack overflow community to see if anyone has had experience with this platform.
I tried clearing the cache. I've tried using the fetch api instead of using the node wrapper I am trying to implement.
I installed the node package 'feedly'.
added this code to my server:
const Feedly = require('feedly')
const f = new Feedly({
client_id: 'client_id here',
client_secret: 'client_secret here',
base: 'https://cloud.feedly.com/v3/collections/',
port: 8080
})
async function feedlyStream() {
const results = await f.reads()
return console.log('results', results)
}
feedlyStream();
It does take me to a page to log in, presumably this is the auth so then i can retrieve data.
I'm not a backend user and primarily front end so performing the task this way is new to me.
When i run nodemon ./server.js from the console, it takes me to a login page, like that of feedlys website but then I get the error 'session expired'. There is no other errors, not in the console etc.
I can get retrieve information when working with insomnia to test the api endpoints, with the same exact info as above plus a bearer token.
Here is the fetch version i have tried with is very similar to that of the insomnia input.
const URL = 'https://cloud.feedly.com/v3/collections/'
const proxyurl = "https://cors-anywhere.herokuapp.com/";
window.onload = () => {
fetch(proxyurl + URL, {
credentials: 'same-origin',
Accept: 'application/json',
headers:
{
'Authorization': 'Bearer TOKEN GOES HERE',
'Access-Control-Allow-Origin': 'include',
'Content-Type': 'application/json',
"client_id": "client_id here",
"method": "GET",
"client_secret": "client_secret here",
}
})
.then(function (data) {
console.log('data from api', data.body);
const here = document.getElementById("here")
const bodyText = () => {
if (data.body == null) {
return "Nope, it's null"
}
return data.body;
}
here.innerHTML = bodyText();
})
}
This is what i receive from the console log above
data from api ReadableStreamlocked: false__proto__: ReadableStream
Any help will be greatly appreciated. Thank you.
quite simply i was missing part of the fetch. I needed to transform the response into JSON. Not use to fetch or apis still and this was an obvious but annoying one.
"method": "GET",
"client_secret": "client_secret here",
}
})
.then(res => res.json();) // this is what i needed to add in :)
.then(function (data) {
console.log('data from api', data.body);

Keep getting error with `Fetch` `response.json()`

I have a JavaScript widget with the code:
function submit(email, pass){
fetch('http://127.0.0.1:8888/api/example', {
headers: {
"Content-Type": "application/json",
"Access-Control-Origin": "*",
"X-Requested-With": "XMLHttpRequest",
},
method: 'post',
body: JSON.stringify({
email: email,
password: pass
})
})
.then(
response => response.json(),///<---always give error
error => console.log('An error occurred.', error)
)
.then(
res => dispatch(completeTransactionsSave(res)
)
})
}
I keep getting error:
Uncaught (in promise) SyntaxError: Unexpected end of JSON input
The line response.json() causes the error. I checked many tutorials and all seems to be using the same code and get back the result.
How can I resolve this?
Important Note
I just found out that happened because I am testing it with localhost. The moment I deploy it to real server, everything works fine.
The lesson, never test cross origin stuff with localhost.

Categories