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

Support for Klarna payment method #39

Merged
merged 6 commits into from
Mar 2, 2025
Merged

Support for Klarna payment method #39

merged 6 commits into from
Mar 2, 2025

Conversation

joamag
Copy link
Contributor

@joamag joamag commented Mar 2, 2025

Related to https://github.com/hivesolutions/ustore-neo/issues/182

This pull request introduces support for Klarna payments via Stripe in the src/budy/models/order.py file. The most important changes include the addition of new methods to handle Klarna payments and modifications to existing methods to accommodate the new payment method.

Klarna Payment Integration:

  • Added _pay_stripe_klarna method to handle the creation of Klarna payment intents and generate the payment secret URL.
  • Added _end_pay_stripe_klarna method to process the Klarna payment completion, verifying the charge status and capture status.

Documentation Updates:

  • Updated the docstring of _end_pay_stripe_sca method to reflect changes in the payment data description, specifically mentioning URL redirection instead of Webhook events.

Summary by CodeRabbit

  • New Features
    • Added support for processing payments through Klarna, providing an additional, secure payment option at checkout.
  • Documentation
    • Updated user-oriented release notes to clearly describe the new Klarna payment method integration.

@joamag joamag added the enhancement New feature or request label Mar 2, 2025
@joamag joamag self-assigned this Mar 2, 2025
Copy link

coderabbitai bot commented Mar 2, 2025

Warning

Rate limit exceeded

@joamag has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 25 minutes and 29 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between e283a74 and cd770b5.

📒 Files selected for processing (1)
  • src/budy/models/order.py (3 hunks)

Walkthrough

The changes add two new methods, _pay_stripe_klarna and _end_pay_stripe_klarna, to the Order class in src/budy/models/order.py. These methods integrate Klarna payments with the Stripe API by handling payment intent creation, data updates, and finalizing the payment process through charge validation. A docstring update in the _end_pay_stripe_sca method clarifies the redirection flow from Stripe and the role of payment_data.

Changes

File Change Summary
src/budy/models/order.py Added _pay_stripe_klarna and _end_pay_stripe_klarna for handling Klarna payments via the Stripe API; updated docstring for _end_pay_stripe_sca.
CHANGELOG.md Added entry for support of Stripe Klarna payment method, replacing placeholder with descriptive line.

Sequence Diagram(s)

sequenceDiagram
    participant Order
    participant StripeAPI
    participant PaymentData
    Order->>PaymentData: Retrieve payment URLs and metadata
    Order->>StripeAPI: Create payment intent with parameters
    StripeAPI-->>Order: Return client secret
    Order->>PaymentData: Update with payment secret URL
Loading
sequenceDiagram
    participant Order
    participant StripeAPI
    participant PaymentData
    Order->>PaymentData: Retrieve payment identifier
    Order->>StripeAPI: List charges for identifier
    StripeAPI-->>Order: Return charge details
    Order->>Order: Validate charge status and capture state
    Order-->>PaymentData: Return True if payment is successful
Loading

Poem

I hop through code with joyful flair,
New paths for payments glide through the air.
Klarna meets Stripe in a seamless dance,
As charges and intents join by chance.
This bunny leaps with a debug delight,
Celebrating changes that shine so bright.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 docstrings to generate docstrings for 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

@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: 1

🔭 Outside diff range comments (2)
src/budy/models/order.py (2)

399-399: 🛠️ Refactor suggestion

Update default payment providers to include stripe_klarna

Since you've added Klarna as a payment method, you should update the default payment providers list to include "stripe_klarna".

        return appier.conf(
            "BUDY_PAYMENT_PROVIDERS",
-            ["stripe", "easypay_v2", "paypal", "stripe_sca"],
+            ["stripe", "easypay_v2", "paypal", "stripe_sca", "stripe_klarna"],
            cast=list,
        )

427-428: 🛠️ Refactor suggestion

Add Klarna payment method to the class methods

You need to add a method to expose Klarna as an available payment method.

    @classmethod
    def _pmethods_stripe_sca(cls):
        return ("stripe_sca",)
+
+    @classmethod
+    def _pmethods_stripe_klarna(cls):
+        return ("stripe_klarna",)
🧹 Nitpick comments (4)
src/budy/models/order.py (4)

1964-2004: Add a docstring to explain the Klarna payment process

This method handles Klarna payment initiation through Stripe, but it lacks a docstring explaining its purpose and workflow. Consider adding a descriptive docstring similar to the one in _pay_stripe_sca to improve maintainability.

