import Inject, { RegisterSingleton } from "@entity-access/entity-access/dist/di/di.js"; import { StoreJournal } from "../../../model/entities/StoreJournal.js"; import StorePaymentAttempt from "../../../model/entities/StorePaymentAttempt.js"; import StorePaymentGateway from "../../../model/entities/StorePaymentGateway.js"; import EncryptionService from "../../encryption/EncryptionService.js"; import LedgerPaymentGateway from "../LedgerPaymentGateway.js"; import SocialMailContext from "../../../model/SocialMailContext.js"; import { CaptureStatus, CheckoutPaymentIntent, Client, Environment, OrdersController, OrderStatus, PayeePaymentMethodPreference, PaypalExperienceLandingPage, PaypalExperienceUserAction, ConsoleLogger, LogLevel} from "@paypal/paypal-server-sdk"; import TimedCache from "@entity-access/entity-access/dist/common/cache/TimedCache.js"; import ServerLogger from "@entity-access/server-pages/dist/core/ServerLogger.js"; import EntityAccessError from "@entity-access/entity-access/dist/common/EntityAccessError.js"; @RegisterSingleton class PaypalClientCache { cache = new TimedCache(); @Inject ecs: EncryptionService; getClient(gateway: StorePaymentGateway) { return this.cache.getOrCreate(gateway.accountID, gateway, (k, p) => { const secret = this.ecs.secure.decrypt(p.encryptedSecret); return new Client({ environment: gateway.sandbox ? Environment.Sandbox : Environment.Production, logging: { logger: new ConsoleLogger(), logLevel: LogLevel.Debug }, clientCredentialsAuthCredentials: { oAuthClientId: gateway.clientID, oAuthClientSecret: secret } }); }); } } export default class extends LedgerPaymentGateway { @Inject ecs: EncryptionService; @Inject pc: PaypalClientCache; @Inject db: SocialMailContext; async createPayment(host: string, gateway: StorePaymentGateway, order: StoreJournal, pa: StorePaymentAttempt) { const pID = this.ecs.general.encrypt(pa.attemptID.toString()); const items = await this.db.storeJournalLineItems.where(order, (x, p) => x.journalID === p.journalID) .include((x) => x.itemPrice.storeItem) .toArray(); const client = this.pc.getClient(gateway); const { emailAddress: { emailAddress: emailAddress}} = await this.db.storeAccountEmails .where(order, (x, p) => x.accountID === p.buyerID) .include((x) => x.emailAddress) .first(); const orders = new OrdersController(client); const currencyCode = items[0].itemPrice.currency; const returnUrl = `https://${host}/store/checkout-callback/${pID}`; const cancelUrl = `https://${host}/store/checkout-callback/${pID}`; const pr = await orders.createOrder({ body: { intent: CheckoutPaymentIntent.Capture, paymentSource: { paypal: { experienceContext: { paymentMethodPreference: PayeePaymentMethodPreference.ImmediatePaymentRequired, brandName: host, landingPage: PaypalExperienceLandingPage.NoPreference, userAction: PaypalExperienceUserAction.PayNow, returnUrl, cancelUrl, }, emailAddress } }, // applicationContext: { // brandName: host, // paymentMethod: { // payeePreferred: PayeePaymentMethodPreference.Unrestricted, // }, // landingPage: OrderApplicationContextLandingPage.Billing, // userAction: OrderApplicationContextUserAction.PayNow, // returnUrl, // cancelUrl, // }, purchaseUnits: [{ invoiceId: `${order.journalID}`, referenceId: `${order.journalID}`, amount: { currencyCode, value: order.total.toString(2), breakdown: { itemTotal: { currencyCode, value: order.total.toString(2) } } }, items: items.map((x) => ({ name: x.item.name, quantity: Number(`${x.quantity || 1}`).toFixed(0), currency: x.itemPrice.currency, unitAmount: { currencyCode, value: (Number(x.total) / x.quantity).toFixed(2) }, })) }] } }); const link = pr.result.links.find((x) => x.rel === "payer-action"); pa.externalID = pr.result.id; await this.db.storePaymentAttempts.statements.update({ externalID: pa.externalID }, { attemptID: pa.attemptID }); return { url: link.href }; // return Content.html( // // Preparing Paypal Order // // // // // ); } async getStatus(pa: StorePaymentAttempt) { const { gateway, externalID: id } = pa; if (!id) { return "failed"; } try { const client = this.pc.getClient(gateway); const oc = new OrdersController(client); let pr = await oc.getOrder({ id }); if (pr.result.status === OrderStatus.Approved) { // let us capture... pr = await oc.captureOrder({ id }); } if(pr.result ?.purchaseUnits .every((x) => x.payments?.captures .every((c) => c.status === CaptureStatus.Completed))) { return "paid"; } return "failed"; } catch (error) { ServerLogger.error(error); return null; } } async refund(pa: StorePaymentAttempt) { throw new EntityAccessError("Not implemented"); } }