Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Oh amazonpay #232

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion enabler/dev-utils/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ const getSessionId = async (cartId, isDropin = false) => {
"bancontactmobile",
"twint",
"sepadirectdebit",
"klarna_billie"
"klarna_billie",
"amazonpay"
], // add here your allowed methods for development purposes
}),
};
Expand Down
6 changes: 4 additions & 2 deletions enabler/src/components/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
Klarna,
EPS,
Twint,
SepaDirectDebit
SepaDirectDebit,
AmazonPay
} from "@adyen/adyen-web";
import {
ComponentOptions,
Expand All @@ -27,7 +28,8 @@ type AdyenComponent =
| EPS
| Twint
| Redirect
| SepaDirectDebit;
| SepaDirectDebit
| AmazonPay;

/**
* Base Web Component
Expand Down
69 changes: 69 additions & 0 deletions enabler/src/components/payment-methods/amazonpay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import {
ComponentOptions,
PaymentMethod,
} from "../../payment-enabler/payment-enabler";
import { AdyenBaseComponentBuilder, DefaultAdyenComponent } from "../base";
import { BaseOptions } from "../../payment-enabler/adyen-payment-enabler";
import { AmazonPay, ICore } from "@adyen/adyen-web";

/**
* Amazon pay component
*
* Configuration options:
* https://docs.adyen.com/payment-methods/amazon-pay/web-component/
*/
export class AmazonpayBuilder extends AdyenBaseComponentBuilder {
public componentHasSubmit = false;

constructor(baseOptions: BaseOptions) {
super(PaymentMethod.amazonpay, baseOptions);
}

build(config: ComponentOptions): AmazonPayComponent {
const amazonPayComponent = new AmazonPayComponent({
paymentMethod: this.paymentMethod,
adyenCheckout: this.adyenCheckout,
componentOptions: config,
sessionId: this.sessionId,
processorUrl: this.processorUrl,
});
amazonPayComponent.init();

return amazonPayComponent;
}
}

export class AmazonPayComponent extends DefaultAdyenComponent {
constructor(opts: {
paymentMethod: PaymentMethod;
adyenCheckout: ICore;
componentOptions: ComponentOptions;
sessionId: string;
processorUrl: string;
usesOwnCertificate?: boolean;
}) {
super(opts);
}

init(): void {
const returnUrl = this.processorUrl.endsWith("/")
? `${this.processorUrl}payments/amazonpay?step=review&sessionId=${this.sessionId}`
: `${this.processorUrl}/payments/amazonpay?step=review&sessionId=${this.sessionId}`;

this.component = new AmazonPay(this.adyenCheckout, {
showPayButton: this.componentOptions.showPayButton,
productType: 'PayOnly',
// environment: 'test', // we can add an additional environment variable for the enabler for this, or add it to the baseOptions to be passed by the user of the enabler
returnUrl,
onClick: (resolve, reject) => {
if (this.componentOptions.onPayButtonClick) {
return this.componentOptions
.onPayButtonClick()
.then(() => resolve())
.catch((error) => reject(error));
}
return resolve();
},
});
}
}
2 changes: 2 additions & 0 deletions enabler/src/payment-enabler/adyen-payment-enabler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { DropinEmbeddedBuilder } from "../dropin/dropin-embedded";
import { SepaBuilder } from "../components/payment-methods/sepadirectdebit";
import { BancontactMobileBuilder } from "../components/payment-methods/bancontactcard-mobile";
import { KlarnaBillieBuilder } from "../components/payment-methods/klarna-billie";
import { AmazonpayBuilder } from "../components/payment-methods/amazonpay";

class AdyenInitError extends Error {
sessionId: string;
Expand Down Expand Up @@ -231,6 +232,7 @@ export class AdyenPaymentEnabler implements PaymentEnabler {
twint: TwintBuilder,
sepadirectdebit: SepaBuilder,
klarna_billie: KlarnaBillieBuilder,
amazonpay: AmazonpayBuilder,
};
if (!Object.keys(supportedMethods).includes(type)) {
throw new Error(
Expand Down
3 changes: 2 additions & 1 deletion enabler/src/payment-enabler/payment-enabler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ export enum PaymentMethod {
bancontactmobile = "bcmc_mobile", // Bancontact mobile
twint = "twint",
sepadirectdebit = "sepadirectdebit",
klarna_billie = "klarna_b2b" // Billie
klarna_billie = "klarna_b2b", // Billie
amazonpay = "amazonpay"
}

export type PaymentResult =
Expand Down
2 changes: 1 addition & 1 deletion processor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"lint:fix": "prettier --write \"**/**/*.{ts,js,json}\" && eslint --fix --ext .ts src",
"build": "rm -rf /dist && tsc",
"dev": "ts-node src/main.ts",
"watch": "nodemon --watch \"src/**\" --ext \"ts,json\" --ignore \"src/**/*.spec.ts\" --exec \"ts-node src/main.ts\"",
"watch": "nodemon --watch \"src/**\" --ext \"ts,json,html\" --ignore \"src/**/*.spec.ts\" --exec \"ts-node src/main.ts\"",
"test": "jest --detectOpenHandles",
"test:watch": "jest --watch --detectOpenHandles",
"test:coverage": "jest --detectOpenHandles --coverage",
Expand Down
184 changes: 184 additions & 0 deletions processor/src/public/checkout.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Amazon Pay Checkout</title>
</head>

<body>
<div id="amazonpay_order-container"></div>

<script>
// Extract query parameters from the URL
function getQueryParam(param) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(param);
}

const sessionId = getQueryParam('sessionId');
const amazonCheckoutSessionId = getQueryParam('amazonCheckoutSessionId');
const step = getQueryParam('step');

const baseUrl = window.location.origin + window.location.pathname;

if (!sessionId || !amazonCheckoutSessionId) {
console.error('Amazon Checkout Session ID or session id is missing in the URL parameters.');
}

fetch(window.location.origin + "/sessions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Session-Id": sessionId,
},
body: JSON.stringify({}),
})
.then((res) => res.json())
.then(async (data) => {
console.log(data)

// Adyen configuration
const configuration = {
onPaymentCompleted: () => {
console.info("payment completed", result.resultCode);
},
onPaymentFailed: () => {
console.info("payment failed", result.resultCode);
},
onError: (error, component) => {
if (error.name === "CANCEL") {
console.info("shopper canceled the payment attempt");
component.setStatus("ready");
} else {
console.error(error.name, error.message, error.stack, component);
}
},
onSubmit: async (state, component, actions) => {
component.setStatus('loading')
console.log('clicked')
try {
component.setStatus('ready')
const reqData = {
...state.data,
channel: "Web",
paymentReference: data.paymentReference,
};
const response = await fetch(window.location.origin + "/payments", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Session-Id": sessionId,
},
body: JSON.stringify(reqData),
});
const res = await response.json();
if (res.action) {
component.handleAction(res.action);
} else {
if (res.resultCode === "Authorised" || res.resultCode === "Pending") {
component.setStatus("success");
} else {
component.setStatus("error");
}
}

actions.resolve({
resultCode: data.resultCode,
action: data.action,
});
} catch (e) {
console.log("Payment aborted by client");
component.setStatus("ready");
actions.reject(e);
}
},
onAdditionalDetails: async (
state,
component,
actions
) => {
try {
const requestData = {
...state.data,
paymentReference: data.paymentReference,
};
const url = window.location.origin.endsWith("/")
? `${window.location.origin}payments/details`
: `${window.location.origin}/payments/details`;

const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Session-Id": sessionId,
},
body: JSON.stringify(requestData),
});
const data = await response.json();
if (data.resultCode === "Authorised" || data.resultCode === "Pending") {
component.setStatus("success");
} else {
component.setStatus("error");
}
actions.resolve({ resultCode: data.resultCode });
} catch (e) {
console.error("Not able to submit the payment details", e);
component.setStatus("ready");
actions.reject();
}
},
analytics: {
enabled: true,
},

