https://graph.microsoft.com/v1.0/me is giving 404 - javascript

I am trying to get the current user from https://graph.microsoft.com/v1.0/me.
I get a valid token, however, the request to https://graph.microsoft.com/v1.0/me gives me a 404.
var token;
$(document).ready(function () {
requestToken();
});
function requestToken() {
$.ajax({
"async": true,
"crossDomain": true,
"url": "https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded"
},
"data": {
"grant_type": "client_credentials",
"client_id ": "{client_id}",
"client_secret": "{client_secret}",
"scope ": "https://graph.microsoft.com/.default"
},
success: function (response) {
console.log(response);
token = response.access_token;
getUserInformation();
},
error: function (error) {
console.log(JSON.stringify(error));
}
})
}
function getUserInformation() {
$.ajax({
method: 'GET',
url: "https://graph.microsoft.com/v1.0/me",
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
}).success(function(response) {
console.log(response);
}).error(function(error) {});
}
Anyone knows what might be the problem?
Thank you.

I got a detailed response:
"error": {
"code": "Request_ResourceNotFound",
"message": "Resource '' does not exist or one of its queried reference-property objects are not present.",
"innerError": {
"request-id": "",
"date": "2020-04-17T09:33:43"
}
}
}

from https://graph.microsoft.com/v1.0/me
I got:
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token is empty.",
"innerError": {
"date": "2020-10-20T11:39:50",
"request-id": "becb1443-91e3-42d9-9c77-b9808aaf2cf7",
"client-request-id": "becb1443-91e3-42d9-9c77-b9808aaf2cf7"
}
}
}
https://graph.microsoft.com/.default
{
"error": {
"code": "BadRequest",
"message": "Invalid version.",
"innerError": {
"date": "2020-10-20T11:41:04",
"request-id": "3fdd24bd-7c96-4ff2-9e18-fc042673ecd2",
"client-request-id": "3fdd24bd-7c96-4ff2-9e18-fc042673ecd2"
}
}
}

Usually, request returns 404 status code when the route does not exist, So I'll recommend you to please check the provided URI is valid or not.

Related

Checkout.com Payment response JavaScript

I am trying to integrate https://www.checkout.com/ in my app.
I tried there sample code to get token.
Frames.addEventHandler(
Frames.Events.CARD_TOKENIZED,
function (data) {
Frames.addCardToken(form, data.token);
if (data.token) {
confirmPayment(data.token);
} else {
console.log(data);
}
}
);
I tried https://api.sandbox.checkout.com/payments/ api to do the payments,
payment successfully captures, but I am unable to read its response to or redirect user on successfully attempt.
async function confirmPayment(token) {
// Storing response
const response = await fetch('https://api.sandbox.checkout.com/payments/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer sk_sbox_..abc'
},
body: JSON.stringify({
"source": {
"type": "token",
"token": token
},
"Capture": true,
"processing_channel_id": "pc_..abc",
'amount': 1000,
'currency': 'USD',
"3ds": {
"enabled": false
},
"customer": {
"email": "test.testUI#example.com",
"name": "John Test"
},
'reference': 'ORD-175-759',
"metadata": {
"udf1": "UI-CALL-TEST",
"coupon_code": "NY2018",
"partner_id": 123989
},
"success_url": "http://example.com/payments/success",
"failure_url": "http://example.com/payments/fail"
})
});
// Storing data in form of JSON
var data = await response.json();
console.log(data);
if (response) {
}
show(data);
}
I want to get a payment response like errors "card invalid" etc
Also redirect to Url if successful.
Please let me know if this is a correct way to do the payment or If there any JavaScript library that I can use?
I want to do payment on client side and use webhook later.
Thank you

Send Mail with attachment Microsoft Graph not working

I am making an application that sends emails from a User as described by this article.
Everything is working as expected, except for when I try to include an attachment. The email sends, but without the attachment. I'm not sure what the problem is as I've tried pretty much everything I could find online. I have made sure the file I am sending is properly encoded in base64.
var message = {
"subject": subject,
"hasAttachments":true,
"body": {
"contentType": "Text",
"content": emailBody
},
"toRecipients": toRecipients,
ccRecipients,
bccRecipients
};
function sendMailRequest(access_token, message, uriSend, file, base64, callback){
const attachments = [{
'#odata.type': '#microsoft.graph.fileAttachment',
"contentBytes": base64
"name": "example.jpg"
}];
// Configure the request
var options2 = {
"url": uriSend,
"method": 'POST',
"headers": {
'Authorization': access_token,
'Content-Type': 'application/json'
},
"body": JSON.stringify({
"message": message,
"SaveToSentItems": "true",
"Attachments": attachments
})
}
Attachments go inside the message JSON, not outside of it. This should work:
function sendMailRequest(access_token, message, uriSend, file, base64, callback) {
const attachments = [
{
"#odata.type": "#microsoft.graph.fileAttachment",
"contentBytes": base64
"name": "example.jpg"
}
];
message["attachments"] = attachments;
// Configure the request
var options2 = {
"url": uriSend,
"method": "POST",
"headers": {
"Authorization": access_token,
"Content-Type": "application/json"
},
"body": JSON.stringify({
"message": message,
"SaveToSentItems": "true"
})
}
...
}

REST API - POST method in Vanilla JavaScript/AJAX - Error 400 (Bad request)

can you please help me how to get to work POST method in vanilla JS (without jQuery)?
I am trying to do it with this code:
var call =
{
"filterParameters": {
"id": 18855843,
"isInStockOnly": false,
"newsOnly": false,
"wearType": 0,
"orderBy": 0,
"page": 1,
"params": {
"tId": 0,
"v": []
},
"producers": [],
"sendPrices": true,
"type": "action",
"typeId": "",
"branchId": ""
}
};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.alza.cz/Services/RestService.svc/v2/products');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('OK ' + xhr.responseText);
}
else if (xhr.status !== 200) {
console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(call);
And constantly getting error 400 (Bad request).
I have tried to call it in jQuery and it is working, but I need to get it work in plain JS.
Please, any idea why it is not working?
For check, here is the working code in jQuery:
addData({
"filterParameters": {
"id": 18855843,
"isInStockOnly": false,
"newsOnly": false,
"wearType": 0,
"orderBy": 0,
"page": 1,
"params": {
"tId": 0,
"v": []
},
"producers": [],
"sendPrices": true,
"type": "action",
"typeId": "",
"branchId": ""
}
}
);
function addData(data){// pass your data in method
$.ajax({
type: "POST",
url: "https://www.alza.cz/Services/RestService.svc/v2/products",
data: JSON.stringify(data),// now data come in this function
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
console.log(data);// write success in " "
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
alert('fail' + status.code);
}
});
}
You must set the content-type header to application/json You are posting json data as formdata which is wrong (beside you have forgotten to stringify your object)
xhr.setRequestHeader('Content-Type', 'application/json');
Heres is a working example using the new vanilla js fetch API
var result = null
fetch("https://www.alza.cz/Services/RestService.svc/v2/products", {
method: "POST",
body: JSON.stringify({
"filterParameters": {
"id": 18855843,
"isInStockOnly": false,
"newsOnly": false,
"wearType": 0,
"orderBy": 0,
"page": 1,
"params": {
"tId": 0,
"v": []
},
"producers": [],
"sendPrices": true,
"type": "action",
"typeId": "",
"branchId": ""
}
}),
headers: {"content-type": "application/json"},
//credentials: 'include'
})
.then(function(res) {
if (res.ok) { // ok if status is 2xx
console.log('OK ' + res.statusText);
} else {
console.log('Request failed. Returned status of ' + res.status);
}
return res.blob()
})
.then(function(blob) {
result = blob
// window.result = blob
})
It's the Access-Control-Allow-Origin response blocking the Javascript code to AJAX access the server data. If the server is not controlled by you, you need another server to fetch the data instead, before it can redirect to your webpage.
So I just tried xhr.send()
and got
XMLHttpRequest cannot load https://www.alza.cz/Services/RestService.svc/v2/products. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://www.alza.cz' that is not equal to the supplied origin.
However if I try this on a blank tab, it actually works.
what url are you trying to run this JS from?
Try running the JS from a blank tab.

How to differentiate a cancelled request with $http

in a $http error handler, I need to differentiate a real HTTP error from cancelled requests.
Here is an example:
app.controller('Ctrl', function ($http, $q) {
const vm = this;
this.errors = [];
vm.errorHandler = (label) => ((error) => {
this.errors.push(label + ' : \n\n' + JSON.stringify(error, null, 2));
});
vm.unResolved = () => {
$http({
method: 'GET',
url : 'https://Idonotexist'
}).catch(vm.errorHandler('unResolved'));
}
vm.cancelled = () => {
const canceller = $q.defer()
$http({
method: 'GET',
timeout: canceller.promise,
url : 'https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699'
}).catch(vm.errorHandler('cancelled'));
canceller.resolve();
}
vm.unsecured = () => {
$http({
method: 'GET',
url : 'http://Idonotexist'
}).catch(vm.errorHandler('unsecured'))
}
});
In my errorHandler function, I want to differentiate cancelled requests from a real error (such as "insecured" or "unresolved hosts").
It would be a real pain for me to pass the canceller to the error handler and it won't be able to treat correctly requests cancelled by the browser without an angularjs canceller.
So far, here are the errors I get in my error handler.
Error for non cancelled (host unresolved) request :
{
"data": null,
"status": -1,
"config": {
"method": "GET",
"transformRequest": [
null
],
"transformResponse": [
null
],
"jsonpCallbackParam": "callback",
"url": "https://Idonotexist",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": ""
}
Error for cancelled request :
{
"data": null,
"status": -1,
"config": {
"method": "GET",
"transformRequest": [
null
],
"transformResponse": [
null
],
"jsonpCallbackParam": "callback",
"timeout": {
"$$state": {
"status": 1,
"processScheduled": false,
"pur": true
}
},
"url": "https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": ""
}
I have a config.timeout that contains the promise but I would like to avoid using it. I would like to treat as cancelled requests requests cancelled by the browser even if no canceller.
Here is a jsfiddle with the example.
Is there a way to add a interceptor on cancelled requests to flag then specifically ?
UPDATE
This can't be solved angularjs $http code does not separate error than timeout or abort. You can see it here.
A pull request is running about it.

Google Calendar REST API errors

I'm trying to implement a simple POST call in meteor.js to the Google Calendar API, and I'm stuck. My request looks like this:
var id = Meteor.http.post("https://www.googleapis.com/calendar/v3/calendars/", {
'headers' : {
'Authorization': auth, // auth = "Bearer " + Meteor.user().services.google.accessToken
'Content-Type': 'application/json'
},
'parameters': {},
'body' : {
'title': "Calendar Title",
}
});
and I get the following error:
Error: failed [400] {
"error": {
"errors": [{
"domain": "global",
"reason": "required",
"message": "Missing title."
}],
"code": 400,
"message": "Missing title."
}
}
Any ideas?
Solved it. This is dumb.
Take out parameters, and make "body" "data" instead and it works.

Categories