Skip to content

Conversation

kkerti
Copy link
Contributor

@kkerti kkerti commented Jun 30, 2025

Description

In our app, we want to allow shop admins to make changes to customer orders which are no longer active. These changes might introduce the need to add additional payments to the order. In this case an order can be for example in the ArrangingAdditionalPayment state, and there we want to shift the payment to the customer.

Primarily we use the existing stripe payment plugin, which works perfectly in regular order flows. Looking at the implementation details, the existing StripeService code could be reused to support our, and possibly other vendure plugin developer's needs.

To do so, we just need to export the StripeService from the plugin.

In the example plugin code below, I show an example createCustomStripePaymentIntent mutation, where I use the StripeService intent creation with custom request context and order lookup.

import { StripeService } from "../../src/stripe/stripe.service";

@Resolver()
export class CustomStripeResolver {
    constructor(private stripeService: StripeService, private orderService: OrderService, private requestContextService: RequestContextService) {}

    @Mutation()
    @Allow(Permission.Owner)
    async createCustomStripePaymentIntent(@Ctx() ctx: RequestContext, @Args() args: {orderCode: string, channelToken: string}): Promise<string> {
        // By the orderCode we find the order where we assume additional payments are required.
        // If the order is not in the request's channel context, we can use other means to lookup the order.
        const order = await this.orderService.findOneByCode(ctx, args.orderCode);
        // The stripe webhook handler expects: channelToken, orderId, orderCode and languageCode
        // We can hijack those details, to support cross-channel payments and additional "non-active" order payments
        const customCtx = await this.requestContextService.create({
            apiType: 'shop',
            channelOrToken: args.channelToken,
            req: ctx.req
        });
        if(!order){
            throw new Error("No order")
        }
        return this.stripeService.createPaymentIntent(customCtx, order);
    }
}

@VendurePlugin({
    imports: [PluginCommonModule, StripePlugin],
    shopApiExtensions: {
            schema: gql`
                extend type Mutation {
                    createCustomStripePaymentIntent(orderCode: String, channelToken: String): String!
                }
            `,
        resolvers: [CustomStripeResolver],
    },
})
export class StripeServiceExportTestPlugin {}

The change itself is a one-liner, a single plugin export. The fixture ./stripe-service-export-test.plugin.ts and additional file changes are only there to explain what I am after.

Let me know if this change is acceptable and works with the codebase. Right now I'm using a patch-package fix to work around the missing export.

Breaking changes

No breaking change.

Screenshots

You can add screenshots here if applicable.

Checklist

📌 Always:

  • I have set a clear title
  • My PR is small and contains a single feature
  • I have checked my own PR

👍 Most of the time:

  • I have added or updated test cases
  • I have updated the README if needed

Summary by CodeRabbit

  • New Features

    • Introduced a custom GraphQL mutation to create Stripe payment intents, supporting cross-channel payments.
    • Added a new test plugin and mutation for custom Stripe payment intent creation in the test environment.
  • Improvements

    • Made the Stripe service available for import by other modules using the plugin.
  • Chores

    • Updated import paths and order for consistency and clarity.
    • Refined test setup to include new plugins and log additional payment intent creation.

Copy link
Contributor

coderabbitai bot commented Jun 30, 2025

Walkthrough

The changes introduce a new Vendure test plugin and related GraphQL mutation to facilitate custom Stripe payment intent creation, update test infrastructure to utilize this mutation, and adjust plugin exports for service accessibility. Additional modifications include import path corrections and code cleanup, without altering existing logic or control flow.

Changes

File(s) Change Summary
.../e2e/fixtures/stripe-checkout-test.plugin.ts Corrected import path for clientSecret and reordered imports from @nestjs/common.
.../e2e/fixtures/stripe-service-export-test.plugin.ts Added StripeServiceExportTestPlugin and CustomStripeResolver with a new mutation for custom Stripe payment intent creation.
.../e2e/payment-helpers.ts Added CREATE_CUSTOM_STRIPE_PAYMENT_INTENT GraphQL mutation constant.
.../e2e/stripe-dev-server.ts Registered new test plugins, imported new mutation, and executed/logged the custom Stripe payment intent mutation in test setup.
.../src/stripe/stripe.plugin.ts Removed unused import and added StripeService to plugin exports for external accessibility.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ShopAPI
    participant CustomStripeResolver
    participant OrderService
    participant RequestContextService
    participant StripeService

    Client->>ShopAPI: createCustomStripePaymentIntent(orderCode, channelToken)
    ShopAPI->>CustomStripeResolver: invoke mutation resolver
    CustomStripeResolver->>OrderService: findOneByCode(ctx, orderCode)
    OrderService-->>CustomStripeResolver: return Order or null
    alt Order found
        CustomStripeResolver->>RequestContextService: create({ channelOrToken: channelToken })
        RequestContextService-->>CustomStripeResolver: return customCtx
        CustomStripeResolver->>StripeService: createPaymentIntent(customCtx, order)
        StripeService-->>CustomStripeResolver: return paymentIntent
        CustomStripeResolver-->>ShopAPI: return paymentIntent
        ShopAPI-->>Client: return paymentIntent
    else Order not found
        CustomStripeResolver-->>ShopAPI: throw error
        ShopAPI-->>Client: error
    end