session: {
id: data.sessionData.id,
sessionData: data.sessionData.sessionData,
},
environment: '{{ENVIRONMENT}}',
clientKey: '{{ADYEN_CLIENT_KEY}}',
countryCode: 'DE'
};

console.log(configuration)

const { AdyenCheckout, AmazonPay } = window.AdyenWeb;

const checkout = await AdyenCheckout(configuration);

if (step === 'review') {
// TODO; implement loader while waiting for component to mount
const amazonComponent = new AmazonPay(checkout, {
amazonCheckoutSessionId,
returnUrl: baseUrl+'?step=result&&sessionId='+sessionId, // create a function to do this manual task, to avoid errors
showChangePaymentDetailsButton: true,
}).mount('#amazonpay_order-container');

} else if (step === 'result') {
// TODO; implement loader while waiting for component to mount
const amazonComponent = new AmazonPay(checkout, {
amazonCheckoutSessionId,
showOrderButton: false,
}).mount('#amazonpay_order-container');

amazonComponent.submit()
}
})
.catch((error) => {
console.error('Error fetching session:', error);
});

// Get sessionId and returnUrl from URL query parameters
console.log(amazonCheckoutSessionId)
</script>

<script src="https://checkoutshopper-test.cdn.adyen.com/checkoutshopper/sdk/6.0.0/adyen.js"
integrity="sha384-GDA6txYXS6ka6zCgDtLmgI80TQMlYST32KjDtdiyFi/k/zp9rXP64qbziIXVOI5h"
crossorigin="anonymous"></script>

