如何使用Stripe React组件和Django重定向用户

huangapple go评论73阅读模式
英文:

how redirect user with stripe react component and django

问题

I understand that you want to redirect your user after a successful payment using Stripe in your Django and React application. Here are the parts of your provided content that I've translated into English:

Offers.js: ReactComponent by Stripe

<stripe-pricing-table 
   pricing-table-id="prctbl_<my_pricing_table_key>"
   publishable-key="pk_test_<my-stripe-public-key>"
   // user information for updating subscriptions in the Django model
   customer-email={`${info_user.info_user.email}`}
   client-reference-id={`${info_user.info_user.id}`}
 >
 </stripe-pricing-table>

views.py:

class StripeWebhookView(APIView):
    # ... (omitting some code)
    
    # here I try several things but not working currently (with redirect)
    class SuccessView(View):
        def get(self, request):
            return redirect('/success')

    class CancelView(View):
        def get(self, request):
            return render(request, 'cancel.html', {})

urls.py:

urlpatterns = [
    # it's ok !
    path('stripe-webhook', views.StripeWebhookView.as_view(), name='create-payment-intent'),
    # not in use currently
    path('success', views.SuccessView.as_view(), name='success'),
    path('cancel', views.CancelView.as_view(), name='cancel'),
]

models.py:

class Abonnement(models.Model):
    # ... (omitting some code)

In your provided content, you've created a SuccessView class in your Django views to handle successful payment redirection. It appears that you are using the redirect function to direct the user to the "/success" URL.

If the redirection is not working as expected, you should make sure that the URL patterns are correctly configured in your Django application. Additionally, you need to ensure that your React component, specifically the stripe-pricing-table, handles the response from the Stripe payment correctly and triggers the redirection.

If you are encountering issues with the Stripe component not triggering the redirect, you may need to review the Stripe documentation or seek assistance in Stripe's official support channels, as it may involve specific interactions with their React component.

英文:

I would like to redirect my user after he has made a payment (successful or failed) to a page automatically.

Currently, the payment is going well, the update is a success on stripe and I manage to retrieve the necessary information with my django view.

However, after successful payment, no redirection takes place. There are several documentation but I can't find a way to do it with the react component proposed by stripe themselves.

How can I proceed?

here is my work

Offers.js : ReactComponent by Stripe

&lt;stripe-pricing-table 
   pricing-table-id=&quot;prctbl_&lt;my_pricing_table_key&gt;&quot;
   publishable-key=&quot;pk_test_&lt;my-stripe-public-key&gt;&quot;
   // user informations for update subscriptions django model
   customer-email={`${info_user.info_user.email}`}
   client-reference-id={`${info_user.info_user.id}`}
 &gt;
 &lt;/stripe-pricing-table&gt;

When I click on the subscribe button, everything is fine. the payment is made on stripe and I retrieve the information in my webhook with django

views.py

class StripeWebhookView(APIView):
    permission_classes = []
    authentication_classes = []
    helpers = AbonnementHelpers
    updating = UpdateAbonnementHelpers
    
    def post(self, request):
        payload = request.body
        sig_header = request.META[&#39;HTTP_STRIPE_SIGNATURE&#39;]
        endpoint_secret = STRIPE_WEBHOOK_SECRET
        # webhook
        try:
            event = stripe.Webhook.construct_event(
                payload, sig_header, endpoint_secret
            )
        except ValueError as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        except stripe.error.SignatureVerificationError as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # full session data recovery
        if event[&#39;type&#39;] == &#39;checkout.session.completed&#39;:
            info_event = self.helpers().stripe_event(event)
            user = UserAccount.objects.get(id=info_event[&#39;user_id&#39;])
            # check if user subscription exist in my database
            try:
                abo = Abonnement.objects.get(user=user)
                self.updating.update_abo(
                    abo=abo,
                    subscription_id=info_event[&#39;subscription_id&#39;],
                    num_facture=info_event[&#39;num_facture&#39;],
                    is_paid=info_event[&#39;is_paid&#39;],
                    expire_at=info_event[&#39;expire_at&#39;],
                    price=info_event[&#39;price&#39;],
                    abo_id=info_event[&#39;abonnement_id&#39;],
                    customer_id=info_event[&#39;customer_id&#39;],
                    plan=info_event[&#39;plan&#39;]
                )
            # if not exist, create the subscription with django model
            except ObjectDoesNotExist:
                abo = Abonnement(
                    user=user,
                    email=user.email,
                    stripe_subscription_id=info_event[&#39;subscription_id&#39;],
                    numero_facture=info_event[&#39;num_facture&#39;],
                    is_paid=info_event[&#39;is_paid&#39;],
                    abonne_jusquau=info_event[&#39;expire_at&#39;],
                    price=info_event[&#39;price&#39;],
                    abonnement_id=info_event[&#39;abonnement_id&#39;],
                    stripe_user_id=info_event[&#39;customer_id&#39;],
                    plan=info_event[&#39;plan&#39;]
                )
                abo.save()
            return Response(status=status.HTTP_200_OK)

        return Response(status=status.HTTP_200_OK)

# here i try several things but not working currently (with redirect)
class SuccessView(View):
    def get(self, request):
        return redirect(&#39;/success&#39;)


class CancelView(View):
    def get(self, request):
        return render(request, &#39;cancel.html&#39;, {})

And here are my affiliate url routes to my subscriptions app

urls.py

urlpatterns = [
    # it&#39;s ok !
    path(&#39;stripe-webhook&#39;, views.StripeWebhookView.as_view(), name=&#39;create-payment-intent&#39;),
    # not use currently
    path(&#39;success&#39;, views.SuccessView.as_view(), name=&#39;success&#39;),
    path(&#39;cancel&#39;, views.CancelView.as_view(), name=&#39;cancel&#39;),
]

models.py

class Abonnement(models.Model):
    user = models.OneToOneField(UserAccount, on_delete=models.CASCADE)
    email = models.EmailField(max_length=50, unique=True)
    stripe_subscription_id = models.CharField(max_length=255)
    is_paid = models.BooleanField(default=False)
    paye_le = models.DateTimeField(auto_now_add=True)
    abonne_jusquau = models.DateTimeField(blank=True)
    price = models.FloatField(default=0.0, blank=True)
    numero_facture = models.CharField(max_length=150, blank=True)
    abonnement_id = models.CharField(max_length=255)
    stripe_user_id = models.CharField(max_length=255)
    last_update = models.DateTimeField(blank=True, null=True)
    plan = models.CharField(max_length=15)

    def __str__(self):
        return f&quot;{self.user} {self.plan}&quot;

after the payment I get a page with "successful payment" but no redirect to apply and no possibility to return to the application. the URL looks like this:
https://checkout.stripe.com/c/pay/cs_test_b1m[...]ERl#fid[...]ICUl

[...] = sequence of several numbers and letters

what am I doing wrong? thanks for your help

答案1

得分: 3

要在成功付款后设置将用户重定向到您的应用程序,可以在仪表板中的定价表页面 中进行设置。您可以在每个价格上选择“不显示确认页面”以禁用显示Stripe的确认页面,并将返回URL设置为指向您的网站。

以下是您可以进行设置的屏幕截图:

如何使用Stripe React组件和Django重定向用户

英文:

To set up redirection to your application after successful payment, it can be done by setting in the pricing table page in Dashboard. You can select Don&#39;t show confirmation page in every price to disable showing Stripe's confirmation page and set the return URL to direct to your website.

Here's the screenshot of where you can set it up:

如何使用Stripe React组件和Django重定向用户

huangapple
  • 本文由 发表于 2023年2月19日 18:03:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定