简体   繁体   English

如何将Stripe支付网关与Django Oscar集成?

[英]How to integrate Stripe payments gateway with Django Oscar?

I am trying to integrate the Stripe payment gateway to Django oscar for an e-commerce site which sells physical goods like groceries online.I use python 3.6.3, Django 2.0, Django-oscar 1.6, stripe 1.82.2. 我正在尝试将Stripe支付网关集成到Django oscar,这是一个电子商务网站,在网上销售像杂货这样的实体商品。我使用的是python 3.6.3,Django 2.0,Django-oscar 1.6,条纹1.82.2。

Method 1 : 方法1

So I followed this link in django-oscar groups: 所以我在django-oscar组中关注了这个链接:

https://groups.google.com/forum/#!searchin/django-oscar/handle_payment$20override%7Csort:date/django-oscar/Cr8sBI0GBu0/PHRdXX2uFQAJ https://groups.google.com/forum/#!searchin/django-oscar/handle_payment$20override%7Csort:date/django-oscar/Cr8sBI0GBu0/PHRdXX2uFQAJ

I have signed up for a stripe account and used my publishable key and test key to configure stripe.The problem is, when I try to pay using the button provided with label "Pay with Card",it collects my card information and then when I click the button, it shows "Some money will be debited from the card" like in this image: Image of Preview page 我已经注册了一个条带帐户,并使用我的可发布密钥和测试密钥来配置条带。问题是,当我尝试使用带有“用卡支付”标签提供的按钮付款时,它会收集我的卡信息然后当我点击按钮,显示“将从卡中扣除一些钱”,如下图所示: 预览页面的图像

Then after I click the place order button,it shows me this: Image of confirmation page 然后在我点击下订单按钮后,它显示我: 确认页面的图像

Though I have paid using my card. 虽然我已经用我的卡付了钱。 I guess oscar doesn't seem to know that the payment has been done through stripe already?But I'm not sure how to solve this. 我猜奥斯卡似乎不知道支付已经通过条纹完成了吗?但我不知道如何解决这个问题。

Method 2 : I tried to use dj-stripe,found here: 方法2 :我尝试使用dj-stripe,在这里找到:

https://github.com/dj-stripe/dj-stripe https://github.com/dj-stripe/dj-stripe

But I read the whole documentation on https://dj-stripe.readthedocs.io/en/stable-1.0/ , it seems like I can use it only for products that need subscriptions, mine don't require subscribing and the docs for dj-stripe aren't fully complete. 但我在https://dj-stripe.readthedocs.io/en/stable-1.0/上阅读了整个文档,似乎我只能将它用于需要订阅的产品,我的不需要订阅和文档dj-stripe不完整。

I tried with the official django-oscar repo, the link is here: https://github.com/django-oscar/django-oscar-stripe , this repository is like five years old and I don't think it would be compatible to use with my version of Django oscar. 我尝试使用官方django-oscar repo,链接在这里: https//github.com/django-oscar/django-oscar-stripe ,这个存储库就像五年了,我认为它不兼容与我的Django oscar版本一起使用。

Method 3 : I tried using the stripe.js and elements and created my form to accept cards: 方法3 :我尝试使用stripe.js和elements并创建我的表单来接受卡片:

 < script src = "https://js.stripe.com/v3/" > < /script> < script > var stripe = Stripe('your_stripe_publishable_key'); var elements = stripe.elements(); // Custom styling can be passed to options when creating an Element. var style = { base: { color: '#32325d', lineHeight: '18px', fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: 'antialiased', fontSize: '20px', '::placeholder': { color: '#aab7c4' } }, invalid: { color: '#fa755a', iconColor: '#fa755a' } }; // Create an instance of the card Element. var card = elements.create('card', { style: style }); // Add an instance of the card Element into the `card-element` <div>. card.mount('#card-element'); card.addEventListener('change', function(event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } }); // Create a source or display an error when the form is submitted. var form = document.getElementById('payment-form'); form.addEventListener('submit', function(event) { event.preventDefault(); stripe.createSource(card).then(function(result) { if (result.error) { // Inform the user if there was an error var errorElement = document.getElementById('card-errors'); errorElement.textContent = result.error.message; } else { // Send the source to your server stripeSourceHandler(result.source); } }); }); function stripeSourceHandler(source) { // Insert the source ID into the form so it gets submitted to the server var form = document.getElementById('payment-form'); var hiddenInput = document.createElement('input'); var hiddenAmount = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeSource'); hiddenInput.setAttribute('value', source.id); form.appendChild(hiddenInput); hiddenAmount.setAttribute('type', 'hidden'); hiddenAmount.setAttribute('name', 'amt'); hiddenAmount.setAttribute('value', '{{ order_total.incl_tax|safe }}'); form.appendChild(hiddenAmount); // Submit the form form.submit(); } < /script> 
 <form action="/charge/" method="post" id="payment-form"> {% csrf_token % } <div class="form-row"> <label for="card-element"> Credit or debit card </label> <div id="card-element"> <!-- A Stripe Element will be inserted here. --> </div> <!-- Used to display Element errors. --> <div id="card-errors" role="alert"></div> </div> <br> <!--<hr>--> <button class="btn btn-primary">Pay Now</button> </form> 

And in my python views.py file I create a stripe charge and also sources. 在我的python views.py文件中,我创建了条带费用,也是源代码。

