'My redirect url adds to my url instead of replacing
I'm updating the stripe checkout on a website and I'm having trouble redirecting to the session.url. Everything worked fine in localhost, bu now that is live I can't make it redirect correctly (even though the log on stripe page says it's good). The problem is that the url that I want to go to doesn't substitute my current url, but goes after it. Since I'm not the person who coded the rest of the website and I'm also unexperieced I'm having a bit of dificulty solving this issue. Below is the server code:
/*jshint esversion: 6 */
(()=>'use strict')(); //use strict in function form
// ================================================================
//This adds functionality to express response so we can use layouts (check /otherModules/mpResponse.js for details)
require('./utils/mpResponse')();
const express = require('express'),
path = require('path'),
app = express(),
bodyParser = require('body-parser'),
passport = require('passport'),
// LocalStrategy = require('passport-local').Strategy, // not required when using email as local strategy login
flash = require('connect-flash'),
session = require('express-session'),
{User} = require('./models/index'),
util = require('util'),
cookieParser = require('cookie-parser'),
i18n = require('i18n'),
MongoStore = require('connect-mongo')(session),
favicon = require('serve-favicon'),
auth = require('./middleware/authentication'),
asyncMiddleware = require('./utils/asyncMiddleware'),
logger = require('./utils/logger'); //winston with mongodb transport
cfg = require('./config');
stripeRoutes = require('./routes/stripe/webhooks.js');
// ADDED BY ANA TO HAVE NEW CHECKOUT =====
mongoose = require('mongoose');
Subscription = require('./models/subscription');
userModel = require('./models/userModel');
const { ObjectId } = require('mongodb');
let userId;
let customer; //stripe customer object
mongoose.connect('mongodb+srv://....wqjcc.mongodb.net/ibasim?retryWrites=true&w=majority', { useNewUrlParser: true })
.then((result) => console.log('connected with db - ana'))
.catch((err) => console.log(err))
//=======================================
const { redirect } = require('express/lib/response');
// ================================================================
// load all configs
var config = require('./config');
// ================================================================
// setup our express application view engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, config.viewTemplateFolder ));
app.set('view layout', 'main_layout');
// ================================================================
//serve static files directly from public folder
app.use( express.static(path.join(__dirname, config.public)) );
app.use( express.static(path.join(__dirname, 'locales')) );
app.use('/js', express.static(`${__dirname}/node_modules/bootstrap/dist/js`));
app.use('/jquery', express.static(`${__dirname}/node_modules/jquery/dist`));
app.use('/css', express.static(`${__dirname}/node_modules/bootstrap/dist/css`));
// ================================================================
// Favicon (dosen't seem to be working)
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// ================================================================
// Webhooks
const stripe = require('stripe')(cfg.stripe.keySecret);
const endpointSecret = process.env.webhookSecret;
let subscription;
app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
let event;
try {
event = stripe.webhooks.constructEvent(req.body, req.header('stripe-signature'), endpointSecret);
} catch (err) {
console.log(err);
return res.sendStatus(400)
}
if (event.type === 'checkout.session.completed') {
console.log('checkout.session.completed')
console.log(event.data.object.subscription)
subscription = await stripe.subscriptions.retrieve(
event.data.object.subscription
);
console.log(subscription)
};
if (event.type === 'payment_intent.succeeded') {
console.log('payment_intent.succeeded')
const data = event.data.object;
// const paymentMethod = event.data.object.payment_method;
// // const customer = event.data.object.customer;
// // attach payment to customer
// const attachPaymentToCustomer = await stripe.paymentMethods.attach(
// paymentMethod, // <-- your payment method ID collected via Stripe.js
// { customer: customer.id } // <-- your customer id from the request body
// );
// //create subscription
// const subscription = await stripe.subscriptions.create({
// customer: customer.id,
// items: [{ plan: 'plan_DznNb3tPEEI0cj' }],
// default_payment_method: paymentMethod,
// expand: ['latest_invoice.payment_intent']
// });
const customer = await stripe.customers.retrieve(
event.data.object.customer
);
try {
await User.updateOne(
{_id: ObjectId(userId) },
{$set: { "stripeCustomer": customer}},
);
} catch (err) {
console.log(err);
}
try {
await User.updateOne(
{_id: ObjectId(userId) },
{$set: { "stripeCustomer.subscriptions": subscription}},
);
} catch (err) {
console.log(err);
}
}
res.sendStatus(200);
});
// ================================================================
// setup modules
app.use(express.urlencoded({extended: true})); //so we can post nested objects
app.use(express.json()); //use json parser middleware
app.use(flash());
// ================================================================
// TODO: add i18n config to another file
// i18n setup
i18n.configure({
directory: `${__dirname}/locales`,
defaultLocale: config.defaultLanguage,
queryParameter: 'lang',
autoReload: true,
cookie: 'i18n',
objectNotation: true, // object notation needs to be set to true for nested translations to work
logDebugFn: (msg) => {
console.log('debug', msg);
},
logWarnFn: (msg) => {
console.log('warn', msg);
},
logErrorFn: (msg) => {
console.log('error', msg);
}
});
// ================================================================
// cookie-parser middleware
app.use(cookieParser('delta slefty'));
// ================================================================
// session middleware
app.use(session({
secret: 'delta slefty',
resave: false, // (https://www.npmjs.com/package/express-session) resave true may cause race conditions as per documentation
saveUninitialized: false,
// cookie: {
// maxAge: 600000
// secure: true // cookie.secure true requires https applications, set to true after https is enabled
// },
store: new MongoStore({
mongooseConnection: require('./models/initMongoose').mongoose.connection, // use existing connection
touchAfter: 24 * 3600
})
}));
// ================================================================
/**
* Mount i18n
*
* i18n mount has to come after cookie-parser config
*/
app.use(i18n.init);
// ================================================================
/**
* Config passport
*
*/
app.use(passport.initialize());
app.use(passport.session());
passport.use(User.createStrategy());
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser( (id, done) => {
User.findById(id, (err, user) => {
//for the user that are agregated into group leaders or managers
//select their manager by id and add the company and manager object
if(!user || !user.role ) return done(err, user);
if(user.role === 'user' && user.affiliatedOf ){
User.findById(user.affiliatedOf, (e, manager) => {
var userWithAddons = user.toObject();
userWithAddons.company = manager.company || manager.name;
userWithAddons.manager = manager;
return done(e, userWithAddons);
});
}else{
done(err, user);
}
});
});
// ================================================================
/**
*
*
*/
app.use( asyncMiddleware( async(req, res, next) => {
if( req.cookies.i18n ){
//set language according to user preference (cookies)
req.lang = req.cookies.i18n;
}else{
//or the default language if no cookies exist
req.lang = config.defaultLanguage;
}
res.locals.currentUser = req.user;
res.locals.error = req.flash('error');
res.locals.success = req.flash('success');
//check for user for active subscription and add it to the user object so it is accessible anyware
if(req.user){
let manager = req.user.manager || req.user
res.locals.currentUserHasActiveSubscription = await manager.hasActiveSubscription()
}else{
res.locals.currentUserHasActiveSubscription = false;
}
next();
}));
// ================================================================
/**
* Register routes
*
*/
app.use('/', require('./routes'));
var server = app.listen(config.web.port, function () {
let host = server.address().address;
let port = server.address().port;
console.log("Example delta-slefty.tk listening at http://%s:%s", host, port);
});
// ================================================= Ana Stripe
app.post('/create-checkout-session', async (req, res) => {
userId = req.user._id;
let planId;
let planRenewal;
let normPlanId, rsaPlanId;
let planName;
let cartElements = [];
customer = await stripe.customers.create({
description: req.user.name,
address : {
country: 'PT',
}
});
await Subscription.find({_id: req.body.sub_id})
.then((result) => {
planId = result[0].stripePlanId;
planRenewal = result[0].renewalPeriod;
planName = result[0].name;
})
.catch((err) =>
console.log(err));
cartElements.push(planId);
let cartArray = [];
for (let j = 0; j < cartElements.length; j++) {
cartArray[j] = { price: cartElements[j], quantity: 1 }
};
const session = await stripe.checkout.sessions.create({
line_items: cartArray,
mode: 'subscription',
customer: customer.id,
success_url: `${process.env.web_app_url}/subscricoes`,
cancel_url: `${process.env.web_app_url}`,
automatic_tax: {enabled: true},
});
res.redirect(301, session.url);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
