Stripe login link URL does not work - node.js

I am following the project at stripe-connect-rocketrides, and running it on my own NodeJS server to try to learn how to integrate Stripe payments. I've setup pretty much everything,
but am now running into an issue where the login link doesn't work.
To start, I have a Stripe Account ID that I have created for the user who logged in and stored in the database. Now, when I try to log the user in to the Stripe Dashboard, I know that I need to use the Create Login Link API to fetch a URL from Stripe that I can redirect users to. The URL I get is: https://connect.stripe.com/express/somehash
The problem is, when I redirect users to https://connect.stripe.com/express/somehash, this is the response I get:
{
"error": {
"code": "unexpected_api_error",
"message": "An unexpected error occurred",
"type": "api_error"
}
}
This is code in the project that redirects the users to that page:
router.get('/transfers', pilotRequired, async (req, res) => {
const pilot = req.user;
// Make sure the logged-in pilot had completed the Stripe onboarding.
if (!pilot.stripeAccountId) {
return res.redirect('/pilots/signup');
}
try {
// Generate a unique login link for the associated Stripe account.
const loginLink = await
stripe.accounts.createLoginLink(pilot.stripeAccountId);
return res.redirect(loginLink.url);
} catch (err) {
console.log('Failed to create a Stripe login link.');
return res.redirect('/pilots/signup');
}
});
I wonder if this is because the URL expired. But I always get the API error from Stripe as soon as I receive the URL. Any help would be greatly appreciated

Related

Node / React Authentication API callback STUMPER

I've been developing for a year and change and this maybe a novice question but I've tried EVERYTHING (~150 hours worth of tries, YIKES) I will post my React Frontend and my Nodejs backend to hopefully get some clarity.
Key notes:
-I am using Auth0 authentication to build an api with a nodeJs server
-Auth0 says to use an https:// call which my localhost:3000 is not. However, everything about AUTH0 works except the API call invoked when a user logs in to redirect them and display their information on their profile. I have only found one solution to this which is a reverse proxy https:// server to make calls (I can stop here if this is the issue lol unless another easier method is out there). Also why would AUTH0 require production https servers to test???
-I have the correct CORS enabled on AUTH0's site and 99% sure NodeJs (I can get a console.log response from my API) and have tried many ways on the front end and backend
to solve.
Help would greatly, greatly, be appreciated.
Code:
function URLChecker() {
// setTimeout(function(){
// console.log("Executed immediately");
if (location.pathname.indexOf('/profile/') === 0) {
//setToken(true);
return true;
}
}
function tokenChanger() {
setToken(true);
console.log("Your token is presented as...", token)
}
useEffect(()=> {
//console.log("url checker is:" + URLChecker());
if(URLChecker() == true){
tokenChanger();
console.log(location)
if (token) {
console.log("token exists");
axios.defaults.headers.get['Access-Control-Allow-Origin'] = 'http://localhost:3000';
axios.get('http://localhost:8080/profile')
.then(res => {
//console.log(res);
console.log(res.data);
}).catch(error => {
console.log(error);
console.log("API for user FAILED")
})
}
app.get('/profile', requiresAuth(), (req, res, next ) => {
console.log(req.oidc.user);
res.header("Access-Control-Allow-Origin", "*");
res.redirect(http://localhost:3000/profile/${((req.oidc.user.nickname))})
});
(res(req.oidc.user) returns a localhost:8080/profile page that is blank with the JSON of the user's information displayed. My next step is to obviously make my frontend call a different API instead of /profile to hit an authentication required api that will return user data, however no matter what I've tried I always get stuck with the same error message. I am so close and don't know whether to stick with AUTH0 to solve this error or going with Google authentication which I hear is nice.
Thank you,
imgur link to error message on my frontend

Protect the API from being displayed on the browser and programs such as postman

I want to protect the api of the current user, I am starting to learn Node.js but I know that I can get the request information so I wrote this code in which I try to prevent sensitive data from appearing if someone takes the API link and puts it on the browser or postman.
My question: is this method correct to use?.
(sorry for the poor english)
module.exports.current_user_get = (req, res) => {
// If the API is opened by browser or postman
if (req.rawHeaders.indexOf("User-Agent") > -1) {
return res.json({ msg: "Not allowed" });
}
// return user data
};

Stripe Connect in Europe: Using Payment Intents to Charge Customers (React and Node js)

I am setting up a standard stripe connect account with direct charges.
This was working perfectly for me using the charges api with tokens but won't work for me using the payments intent api as required in EU.
The below code is working in terms of getting the client secret.
axios.post(`${process.env.REACT_APP_API}/paymentIntent`, stripeData).then(res => {console.log('paymentIntent res', res.data)
let clientSecret = res.data.clientSecret
this.props.stripe.createToken({}).then(res => {
console.log('stripe token', res)
if (!res.token) {
this.setState({
message:
"Invalid Credit Card. Your tickets have not been booked. You have not been charged"
})
}
else{
this.props.stripe.confirmCardPayment(
clientSecret,
{
payment_method: {
card: {
token: res.token.id
}
}
}
).then( res => {console.log(res)})
}
})
}
But I am getting the following errors in the console:
Failed to load resource: the server responded with a status of 404 ()
error:
code: "resource_missing"
doc_url: "https://stripe.com/docs/error-codes/resource-missing"
message: "No such payment_intent: pi_1FnrwXLkWxxxxxxxxxxxxxxx"
param: "intent"
type: "invalid_request_error"
There's a few things confusing me.
My clientSecret code is in the format:
pi_1FnrwXLkWxxxxxxxxxxxxxxx_secret_pGBi46eAzWxxxxxxxxxxxxxxx
From the error message, it appears only part of it is being sent to the stripe api. Is this what is causing the error?
Two stripe answers are suggesting using the following code on the frontend.
var stripe = Stripe(STRIPE_PUBLIC_KEY, { stripeAccount: "{{ connected_account }}" })
If this is correct how do I adapt this code for react and where do i put it in the component? It is throwing me an error as it currently is.
Ref1: Code=50 “No such payment_intent” when confirm payment intent for stripe
Ref2: Stripe Connect PaymentIntent error: No such payment_intent
Elsewhere in the Stripe docs it says to use the Payment Methods API instead of tokens with the Payment Intents API. Should I abandon using tokens altogether?
I've figured the answers to these questions (with some help from stripe)
Q1. This isn't an issue
Q3. Don't use tokens with Payment Intents API.
Q2. Don't use that code from the docs. Use
<StripeProvider
apiKey={process.env.REACT_APP_API_STRIPE_PUBLISH}
stripeAccount="{{ connected_account }}">
This worked for me when I hardcoded the account but wouldn't work when I was getting the connected account id from the backend and saving in State. I got it working by conditionally rending the component. I initialised the connected account in state to '' and used this code:
{this.state.userEvent.organiser.stripeAccountID !== '' &&
<StripeProvider
apiKey={process.env.REACT_APP_API_STRIPE_PUBLISH}
stripeAccount={this.state.userEvent.organiser.stripeAccountID}>
<Elements>
<CheckoutForm
total={this.displayTotal()}
applicationFee={this.displayAdminFee()}
currency={this.state.userEvent.currency}
eventTitle={this.state.userEvent.title}
purchaser={this.state.purchaser}
userEvent={this.state.userEvent}
numTicketsSought={this.state.userEvent.numTicketsSought}
/>
</Elements>
</StripeProvider>
}

Facebook API Nodejs

I'm trying post a message as admin of a facebook page, but my code keeps posting as my personal account to the "wall" of the page, not as the page itself.
When authorizing my application I ask for the right permissionscopes, and accept them. Although, when I check my permissions with /{USER-ID}/permissions, it says that I've denied the application to manage my pages. Any ideas why?
Here's my code for posting:
var parameters = {};
parameters.message = "Hello world, this is dog.";
parameters.access_token = req.session.access_token;
FB.api('{PAGE-ID}/feed', 'post', parameters, function (result) {
if (!result) {
return res.send(500, 'error');
} else if (result.error) {
if (result.error.type == 'OAuthException') {
result.redirectUri = FB.getLoginUrl({ scope: 'publish_actions,manage_pages,publish_pages', state: encodeURIComponent(JSON.stringify(parameters)) });
}
console.log(result);
return res.send(500, result);
}
res.send(result);
});
And yes, of course I use my page id instead of the placeholder in my code above.
*Update: It seems like the permissions aren't even asked for when authorizing the application. I added the email scope to the list and it appears when I re-authorize the application.
Could this have anything to do with my application not beeing approved?
"Submit for Login Review
Some of the permissions below have not been approved for use by Facebook.
Submit for review now or read more."

Messenger Bot Fails to Respond

My bot has been approved and is available publicly (see image), but it does not respond to anyone besides the developer.
I have it hosted on Heroku. I have tried to debug it with a ton of console logs, and I have realized that it doesn't log the "Enter App.Post" (see below) when any one other than the developer sends it a message.
Has anybody else experienced this behavior?
/// Facebook verification
app.get('/webhook/', function (req, res) {
if (req.query['hub.verify_token'] === '***************') {
res.send(req.query['hub.challenge'])
}
res.send('Error, wrong token')
})
/// Star up the server
app.listen(app.get('port'), function() {
console.log('running on port', app.get('port'))
})
app.post('/webhook/', function (req, res) {
console.log("Enter App.Post");
messaging_events = req.body.entry[0].messaging
for (i = 0; i < messaging_events.length; i++) {
....
Update: I found the following logs:
Error: { message: '(#10) Cannot message users who are not admins, developers or testers of the app until pages_messaging permission is reviewed and the app is live.',
type: 'OAuthException',
code: 10,
fbtrace_id: 'CVUDg****' }
Are you sure your Facebook messenger bot has been approved by Facebook?
They have to formally approve specifically the messenger bot before anyone besides admins developers and testers can use it.
There's nothing in the code provided that would stop it from receiving messages from other users, so I'm guessing your bot hasn't actually been approved by Facebook yet.
If you're trying to test it with a user besides yourself, add them as a tester and they will have access to the bot, pre-approval.

Resources