I am building a React Native application and I am using Nodejs, MYSQL and Expo React Native. I am implementing payment with paystack for the first time. I followed their API guide which is found here for Node.js based application.
This is my code implementation:
export const httpBuyAction = async(req: Request, res: Response)=>{
//create a new instance of payment
const paystack = new PaymentSystem(sanitizedConfig.PAYSTACK_KEY);
const multiplyCartSum = cart.dataValues.cart_total_sum as number * 100;
const convertAmount = multiplyCartSum.toString()
const paymentDetails = {
email: user.dataValues.user_email as string,
amount: convertAmount as string
}
const response = await paystack.initializePayment(paymentDetails);
if(response?.response?.data?.status == false){
return res.status(response.response.status).json(response.response.data.message)
}
return res.status(200).json(response.data.data.authorization_url)
}
This code returns paystack web payment link and I used React Native Linking package to navigate to the paystack external link. This is the code:
const [paymentAuthorization, {data: paymentData, isLoading: isPaymentLoading, isSuccess: isPaymentSuccess,}]= usePaymentAuthorizationMutation();
const handlePayment = async ()=>{
dispatch(updateBackgroundLoader(true))
await paymentAuthorization()
}
I used react useEffect
to trigger the action to navigate to the paystack payment portal.
useEffect(()=>{
const handlePaymentView = async()=>{
if(isPaymentSuccess){
const supportedURL = paymentData;
const supported = await Linking.canOpenURL(supportedURL);
if(supported){
dispatch(updateBackgroundLoader(false))
await Linking.openURL(supportedURL);
}else{
dispatch(updateBackgroundLoader(false))
dispatch(updateNotification(true));
dispatch(updateError('Unsupported link, contact admin'))
}
}else{
dispatch(updateBackgroundLoader(false))
}
}
handlePaymentView()
}, [isPaymentLoading])
It works but I don't know if this is better than using a third party package. Also, I noticed that the link surely takes the user away from the app, how do I return the user to the app after payment? Is it possible?