@csrf_exempt
def stripe_payment(request):
    user = request.user
    source_id = request.POST.get("stripeSource", None)

    amount = request.POST.get("amt", None)
    stripe.api_key = "your_test_key"
    customer = stripe.Customer.create(
        email=email,
        source=source_id,
    )
    # print("Customer ID: ", customer['id'])
    amt = float(amount) * 100
    # print("Amount:", int(amt))
    int_amt = int(amt)
    charge = stripe.Charge.create(
        amount=int_amt,
        currency='cad',
        customer=customer['id'],
        source=source_id,
    ) 

    return HttpResponseRedirect("/checkout/preview/")

Then I created a webhook in the stripe dashboard and linked it to my local url , every-time there is a response from stripe being sent through the web-hook, this url is hit. 然后我在条带仪表板中创建了一个webhook,并将其链接到我的本地URL,每次有条带的响应通过web-hook发送,这个url被击中。

@csrf_exempt
def demo_checkout(request):

    # Retrieve the request's body and parse it as JSON:
    event_json = json.dumps(json.loads(request.body), indent=4)
    # event_json = json.loads(request.body)

    # Do something with event_json
    print("Json event:", event_json)

    return HttpResponse(status=200)

As of now, I can track the various events or logs from my dashboard and the events like creating a customer, making a charge and the web-hook sending a response is working fine,but I can't figure out how can I complete the payment such that Django-oscar can also know that the payment is done and it doesn't show "No payment was required": Thank you page 截至目前,我可以从我的仪表板跟踪各种事件或日志,以及创建客户,收费以及发送响应的Web挂钩等事件正常工作,但我无法弄清楚如何完成付款,以便Django-oscar也知道付款已完成且未显示“无需付款”: 谢谢页面

I have tried all these methods,but it still doesn't work.I am open to using any other method which is suggested or an improvement to what I have done in any of the methods explained so far.I am new to django-oscar and an answer with some code and some explanation would be helpful. 我已经尝试了所有这些方法,但它仍然不起作用。我愿意使用任何其他方法建议或改进我迄今为止所解释的任何方法。我是django-oscar的新手一些代码和一些解释的答案将有所帮助。

I have found a way to integrate Stripe with Django Oscar, this is one of the easy ways to do it. 我找到了将Stripe与Django Oscar集成的方法,这是一种简单的方法。

  1. Create a stripe account first from here: https://stripe.com/ , you will get a publishable key and a secret key, you can view them after logging in into the stripe dashboard under Developers > API keys. 首先从这里创建一个条带帐户: https//stripe.com/ ,您将获得一个可发布的密钥和一个密钥,您可以在登录到开发人员> API密钥下的条带仪表板后查看它们。

  2. In your django oscar code side. 在你的django oscar代码方面。 Fork the checkout app from oscar, add it to the INSTALLED_APPS+=get_core_apps(['checkout']).To know how to fork an app you can follow this link from the docs: https://django-oscar.readthedocs.io/en/latest/topics/customisation.html#fork-oscar-app 从奥斯卡购买结账应用程序,将其添加到INSTALLED_APPS + = get_core_apps(['checkout'])。要知道如何分叉应用程序,您可以从文档中关注此链接: https//django-oscar.readthedocs.io/ EN /最新/主题/ customisation.html#叉奥斯卡应用

  3. Create a file called facade.py under checkout, copy the keys from your dashboard into the settings.py file and do the other changes as suggested in this link: Stripe payment gateway integration on the django oscar groups, it just happens to be titled wrong.Just follow this whole page and it's done. 在checkout下创建一个名为facade.py的文件,将仪表板中的密钥复制到settings.py文件中并按照此链接中的建议执行其他更改:django oscar组上的条带支付网关集成 ,恰好标题错误只需按照整个页面完成。

When you check the logs in your Stripe Dashboard ("Developer > Logs" section ) do you see requests for the creation of the Token, Customer and Charges? 当您检查条带仪表板(“开发人员>日志” 部分 )中的日志时,您是否看到了创建令牌,客户和费用的请求? Were these requests successful? 这些要求是否成功? Do you see any errors? 你看到有什么错误吗?

In relation to Django Oscar, I'm not familiar with it so not sure if the below would help. 关于Django Oscar,我不熟悉它,所以不确定下面的内容是否会有所帮助。

But I had a look at the Django Oscar code and it seems that the "No payment was required" message is shown by the thank_you template when the Order record doesn't have any sources added to it (ie order.sources.all returning empty): 但是我看了一下Django Oscar代码 ,当Order记录没有添加order.sources.all时( order.sources.all返回空),似乎thank_you模板显示“不需要付款”消息。 ):

https://github.com/django-oscar/django-oscar/blob/master/src/oscar/templates/oscar/checkout/thank_you.html#L94 https://github.com/django-oscar/django-oscar/blob/master/src/oscar/templates/oscar/checkout/thank_you.html#L94

So it could be that in your handle_payment code you may be not properly adding the source record to the current Order record as suggested in this recipe or the email thread you listed. 因此,在您的handle_payment代码中,您可能没有按照此配方或您列出的电子邮件主题中的建议将源记录正确添加到当前订单记录中。

For debugging this further, I would suggest to: 为了进一步调试,我建议:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM