Skip to content

Commit

Permalink
tmp
Browse files Browse the repository at this point in the history
  • Loading branch information
silenaker committed Aug 13, 2024
1 parent 781ca23 commit 9628942
Show file tree
Hide file tree
Showing 12 changed files with 125 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export * from "./create-line-item-adjustments"
export * from "./create-line-items"
export * from "./create-order-from-cart"
export * from "./create-shipping-method-adjustments"
export * from "./create-payment-collection"
export * from "./find-one-or-any-region"
export * from "./find-or-create-customer"
export * from "./find-sales-channel"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ interface StepInput {
provider_id: string
amount: BigNumberInput
currency_code: string
provider_token?: string
context?: PaymentProviderContext
data?: Record<string, unknown>
}
Expand All @@ -27,6 +28,7 @@ export const createPaymentSessionStep = createStep(
input.payment_collection_id,
{
provider_id: input.provider_id,
provider_token: input.provider_token,
currency_code: input.currency_code,
amount: input.amount,
data: input.data ?? {},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { PaymentProviderContext, PaymentSessionDTO } from "@medusajs/types"
import { PaymentSessionStatus } from "@medusajs/utils"
import {
WorkflowData,
createWorkflow,
Expand All @@ -12,8 +13,10 @@ import { deletePaymentSessionsWorkflow } from "./delete-payment-sessions"
interface WorkflowInput {
payment_collection_id: string
provider_id: string
provider_token?: string
data?: Record<string, unknown>
context?: PaymentProviderContext
amount?: number
}

export const createPaymentSessionsWorkflowId = "create-payment-sessions"
Expand All @@ -22,20 +25,36 @@ export const createPaymentSessionsWorkflow = createWorkflow(
(input: WorkflowData<WorkflowInput>): WorkflowData<PaymentSessionDTO> => {
const paymentCollection = useRemoteQueryStep({
entry_point: "payment_collection",
fields: ["id", "amount", "currency_code", "payment_sessions.*"],
fields: [
"id",
"amount",
"authorized_amount",
"refunded_amount",
"currency_code",
"payment_sessions.*",
],
variables: { id: input.payment_collection_id },
list: false,
})

const paymentSessionInput = transform(
{ paymentCollection, input },
(data) => {
const authorizedAmount = data.paymentCollection.authorized_amount || 0
const refundedAmount = data.paymentCollection.refunded_amount || 0
const remainingAmount =
data.paymentCollection.amount - authorizedAmount + refundedAmount

return {
payment_collection_id: data.input.payment_collection_id,
provider_id: data.input.provider_id,
provider_token: data.input.provider_token,
data: data.input.data,
context: data.input.context,
amount: data.paymentCollection.amount,
amount: Math.min(
data.input.amount || remainingAmount,
remainingAmount
),
currency_code: data.paymentCollection.currency_code,
}
}
Expand All @@ -46,15 +65,14 @@ export const createPaymentSessionsWorkflow = createWorkflow(
(data) => {
return {
ids:
data.paymentCollection?.payment_sessions?.map((ps) => ps.id) || [],
data.paymentCollection?.payment_sessions
?.filter((ps) => ps.status !== PaymentSessionStatus.AUTHORIZED)
?.map((ps) => ps.id) || [],
}
}
)

// Note: We are deleting an existing active session before creating a new one
// for a payment collection as we don't support split payments at the moment.
// When we are ready to accept split payments, this along with other workflows
// need to be handled correctly
// Note: We are deleting all existing non-authorized session before creating a new one
const [created] = parallelize(
createPaymentSessionStep(paymentSessionInput),
deletePaymentSessionsWorkflow.runAsStep({
Expand Down
16 changes: 16 additions & 0 deletions packages/core/js-sdk/src/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,22 @@ export class Store {
query,
})
},

addPaymentSession: async (
paymentCollectionId: string,
body: Record<string, any>,
query?: SelectParams,
headers?: ClientHeaders
) => {
return this.client.fetch<{
payment_collection: HttpTypes.StorePaymentCollection
}>(`/store/payment-collections/${paymentCollectionId}/payment-sessions`, {
method: "POST",
headers,
body,
query,
})
},
}

public order = {
Expand Down
5 changes: 5 additions & 0 deletions packages/core/types/src/payment/mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,11 @@ export interface CreatePaymentSessionDTO {
*/
provider_id: string

/**
* The provider's payment method token
*/
provider_token?: string

/**
* The ISO 3 character currency code of the payment session.
*/
Expand Down
27 changes: 26 additions & 1 deletion packages/core/types/src/payment/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,20 @@ export type PaymentProviderContext = {
email?: string

/**
* The ID of payment session the provider payment is associated with.
* The associated payment session's ID.
*/
session_id?: string

/**
* The associated cart's ID.
*/
cart_id?: string

/**
* The associated order's ID.
*/
order_id?: string

/**
* The customer associated with this payment.
*/
Expand Down Expand Up @@ -76,6 +86,11 @@ export type CreatePaymentProviderSession = {
* The ISO 3 character currency code.
*/
currency_code: string

/*
* The payment method token
*/
token?: string
}

/**
Expand Down Expand Up @@ -184,6 +199,16 @@ export type WebhookActionData = {
*/
session_id: string

/**
* The associated cart's ID.
*/
cart_id: string

/**
* The associated order's ID.
*/
order_id: string

/**
* The amount to be captured or authorized (based on the action's type.)
*/
Expand Down
15 changes: 8 additions & 7 deletions packages/medusa/src/api/store/orders/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { getOrderDetailWorkflow } from "@medusajs/core-flows"
import { MedusaRequest, MedusaResponse } from "../../../../types/routing"
import { refetchOrder } from "../helpers"
import { StoreGetOrdersParamsType } from "../validators"

// TODO: Do we want to apply some sort of authentication here? My suggestion is that we do
export const GET = async (
req: MedusaRequest<StoreGetOrdersParamsType>,
res: MedusaResponse
) => {
const order = await refetchOrder(
req.params.id,
req.scope,
req.remoteQueryConfig.fields
)
const { result } = await getOrderDetailWorkflow(req.scope).run({
input: {
fields: req.remoteQueryConfig.fields,
order_id: req.params.id,
},
})

res.json({ order })
res.json({ order: result })
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const POST = async (
res: MedusaResponse
) => {
const collectionId = req.params.id
const { context = {}, data, provider_id } = req.body
const { context = {}, data, provider_id, amount } = req.body

// If the customer is logged in, we auto-assign them to the payment collection
if (req.auth_context?.actor_id) {
Expand All @@ -21,7 +21,8 @@ export const POST = async (
}
const workflowInput = {
payment_collection_id: collectionId,
provider_id: provider_id,
provider_id,
amount,
data,
context,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export const StoreCreatePaymentSession = z
provider_id: z.string(),
context: z.record(z.unknown()).optional(),
data: z.record(z.unknown()).optional(),
amount: z.number().optional(),
})
.strict()

Expand Down
10 changes: 10 additions & 0 deletions packages/modules/payment/src/services/payment-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ export default class PaymentModuleService
context: { ...input.context, session_id: paymentSession.id },
amount: input.amount,
currency_code: input.currency_code,
token: input.provider_token,
})

paymentSession = (
Expand Down Expand Up @@ -862,6 +863,15 @@ export default class PaymentModuleService
{},
sharedContext
)

if (event.data.order_id && !event.data.cart_id) {
await this.authorizePaymentSession(
event.data.session_id,
{},
sharedContext
)
}

if (payment && !payment.captured_at) {
await this.capturePayment(
{ payment_id: payment.id, amount: event.data.amount },
Expand Down
27 changes: 22 additions & 5 deletions packages/modules/providers/payment-stripe/src/core/stripe-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,9 @@ abstract class StripeBase extends AbstractPaymentProvider<StripeOptions> {
input: CreatePaymentProviderSession
): Promise<PaymentProviderError | PaymentProviderSessionResponse> {
const intentRequestData = this.getPaymentIntentOptions()
const { email, extra, session_id, customer } = input.context
const { currency_code, amount } = input
const { email, extra, session_id, cart_id, order_id, customer } =
input.context
const { currency_code, amount, token } = input

const description = (extra?.payment_description ??
this.options_?.paymentDescription) as string
Expand All @@ -120,13 +121,23 @@ abstract class StripeBase extends AbstractPaymentProvider<StripeOptions> {
description,
amount: getSmallestUnit(amount, currency_code),
currency: currency_code,
metadata: { session_id: session_id! },
payment_method: token,
confirm: !!token,
metadata: {
session_id: session_id!,
cart_id: cart_id as string | null,
order_id: order_id as string | null,
},
capture_method: this.options_.capture ? "automatic" : "manual",
...intentRequestData,
}

if (this.options_?.automaticPaymentMethods) {
intentRequest.automatic_payment_methods = { enabled: true }
const automaticPaymentMethods = this.options_?.automaticPaymentMethods
if (automaticPaymentMethods) {
intentRequest.automatic_payment_methods =
typeof automaticPaymentMethods === "boolean"
? { enabled: true }
: automaticPaymentMethods
}

if (customer?.metadata?.stripe_id) {
Expand Down Expand Up @@ -330,6 +341,8 @@ abstract class StripeBase extends AbstractPaymentProvider<StripeOptions> {
action: PaymentActions.AUTHORIZED,
data: {
session_id: intent.metadata.session_id,
cart_id: intent.metadata.cart_id,
order_id: intent.metadata.order_id,
amount: getAmountFromSmallestUnit(
intent.amount_capturable,
currency
Expand All @@ -341,6 +354,8 @@ abstract class StripeBase extends AbstractPaymentProvider<StripeOptions> {
action: PaymentActions.SUCCESSFUL,
data: {
session_id: intent.metadata.session_id,
cart_id: intent.metadata.cart_id,
order_id: intent.metadata.order_id,
amount: getAmountFromSmallestUnit(intent.amount_received, currency),
},
}
Expand All @@ -349,6 +364,8 @@ abstract class StripeBase extends AbstractPaymentProvider<StripeOptions> {
action: PaymentActions.FAILED,
data: {
session_id: intent.metadata.session_id,
cart_id: intent.metadata.cart_id,
order_id: intent.metadata.order_id,
amount: getAmountFromSmallestUnit(intent.amount, currency),
},
}
Expand Down
8 changes: 6 additions & 2 deletions packages/modules/providers/payment-stripe/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import Stripe from "stripe"

export interface StripeOptions {
/**
* The API key for the Stripe account
Expand All @@ -12,9 +14,11 @@ export interface StripeOptions {
*/
capture?: boolean
/**
* set `automatic_payment_methods` on the intent request to `{ enabled: true }`
* set `automatic_payment_methods` on the intent request
*/
automaticPaymentMethods?: boolean
automaticPaymentMethods?:
| boolean
| Stripe.PaymentIntentCreateParams.AutomaticPaymentMethods
/**
* Set a default description on the intent if the context does not provide one
*/
Expand Down

0 comments on commit 9628942

Please sign in to comment.