This is my first time of integrating payment gateway to my website using official paystack-node sdk package in my node.js application, but after following through the documentation i’m facing this error: PayStackAPIError: Bearer Authorization header may not have been set | Unauthorized (401).
This is my code sequence on the server side:
const Paystack = require('paystack-node');
const {PaystackPaymentSetupValidator,throwValidationError} = require('../utils/schemas');
const router = require('express').Router();
const ExpressError = require('../utils/express_error');
const paystack = new Paystack(process.env.PAYSTACK_SECRET_KEY, process.env.NODE_ENV);
const _isDevt = (process.env.NODE_ENV !== 'production');
const callback_url = process.env.PAYSTACK_CALLBACK_URL;
// Middleware to validate Paystack requests
const _validateRequest = async (req, resp, next) => {
try{
const {req_typ} = req.body;
const {error} = await req_typ=='paystack-payment-setup-req'? PaystackPaymentSetupValidator.validate(req.body,{abortEarly:false}) : throwValidationError(req.body);
if (error) {
let msg = error? error.details.map(el => el.message).join('n# ') : 'Invalid Session Data!';
if(_isDevt){
console.log('validation err:',error,msg);
msg = `n# ${msg}.`;
} else {
msg = '';
} // end if
req.app.locals.appfx.log(new ExpressError('Validation Error',msg,0,req.body));
return resp.send({error: {text: msg||'Invalid Request format.'}});
} // end if
return next();
} catch(err) {
if(_isDevt){
console.log('catch err:',error);
} // end if
req.app.locals.appfx.log(error);
return resp.send({error: {text:`Request Error!${_isDevt?`n${error}`:''}`}});
} // end catch
} // end fx
// Middleware to initialize Paystack
const _initiatePayment = async (req, resp) => {
try {
const {email, amount, metadata} = req.body;
const response = await paystack.initializeTransaction({
email: email,
amount: amount * 100, // Amount in kobo
metadata: metadata || {},
callback_url: callback_url
});
console.log('resp:',response);
if(response.status) {
return resp.send({success: {text: 'Paystack initialized successfully.', data: response.data}});
} else {
return resp.status(400).send({error: {text: 'Failed to initialize Paystack transaction.'}});
} // end if
} catch (error) {
if(_isDevt){
console.log('catch err:',error);
} // end if
req.app.locals.appfx.log(error);
return resp.status(500).send({error: {text:`Request Error!${_isDevt?`n${error}`:''}`}});
} // end catch
} // end fx
// Middleware to verify Paystack transaction
const _verifyPayment = async (req, resp, next) => {
const {reference} = req.body||req.query;
if(!reference) {
return resp.status(400).send({error: {text: 'Transaction reference is required.'}});
} // end if
try {
const response = await paystack.verifyTransaction({reference});
// Handle successful verification (e.g., update order status)
if(response.data.status && response.data.data.status === 'success') {
req.transaction = response.data.data;
return next();
} else {
return resp.status(400).send({error: {text: 'Transaction verification failed.'}});
} // end if
} catch (error) {
if(_isDevt){
console.log('catch err:',error);
} // end if
req.app.locals.appfx.log(error);
return resp.status(500).send({error: {text: 'An error occurred while verifying the transaction.'}});
} // end catch
} // end fx
// Define routes
router.get('/', (req, resp) => {
return resp.render('paystack', { title: 'Paystack Payment Gateway Handler', user: req.user, _csrf: req.app.locals._csrf, payment_setup_url:'payment_setup/initiate' });
});
router.route('/initiate').post(_validateRequest, _initiatePayment);
router.route('/verify').post(_validateRequest, _verifyPayment, (req, resp) => {
return resp.send({success: {text: 'Transaction verified successfully.', data: req.transaction}});
});
module.exports = router;
After running this, I get this error:
PayStackAPIError: Bearer Authorization header may not have been set | Unauthorized (401).
I was hoping for smooth running, please can anyone help me through this…