import Inject 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 LedgerPaymentGateway from "../LedgerPaymentGateway.js"; import SocialMailContext from "../../../model/SocialMailContext.js"; import * as stripe from "stripe"; import EncryptionService from "../../encryption/EncryptionService.js"; import EntityAccessError from "@entity-access/entity-access/dist/common/EntityAccessError.js"; export default class StripePaymentGateway extends LedgerPaymentGateway { @Inject db: SocialMailContext; @Inject ecs: EncryptionService; async createPayment(host: string, gateway: StorePaymentGateway, order: StoreJournal, pa: StorePaymentAttempt) { const s = this.getClient(gateway); // create order... const items = await this.db.storeJournalLineItems.where(order, (x, p) => x.journalID === p.journalID) .include((x) => x.itemPrice.storeItem) .toArray(); const { emailAddress: { emailAddress: customer_email}} = await this.db.storeAccountEmails .where(order, (x, p) => x.accountID === p.buyerID) .include((x) => x.emailAddress) .first(); const pID = this.ecs.general.encrypt(pa.attemptID.toString()); const redirectUrl = `https://${host}/store/checkout-callback/${pID}`; const { url , id } = await s.checkout.sessions.create({ success_url: redirectUrl, cancel_url: redirectUrl, metadata: { "order-id": order.journalID.toString() }, line_items: items.map((x) => ({ price_data: { currency: x.itemPrice.currency, unit_amount_decimal: ((Number(x.total) / x.quantity) * 100).toFixed(2), product_data: { name: x.itemPrice.storeItem.name, }, tax_behavior: "inclusive" }, quantity: Number(x.quantity).toFixed(0) as any })), mode: "payment", customer_email }); pa.externalID = id; await this.db.storePaymentAttempts.statements.update({ externalID: id }, { attemptID: pa.attemptID }); return { url }; } async getStatus(pa: StorePaymentAttempt) { const s = this.getClient(pa.gateway); const session = await s.checkout.sessions.retrieve(pa.externalID); switch(session.payment_status) { case "paid": case "no_payment_required": return "paid"; } return "failed"; } async refund(pa: StorePaymentAttempt) { throw new EntityAccessError("Not implemented"); } getClient(gateway: StorePaymentGateway) { const ds = this.ecs.secure.decrypt(gateway.encryptedSecret); const s = new stripe.Stripe(ds); return s; } }