@unchainedshop/plugins
Version:
Official plugin collection for the Unchained Engine with payment, delivery, and pricing adapters
63 lines (62 loc) • 2.22 kB
JavaScript
import { createLogger } from '@unchainedshop/logger';
import { buildSignature } from "./buildSignature.js";
import { timingSafeStringEqual } from '@unchainedshop/utils';
const logger = createLogger('unchained:saferpay:handler');
export const saferpayHandler = async (request, reply) => {
const resolvedContext = request.unchainedContext;
const { modules, services } = resolvedContext;
const { orderPaymentId, signature, transactionId } = request.query;
const isValidRequest = typeof orderPaymentId === 'string' &&
typeof signature === 'string' &&
typeof transactionId === 'string' &&
orderPaymentId &&
transactionId &&
signature;
if (!isValidRequest) {
logger.warn(`orderPaymentId missing in query`);
reply.status(404);
return reply.send();
}
try {
logger.info(`checkout with orderPaymentId: ${orderPaymentId}`);
const orderPayment = await modules.orders.payments.findOrderPayment({
orderPaymentId,
});
if (!orderPayment) {
throw new Error(`order payment not found with orderPaymentId: ${orderPaymentId}`);
}
const correctSignature = await buildSignature(transactionId, orderPaymentId);
if (!(await timingSafeStringEqual(correctSignature, signature))) {
throw new Error('Invalid signature');
}
const order = await services.orders.checkoutOrder(orderPayment.orderId, {
paymentContext: {
transactionId,
},
});
if (!order)
throw new Error(`Order with id ${orderPayment.orderId} not found`);
logger.info(`checkout successful`, {
orderPaymentId,
orderId: order._id,
});
reply.status(200);
return reply.send({
success: true,
orderPaymentId,
orderId: order._id,
});
}
catch (error) {
logger.error(error, {
orderPaymentId,
transactionId,
});
reply.status(500);
return reply.send({
success: false,
message: error.message,
name: error.name,
});
}
};