<link rel="stylesheet"
href="https://checkoutshopper-test.cdn.adyen.com/checkoutshopper/sdk/6.0.0/adyen.css"
integrity="sha384-Gngchfiq4JxdVPMOwrUaDK70raLnMJ7IgBKi2OE0VSlbUeHysN7Mwd4aHREEvEAw"
crossorigin="anonymous">
</body>
48 changes: 48 additions & 0 deletions processor/src/routes/adyen-payment.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ import {
} from '../dtos/adyen-payment.dto';
import { AdyenPaymentService } from '../services/adyen-payment.service';
import { HmacAuthHook } from '../libs/fastify/hooks/hmac-auth.hook';
import path from 'node:path';
import fastifyStatic from '@fastify/static';
import { getConfig } from '../config/config';
import { promisify } from 'node:util';
import { readFile } from 'fs';

type PaymentRoutesOptions = {
paymentService: AdyenPaymentService;
Expand All @@ -31,6 +36,14 @@ export const adyenPaymentRoutes = async (
fastify: FastifyInstance,
opts: FastifyPluginOptions & PaymentRoutesOptions,
) => {
// Serve static files (HTML, CSS, JS)
fastify.register(fastifyStatic, {
root: path.join(__dirname, 'public'),
prefix: '/public/',
});

const readFileAsync = promisify(readFile);

fastify.post<{ Body: PaymentMethodsRequestDTO; Reply: PaymentMethodsResponseDTO }>(
'/payment-methods',
{
Expand Down Expand Up @@ -90,6 +103,39 @@ export const adyenPaymentRoutes = async (
},
);

fastify.get<{
Reply: string;
Querystring: {
paymentReference: string;
redirectResult?: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
};
}>(
'/payments/amazonpay',
{
preHandler: [],
},
async (request, reply) => {
//HINT: add check here for amazon session ID and return a html here
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const queryParams = request.query as any;

if (queryParams.amazonCheckoutSessionId) {
const filePath = path.join(__dirname, '../public/checkout.html');
const fileContent = await readFileAsync(filePath, 'utf8');

// Inject the environment variable into the HTML content
const htmlWithEnv = fileContent
.replace('{{ADYEN_CLIENT_KEY}}', getConfig().adyenClientKey)
.replace('{{ENVIRONMENT}}', getConfig().adyenEnvironment);
return reply.type('text/html').send(htmlWithEnv);
}

return reply.send('missing query parameters');
},
);

fastify.get<{
Reply: ConfirmPaymentResponseDTO;
Querystring: {
Expand All @@ -104,8 +150,10 @@ export const adyenPaymentRoutes = async (
preHandler: [opts.sessionQueryParamAuthHook.authenticate()],
},
async (request, reply) => {
//HINT: add check here for amazon session ID and return a html here
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const queryParams = request.query as any;

const res = await opts.paymentService.confirmPayment({
data: {
details: {
Expand Down
Loading
Loading