def _pay_stripe_klarna(self, payment_data):
+    """
+    Starts the payment process for the current order using the
+    Stripe Klarna payment method. This method creates a payment
+    intent with Klarna as the payment method type and generates
+    a payment secret URL that includes the intent's client secret
+    and return URL.
+
+    The payment process is as follows:
+    1. The customer is redirected to the Stripe Klarna payment page.
+    2. The customer confirms the payment through Klarna's interface.
+    3. The customer is redirected back to the return URL with the
+       payment result.
+
+    :type payment_data: dict
+    :param payment_data: The payment data received that is going to be used
+    to control the payment process.
+    :rtype: String
+    :return: The payment (secret) URL for the Stripe Klarna payment page.
+    """

2128-2141: Add a docstring to explain the Klarna payment completion process

Similar to the _pay_stripe_klarna method, this method lacks a docstring explaining its purpose and workflow. Consider adding a descriptive docstring to improve maintainability.

def _end_pay_stripe_klarna(self, payment_data):
+    """
+    Finalizes the payment process for the current order using the
+    Stripe Klarna payment method. This method is called after the
+    customer has completed the Klarna payment flow and been redirected
+    back to the application.
+
+    The method verifies that the payment was successful by checking
+    the charge status and capture state.
+
+    :type payment_data: dict
+    :param payment_data: The payment data containing the payment identifier
+    and other relevant information.
+    :rtype: bool
+    :return: True if the payment was successfully processed, False otherwise.
+    """

2132-2140: Consider adding error handling for Klarna-specific error cases

The current implementation checks for basic charge status, but you might want to add error handling for Klarna-specific error cases or status codes to provide more descriptive error messages to users.


1974-1976: Add more Klarna payment parameters for better user experience

Consider adding more Klarna-specific payment parameters such as payment_category and custom_payment_methods to optimize the checkout experience.

            payment_method_types=["klarna"],
-            payment_method_options=dict(klarna=dict(preferred_locale="en-GB")),
+            payment_method_options=dict(
+                klarna=dict(
+                    preferred_locale="en-GB",
+                    payment_category="pay_later",
+                    custom_payment_methods=["pay_in_30_days", "instalments"]
+                )
+            ),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2f47b44 and 1369742.

📒 Files selected for processing (1)
  • src/budy/models/order.py (3 hunks)
🔇 Additional comments (2)
src/budy/models/order.py (2)

2082-2094: Good docstring update with clear explanation

The docstring update clearly explains that the method is called upon URL redirection from Stripe rather than a webhook event, which aligns with how the payment flow actually works.


1975-1976:

❓ Verification inconclusive

Verify Klarna supported locales

The preferred locale is hardcoded to "en-GB". Consider making this configurable via application settings to support different markets where Klarna operates.


🏁 Script executed:

#!/bin/bash
# Check Stripe API documentation for supported Klarna locales
curl -s https://stripe.com/docs/api/payment_intents/create | grep -A 10 "klarna\[preferred_locale\]"

Length of output: 102


Below is a revised review comment. Since the Stripe docs query returned no clear evidence on supported Klarna locales and we haven't verified anywhere in the codebase that this value is externally configurable, please manually double-check both the Stripe integration and any related configuration settings to ensure that hardcoding "en-GB" is appropriate for your supported markets.

Action: Confirm and Externalize Klarna Locale

  • The current setting of preferred_locale="en-GB" in src/budy/models/order.py (lines 1975–1976) remains hardcoded.
  • Verify via Stripe’s Klarna documentation and/or your integration tests that "en-GB" is indeed the intended default.
  • Consider updating the code to read the locale from a configuration source (e.g., application settings) so that it can adapt to other markets.

Please review the integration and configuration to determine if this change is required.

appier.quote(secret),
appier.quote(return_url),
)
print(secret)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove debug print statement

The print statement is debugging code that shouldn't be included in production.

-        print(secret)
📝 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
print(secret)

Copy link

@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: 0

🧹 Nitpick comments (1)
CHANGELOG.md (1)

12-12: Changelog Entry Clarity and Traceability

The new entry clearly documents the addition of Stripe Klarna payment support as introduced in this PR. For enhanced traceability, consider adding a reference to the associated issue (e.g. "Resolves #182") if that fits your changelog style.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1369742 and e283a74.

📒 Files selected for processing (1)
  • CHANGELOG.md (1 hunks)

@joamag joamag merged commit 42a346b into master Mar 2, 2025
28 checks passed
@joamag joamag deleted the feat/klarna branch March 2, 2025 22:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant