Using microsoft graph api to send email from a react application - 401 error - axios

I have a react application that grants access to a user's outlook account. The azure app has delegated permissions for Mail.Send, Mail.ReadWrite and User.Read and when I go through the authorization flow I'm prompted that the application will be able to read and send emails for me. However, after retrieving an access token I get a 401 unauthorized error when sending an email. The logs say the token claims have Mail.Send, Mail.ReadWrite and I'm able to retrieve the user's emails just fine. So I think the token is valid. But sending an email doesn't work and gets a 401 error. Any ideas would be appreciated. Here is my request:
const url = "https://graph.microsoft.com/v1.0/me/sendMail";
const messageToSend = {
subject: "Testing Outlook API",
importance: "Low",
body: {
contentType: "HTML",
content:
"Hello, Testing 1234. This is the body of the message to send. <b>awesome</b>! ",
},
toRecipients: [
{
emailAddress: {
address: "someemail#email.com",
},
},
],
ccRecipients: [
{
emailAddress: {
address: "anotheremail#email.com",
},
},
],
saveToSentItems: true,
};
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${microsoftToken}`,
};
axios
.post(url, messageToSend, {
headers: headers,
})
.then((response) => {
console.log("sent mail", response.data);
return response.data;
})
.catch((error) => {
console.log("📛", error);
return false;
});

Related

Error 403 when requesting Google APIs in Capacitor

I am working on transferring a Web App into an iOS format using Capacitor. I am using axios to make requests to Google APIs, and my requests return an Error 403 on the iOS version despite working perfectly in the browser.
Here is the flow from authentication to making the first API call (I'm using capacitor-google-auth for the iOS OAuth, then passing the access token I get from that to Axios to use as the header for HTTP requests).
I used these resources so far: https://github.com/CodetrixStudio/CapacitorGoogleAuth, https://developers.google.com/calendar/api/v3/reference/calendarList/list
My plugin settings for GoogleAuth in "capacitor.config.json" (I've also added the URL scheme of the REVERSED_CLIENT_ID to my info.plist file, as the docs for CapacitorGoogleAuth describe):
"plugins": {
"GoogleAuth": {
"scopes": [
"https://www.googleapis.com/auth/calendar"
],
"clientId": <<my iOS Client ID>>
}
}
When starting the app with "index.js," get an access token (works):
import { GoogleAuth } from '#codetrix-studio/capacitor-google-auth'
const axios = require('axios')
const token = await GoogleAuth.signIn()
const response = await axios
.request({
method: 'GET',
url: 'https://www.googleapis.com/calendar/v3/users/me/calendarList',
headers: {
Authorization: `Bearer ${token.authentication.accessToken}`
},
params: {
key: <<My API Key>>
}
})
.catch(err => console.log(err))
console.log(response)
At this point, it throws this error:
{
"message": "Request failed with status code 403",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [null],
"transformResponse": [null],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": { "FormData": null },
"headers": {
"Accept": "application/json, text/plain, */*",
"Authorization": "Bearer <<My access token>>"
},
"method": "get",
"url": "https://www.googleapis.com/calendar/v3/users/me/calendarList",
"params": { "key": <<My Api key>> }
},
"code": "ERR_BAD_REQUEST",
"status": 403
}
Why is this happening with iOS? Is there an issue with the credentials in some way? Do Google APIs not allow HTTP requests from Capacitor apps? Any help would be appreciated as I'm quite stumped. This code works perfectly outside of the iOS environment.
So after reviewing this a bit, I learned that Capacitor apps have HTTP restrictions. Changing my request client to use the Capacitor community HTTP module works.
https://capacitorjs.com/docs/apis/http

Always getting error "requestId is required" when doing POST on quickbooks payment API Apps Script

Im creating a script that will process a credit transaction and I always getting this response:
{
"errors": [
{
"code": "PMT-4002",
"type": "invalid_request",
"message": "requestId is required.",
"detail": "requestId",
"infoLink": "https://developer.intuit.com/v2/docs?redirectID=PayErrors"
}
]
}
Im trying to figure out where to put the "request-id" parameter on the request body. Here is my code:
function QBOcreatecharge(){
var token = "TOKEN"
var service = getQuickbooksService();
if (service.hasAccess()) {
var url = 'https://sandbox.api.intuit.com/quickbooks/v4/payments/charges'
var Details =
{
"amount": "80.00",
"currency": "USD",
"capture": "false",
"token": token
}
var params = {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
contentType: 'application/json',
method: 'POST',
payload: JSON.stringify(Details),
muteHttpExceptions:true
}
var response = UrlFetchApp.fetch(url, params);
var value = JSON.parse(response.getContentText())
Logger.log(value)
}
else{
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s', authorizationUrl);
}
}
How do I add the requestId parameter? I tried to insert it on the link, on the header and nothing work. Im using UrlFetch on Google Apps Script. Any help will be appreciated. Thanks!
The Request-Id is a header you need to send. e.g.:
headers: {
Authorization: 'Bearer ' + service.getAccessToken(),
'Request-Id': your unique value here
},
Intuit documents it here:
https://developer.intuit.com/app/developer/qbpayments/docs/develop/explore-the-quickbooks-payments-api/rest-api-features#identifiers

Getting POST Request Message using React.JS

I am writing a program which has a "sign up" functionality. The front-end is created using React.JS. So far, I am able to using this code to send a post request in React.JS:
fetch('http://localhost:2000/users/signup/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"email": "testing#gmail.com",
"password": "secret",
"name": "matthew",
"organization": "Apple"
})
}).then(function(response) {
return response.json();
});
This works perfectly - for the user information is now in the database. However I am not sure how to get the response JSON using response.json(). I want to be able to take the response, get the message string, and display it to my user on the front-end. This is the response when I run the same post request on Postman.
{
"message": "New user created"
}
Thanks for the help!
response.json() returns a promise, so you need one more then to get the actual data:
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
see https://developer.mozilla.org/en-US/docs/Web/API/Body/json

Ionic Push is no longer working 1.x

Everything has been working great then now I get the following error:
ionic.bundle.js:18463 OPTIONS https://push.ionic.io/api/v1/push net::ERR_NAME_NOT_RESOLVED
i cant seem to send a push using the following:
// Encode your key
var auth = btoa(privateKey + ':');
// Build the request object
var req = {
method: 'POST',
url: 'https://push.ionic.io/api/v1/push',
headers: {
'Content-Type': 'application/json',
'X-Ionic-Application-Id': appId,
'Authorization': 'basic ' + auth
},
data: {
"tokens": devices,
"notification": {
"alert": message,
"ios":{
"priority": 10,
"badge": 1,
"payload": {"path": path}
}
}
}
};
// Make the API call
$http(req).success(function(resp){
// Handle success
console.log("Ionic Push: Push success!");
}).error(function(error){
// Handle error
console.log("Ionic Push: Push error...");
});
everything just stopped working - it was working beautifully before.
thanks for your help
I think they have change the URL and format little bit.
New URL is https://api.ionic.io/push/notifications
Payload
{
"tokens":["device_token_1", "device_token_2"],
"profile": "prod",
"notification": {
"title" : "Title of the message",
"message": "Ur message!"
}
}

Sending push notification using ionicframework cloud api

Hello am trying to send push notification from my nodejs server to ionicframework API and am getting an error here is my code
var token = '66a5c472b52d3210b591f717b5b996312f8xxxxxxxxxxxx';
var title = 'test';
var message = 'message';
var options = {
method: 'POST',
url: 'https://api.ionic.io/push/notifications',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
json : {
"send_to_all": true,
"profile" : "my-profile",
"notification": {
"title": title,
"message": message,
"android": {
"title": title,
"message": message
},
"ios": {
"title": title,
"message": message
}
}
}
};
request(options, function(err, response, body) {
if (err) throw new Error(err);
console.log(body);
});
am getting this error
{ error:
{ message: 'JWT decode error occurred.',
link: null,
type: 'Unauthorized' },
meta:
{ status: 401,
version: '2.0.0-beta.0',
request_id: '75726406-3060-4329-a59e-3bd7f9ca90c8' } }
What could I be doing wrong
I think there is issue with your authorization header.
In header you're putting token, but please make sure it is API token.
Also make a postman request first and check whether it is working fine.
add content-type and authroization parts in header only..
then check the difference..
Thanks
Basu