Loading

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-30T14_59_30_589Z-debug-0.log


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

vercel bot commented Jun 30, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
docs ✅ Ready (Inspect) Visit Preview Jun 30, 2025 2:59pm

Copy link

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 61bed48 and c67d9f4.

📒 Files selected for processing (5)
  • packages/payments-plugin/e2e/fixtures/stripe-checkout-test.plugin.ts (1 hunks)
  • packages/payments-plugin/e2e/fixtures/stripe-service-export-test.plugin.ts (1 hunks)
  • packages/payments-plugin/e2e/payment-helpers.ts (1 hunks)
  • packages/payments-plugin/e2e/stripe-dev-server.ts (3 hunks)
  • packages/payments-plugin/src/stripe/stripe.plugin.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/payments-plugin/e2e/stripe-dev-server.ts (3)
packages/payments-plugin/e2e/payment-helpers.ts (1)
  • CREATE_CUSTOM_STRIPE_PAYMENT_INTENT (232-236)
packages/core/src/config/logger/vendure-logger.ts (1)
  • Logger (136-204)
packages/payments-plugin/e2e/fixtures/stripe-service-export-test.plugin.ts (1)
  • createCustomStripePaymentIntent (27-45)
⏰ Context from checks skipped due to timeout of 90000ms (19)
  • GitHub Check: e2e tests (20.x, postgres)
  • GitHub Check: codegen / codegen
  • GitHub Check: e2e tests (22.x, mariadb)
  • GitHub Check: e2e tests (22.x, postgres)
  • GitHub Check: e2e tests (20.x, mariadb)
  • GitHub Check: e2e tests (22.x, mysql)
  • GitHub Check: e2e tests (20.x, mysql)
  • GitHub Check: e2e tests (22.x, sqljs)
  • GitHub Check: e2e tests (20.x, sqljs)
  • GitHub Check: unit tests (20.x)
  • GitHub Check: build (22.x)
  • GitHub Check: build (20.x)
  • GitHub Check: unit tests (22.x)
  • GitHub Check: publish_install (windows-latest, 22.x)
  • GitHub Check: publish_install (macos-latest, 22.x)
  • GitHub Check: publish_install (macos-latest, 20.x)
  • GitHub Check: publish_install (windows-latest, 20.x)
  • GitHub Check: publish_install (ubuntu-latest, 20.x)
  • GitHub Check: publish_install (ubuntu-latest, 22.x)
🔇 Additional comments (4)
packages/payments-plugin/src/stripe/stripe.plugin.ts (1)

200-200: LGTM! Clean implementation of the core feature.

The export of StripeService enables the desired functionality for custom payment flows while maintaining backward compatibility. This change directly addresses the PR objectives.

packages/payments-plugin/e2e/fixtures/stripe-checkout-test.plugin.ts (1)

2-2: LGTM! Import cleanup and path correction.

The import reordering and path correction are good housekeeping changes that maintain proper project structure.

Also applies to: 6-6

packages/payments-plugin/e2e/stripe-dev-server.ts (1)

20-21: LGTM! Proper test plugin integration.

The new test plugins are correctly imported and integrated into the test environment, enabling proper testing of the exported StripeService functionality.

Also applies to: 29-33, 53-53

packages/payments-plugin/e2e/fixtures/stripe-service-export-test.plugin.ts (1)

27-44: Excellent demonstration of the exported StripeService usage.

The resolver effectively showcases how to use the exported StripeService for custom payment flows, including:

  • Cross-channel payment support via custom request context
  • Flexible order lookup by code
  • Proper service injection and usage

This implementation aligns perfectly with the PR objectives and provides a valuable example for developers.

Comment on lines +232 to +236
export const CREATE_CUSTOM_STRIPE_PAYMENT_INTENT = gql`
mutation createCustomStripePaymentIntent {
createCustomStripePaymentIntent
}
`;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix argument mismatch in GraphQL mutation.

The mutation definition is missing the required arguments that the resolver expects. Based on the StripeServiceExportTestPlugin, the mutation should include orderCode and channelToken parameters.

Apply this fix to match the resolver implementation:

-export const CREATE_CUSTOM_STRIPE_PAYMENT_INTENT = gql`
-    mutation createCustomStripePaymentIntent {
-        createCustomStripePaymentIntent
-    }
-`;
+export const CREATE_CUSTOM_STRIPE_PAYMENT_INTENT = gql`
+    mutation createCustomStripePaymentIntent($orderCode: String!, $channelToken: String!) {
+        createCustomStripePaymentIntent(orderCode: $orderCode, channelToken: $channelToken)
+    }
+`;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const CREATE_CUSTOM_STRIPE_PAYMENT_INTENT = gql`
mutation createCustomStripePaymentIntent {
createCustomStripePaymentIntent
}
`;
export const CREATE_CUSTOM_STRIPE_PAYMENT_INTENT = gql`
mutation createCustomStripePaymentIntent($orderCode: String!, $channelToken: String!) {
createCustomStripePaymentIntent(orderCode: $orderCode, channelToken: $channelToken)
}
`;
🤖 Prompt for AI Agents
In packages/payments-plugin/e2e/payment-helpers.ts around lines 232 to 236, the
GraphQL mutation createCustomStripePaymentIntent is missing the required
arguments orderCode and channelToken that the resolver expects. Update the
mutation definition to include these parameters in the mutation signature and
pass them correctly in the mutation body to match the resolver implementation.

Comment on lines +108 to +111
// Showcasing the custom intent creation
const { createCustomStripePaymentIntent } = await shopClient.query(CREATE_CUSTOM_STRIPE_PAYMENT_INTENT);
Logger.debug('Result of createCustomStripePaymentIntent:', createCustomStripePaymentIntent);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix missing arguments in mutation call.

The mutation call is missing the required orderCode and channelToken arguments that the resolver expects. This will cause a runtime error.

Apply this fix to provide the required arguments:

-    // Showcasing the custom intent creation
-    const { createCustomStripePaymentIntent } = await shopClient.query(CREATE_CUSTOM_STRIPE_PAYMENT_INTENT);
-    Logger.debug('Result of createCustomStripePaymentIntent:', createCustomStripePaymentIntent);
+    // Showcasing the custom intent creation
+    const { createCustomStripePaymentIntent } = await shopClient.query(CREATE_CUSTOM_STRIPE_PAYMENT_INTENT, {
+        orderCode: 'T_1', // Use the order code from the test setup
+        channelToken: '__default_channel__', // Use the default channel token
+    });
+    Logger.debug('Result of createCustomStripePaymentIntent:', createCustomStripePaymentIntent);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Showcasing the custom intent creation
const { createCustomStripePaymentIntent } = await shopClient.query(CREATE_CUSTOM_STRIPE_PAYMENT_INTENT);
Logger.debug('Result of createCustomStripePaymentIntent:', createCustomStripePaymentIntent);
// Showcasing the custom intent creation
const { createCustomStripePaymentIntent } = await shopClient.query(CREATE_CUSTOM_STRIPE_PAYMENT_INTENT, {
orderCode: 'T_1', // Use the order code from the test setup
channelToken: '__default_channel__', // Use the default channel token
});
Logger.debug('Result of createCustomStripePaymentIntent:', createCustomStripePaymentIntent);
🤖 Prompt for AI Agents
In packages/payments-plugin/e2e/stripe-dev-server.ts around lines 108 to 111,
the mutation call to createCustomStripePaymentIntent is missing the required
orderCode and channelToken arguments expected by the resolver. Fix this by
passing an object with orderCode and channelToken properties as variables to the
shopClient.query call to ensure the mutation receives the necessary inputs and
avoids runtime errors.

Comment on lines +51 to +55
schema: gql`
extend type Mutation {
createCustomStripePaymentIntent(orderCode: String, channelToken: String): String!
}
`,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Make GraphQL arguments required and improve error handling.

The arguments should be required since the resolver logic depends on them, and the error handling could be more descriptive.

Apply these improvements:

-            extend type Mutation {
-                createCustomStripePaymentIntent(orderCode: String, channelToken: String): String!
-            }
+            extend type Mutation {
+                createCustomStripePaymentIntent(orderCode: String!, channelToken: String!): String!
+            }

Also improve error handling in the resolver:

-        if (!order) {
-            throw new Error('No order');
-        }
+        if (!order) {
+            throw new Error(`Order with code "${args.orderCode}" not found`);
+        }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/payments-plugin/e2e/fixtures/stripe-service-export-test.plugin.ts
around lines 51 to 55, the GraphQL mutation arguments orderCode and channelToken
are currently optional but should be required since the resolver depends on
them. Update the schema to make these arguments non-nullable by adding
exclamation marks. Additionally, enhance the resolver's error handling by
checking for the presence of these arguments explicitly and throwing descriptive
errors if they are missing, to improve clarity and debugging.

@michaelbromley michaelbromley merged commit 829ab2c into vendure-ecommerce:minor Jul 4, 2025
24 checks passed
@github-actions github-actions bot locked and limited conversation to collaborators Jul 4, 2025
@michaelbromley
Copy link
Member

Thanks for going the extra step of demonstrating usage & fixing up the existing server implementation 👍

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants