Cancel Subscription Paypal API + Axios + React - reactjs

I'm stuck with a Paypal Smart buttons error that says 401 (Unauthorized)
The business solution is paid for and everything that should be authorized is.
This is the function I created. Anything in-between [ ] are placement holders of private info:
cancelSubscription = () => {
axios({
url: `https://api.paypal.com/v1/billing/subscriptions/[USER_SUBSCRIPTION_ID]/cancel`,
method: 'post',
headers: { "Content-Type": "application/json", "Authorization": "Bearer [FACILITATOR_ACCESS_TOKEN]" },
data: { "reason": "test -- Not satisfied with the service" }
})
.then(res => {
console.log(`Axios Call completed: ${res}`)
});
}

I don't see a problem with your code, so the clientid, access token, and full response body+response headers (including a PayPal-Debug-Id) will all have to be looked at to troubleshoot a 401. Submit this information to PayPal's support if you aren't going to post it here.

Related

how to fix cors error in mongodb atlas data api

this is the code
HERE this is giving me the cors error. i also added the allow access origin header but the issue is not solved
let headersList = {
"Accept": "*/*",
"User-Agent": "Thunder Client (https://www.thunderclient.com)",
"api-key": "U5H4A6FcMbEuZ33LP0ACQHP0ydkXkGLLJnDfNzQzCXTpzxL8QdJ8tH7NocITeZvv",
"Content-Type": "application/json"
}
let bodyContent = JSON.stringify({
"collection":"users",
"database":"college",
"dataSource":"Cluster0",
"projection": {}
});
let reqOptions = {
url: " https://data.mongodb-api.com/app/data-tfdur/endpoint/data/beta/action/findOne",
method: "POST",
headers: headersList,
body: bodyContent,
}
axios.request(reqOptions).then(function (response) {
console.log(response.data);
})```
At this time, the MongoDB Data API does not support browser requests as CORS is not implemented.
There is a support page where you can vote to let them know the importance of this feature:
MongoDB: Please Support CORS from the Data API

Unspecific CORS error with Post method using fetch on React (Spring Boot backend)

Very new to React coming from a decent understanding of Angular. I have had CORS issues with Angular and have always solved them with backend config. Unfortunately that has not been the case so far with React.
Also, quick note that this is app purely for educational purposes and no actual sensitive date is being submitted or stored in the database. My main concern is with just getting this thing working rather than flawless security, as I am still pretty basic in my React knowledge.
The issue comes with posting to my API using fetch in React. The post method works just fine in Postman, but when using the browser (Chrome) I get the following message:
POST https://bookkeeperdb.herokuapp.com/api/books/add net::ERR_ABORTED 403
Response {type: "cors", url: "https://bookkeeperdb.herokuapp.com/api/books/add", redirected: false, status: 403, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 403
statusText: ""
type: "cors"
url: "https://bookkeeperdb.herokuapp.com/api/books/add"
__proto__: Response
Initially, I was getting more informational errors about being more specific in my config rather than using the wildcard for everything. All of my research into this issue has bounced me from one error to the next and has made the CORS config on my backend more specific. However, I am stuck at this issue and cannot find any relevant solutions to this problem online.
Here is my code for reference:
FRONTEND (form submission in REACT):
handleSubmit(event) {
event.preventDefault();
const formFields = {
title: this.state.bookTitle,
synopsis: this.state.synopsisInput,
pageCount: parseInt(this.state.pageCountInput),
isbn: parseInt(this.state.isbnInput),
genre_name: this.state.genreInput,
author_first_name: 'Cormac',
author_last_name: 'McCarthy',
// author_first_name: this.state.authorInput.slice(0, this.state.authorInput.indexOf(" ")),
// author_last_name: this.state.authorInput.slice(this.state.authorInput.indexOf("")),
publisher_name: this.state.publisherInput
}
const headers = new Headers({
'Content-Type' : 'application/json',
'Authorization': `Bearer ${localStorage.token}`
})
console.log(`The following title was submitted: ${formFields.title}`);
fetch("https://bookkeeperdb.herokuapp.com/api/books/add", {
method: 'POST',
credentials: "include",
headers: headers,
body: JSON.stringify(formFields)
})
.then((response) => console.log(response))
.catch(error => console.log(error))
}
BACKEND (corsconfig in SPRING BOOT):
#Configuration
public class CorsConfig {
#Bean
public WebMvcConfigurer corsConfigurer(){
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.allowedOrigins("http://localhost:3000",
"http://localhost:3000/contribute");
}
};
}
}
Thank you in advance for the help.
Okay, really just took some experimenting but turns out including 'Bearer' in my Authorization header was messing up my token authentication when submitting the post. Well that was anti-climatic.

Netlify, Lambdas, Stripe, and Googlebots

Ive been working on an SPA with React that i have deployed on Netlify. The application uses stripe.js as a form of payment. While all of the functionality of stripe appears to be working fine on the user side, we are running into a problem with Google Search Console. It seems that the Googlebot Crawler is being blocked by the Stripe robots.txt file. basically the ultimate goal is to be approved for google adsense and after numerous rejections (even with prerendering and a lot more content added) we are still getting rejected. when we tried the google search console to see what google bot crawlers see we have absolutely no errors, the site is mobile friendly BUT we are getting this error that is shown below. While I obviously don't have any control over their use of Stripes robot.txt file, the Search console is also telling me this:
Message:
Access to XMLHttpRequest at 'https://m.stripe.com/6' from origin 'https://m.stripe.network' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Source:
https://m.stripe.network/inner.html#url=https%3A%2F%2Fwww.stateiqtest.org%2F&title=&referrer=&muid=NA&sid=NA&version=6&preview=false:0
The last thing i want to mention is all of the stripe functionality is accessed and called from a serverless Lambda function through netlify... I am confused why the CORS issue is a policy for the bot but not for users of the site? I am attaching my stripe lambda function call which I just enabled the cors policy for... but once again ... why do i have to even do this? if im not getting errors in the console from the user side how come the bot can't access it? i have tried everything from changing my netlify.toml file to adding a robots.txt file which disallows the provided Stripe URL. any leads? let me know! your help is already appreciated ! :)
//client sides
import {loadStripe} from "#stripe/stripe-js"
export async function handleFormSubmission(event) {
event.preventDefault();
const form = new FormData(event.target);
const data = {
sku: form.get('sku'),
quantity: Number(form.get('quantity')),
};
const response = await fetch('/.netlify/functions/create-checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "GET, POST",
},
body: JSON.stringify(data),
}).then((res) => res.json())
const stripe=await loadStripe(response.publishableKey);
const {err}=await stripe.redirectToCheckout({
sessionId:response.sessionId
})
if(err){
console.log(err)
}
}
im honestly going to admit i haven't used stripe in a while and haven't had issues until now thus am revisiting code. here is another function that i believe makes the request and creates the stripe checkout...
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const inventory = require('./data/products.json');
exports.handler = async (event) => {
const { sku, quantity } = JSON.parse(event.body);
const product = inventory.find((p) => p.sku === sku);
const validatedQuantity = quantity > 0 && quantity < 2 ? quantity : 1;
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
billing_address_collection: 'required',
success_url: `${process.env.URL}/success`,
cancel_url: process.env.URL,
line_items: [
{
name: 'Cognitive Analysis',
currency:'USD',
amount: 299,
quantity: 1
},
],
});
return {
statusCode: 200,
body: JSON.stringify({
sessionId: session.id,
publishableKey: process.env.STRIPE_PUBLISHABLE_KEY,
}),
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "GET, POST",
}
};
};

Fetch 401 Authorization issue

I've started to build a project using WooComeerce and React.js, but I have one question.
When I try to get the data, for example: "products", received an issue 401 unauthorized..
I've tested my request into Postman/Insomnia and everything is working as expected. I think the problem is coming from the headers part, but for now I can't handle the issue..
Also my response headers are empty!
Here is my code:
const getProducts = async () => {
const response = await fetch(`${process.env.REACT_APP_API_URL}products?consumer_key=${process.env.REACT_APP_API_CONSUMER_KEY}&${process.env.REACT_APP_CONSUMER_SECRED_KEY}`,
{
method: "GET",
mode: "cors",
credentials: "include",
headers: {
"Authorization": `Basic ${process.env.REACT_APP_API_CONSUMER_KEY}`,
"Content-Type": "application/json",
},
}
);
return response;
};
How can i fix that issue?
Note: I'm not using WooCommerce REST API package.
Thank you in advance!
Usually the basic auth string is base64-encoded string username:password. However i see the consumer key being used in the req and the header. Can you please double check your authorization header?

Cannot generate embed token using access token in power bi

I'm trying to be understand authorization mechanism in power bi API
I would embed a report in my web app.
I have done the steps as mentioned in docs
Actually I would get report embedded url then use power bi JS API to embed the report.
Getting access_token is successful
var options = {
'method': 'POST',
'url': `https://login.microsoftonline.com/${process.env.TENANT_ID}/oauth2/token`,
'headers': {
'Content-Type': 'multipart/form-data'
},
formData: {
'grant_type': process.env.GRANT_TYPE,
'client_id': process.env.CLIENT_ID,
'client_secret': process.env.CLIENT_SECRET,
'resource': "https://analysis.windows.net/powerbi/api",
'Scope': "https://analysis.windows.net/powerbi/api/.default"
}
};
Now I try to get embedded token for report in group
var data = { accessLevel: "View", datasetId: "5b11d62a-803e-46c9-83f3-*****" };
var config = {
method: 'post',
url: `https://api.powerbi.com/v1.0/myorg/groups/${process.env.GROUP_ID}/reports/${process.env.Report_ID}/GenerateToken`,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${JSON.parse(response).access_token}`
},
data: data
};
let embedtoken
try {
embedtoken = await axios(config)
}
catch (e) {
console.log(e)
}
context.res = {
// status: 200, /* Defaults to 200 */
body: JSON.parse(response).access_token
};
I get error 400 response
But When I generate an embed token for dashboard I get a valid token. But of course that's not working with get report API
My goal is to get report infos. For information I get get that using the access token but it's not safe
For POST API requests, data should be passed in string format. This can be done by using for example, JSON.stringify(data).
Refer below code snippet which should resolve the error.
var config = {
method: 'post',
url: `https://api.powerbi.com/v1.0/myorg/groups/${process.env.GROUP_ID}/reports/${process.env.Report_ID}/GenerateToken`,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${JSON.parse(response).access_token}`
},
data: JSON.stringify(data) };

Resources