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

标签 python django stripe-payments django-oscar stripe.js

我正在尝试将 Stripe 支付网关集成到 Django oscar,用于在线销售杂货等实物商品的电子商务网站。我使用 python 3.6.3、Django 2.0、Django-oscar 1.6、stripe 1.82.2。

方法一:

所以我在 django-oscar 组中点击了这个链接:

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

我已经注册了一个 stripe 帐户并使用我的可发布 key 和测试 key 来配置 stripe。问题是,当我尝试使用带有标签“Pay with Card”的按钮进行支付时,它会收集我的卡信息并然后当我点击按钮时,它显示“将从卡中扣除一些钱”,如下图所示: Image of Preview page

然后在我点击下订单按钮后,它显示如下: Image of confirmation page

虽然我已经使用我的卡付款。 我猜 oscar 似乎不知道付款已经通过 stripe 完成了?但我不确定如何解决这个问题。

方法二: 我尝试使用 dj-stripe,在这里找到:

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

但我阅读了关于 https://dj-stripe.readthedocs.io/en/stable-1.0/ 的整个文档,似乎我只能将它用于需要订阅的产品,我的产品不需要订阅,而且 dj-stripe 的文档并不完整。

我尝试使用官方的 django-oscar 存储库,链接在这里: https://github.com/django-oscar/django-oscar-stripe ,这个存储库已有五年历史了,我认为它与我的 Django oscar 版本不兼容。

方法三: 我尝试使用 stripe.js 和元素并创建我的表单来接受卡片:

< 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>

在我的 python views.py 文件中,我创建了一个 Stripe 电荷和源。

@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/")

然后我在 stripe 仪表板中创建了一个 webhook 并将其链接到我的本地 url ,每次通过 web-hook 发送来自 stripe 的响应时,都会命中此 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)

截至目前,我可以从我的仪表板跟踪各种事件或日志,以及创建客户、收费和发送响应的 web-hook 等事件工作正常,但我不知道如何才能我完成付款,这样 Django-oscar 也可以知道付款已完成并且不会显示“不需要付款”: Thank you page

我已经尝试了所有这些方法,但它仍然不起作用。我愿意使用任何其他建议的方法或改进我在迄今为止解释的任何方法中所做的事情。我是新手django-oscar 以及带有一些代码和一些解释的答案会有所帮助。

最佳答案

我找到了一种将 Stripe 与 Django Oscar 集成的方法,这是实现它的简单方法之一。

  1. 首先从这里创建一个 stripe 帐户:https://stripe.com/ ,您将获得一个可发布 key 和一个 secret key ,您可以在登录开发人员 > API key 下的 strip 仪表板后查看它们。

  2. 在您的 django oscar 代码端。从 oscar fork 结帐应用程序,将其添加到 INSTALLED_APPS+=get_core_apps(['checkout'])。要了解如何 fork 应用程序,您可以点击文档中的此链接:https://django-oscar.readthedocs.io/en/latest/topics/customisation.html#fork-oscar-app

  3. 在 checkout 下创​​建一个名为 facade.py 的文件,将仪表板中的 key 复制到 settings.py 文件中,然后按照此链接中的建议进行其他更改:Stripe payment gateway integration在 django oscar 组上,它恰好标题错误。只需关注整个页面即可完成。

关于python - 如何将 Stripe 支付网关与 Django Oscar 集成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51243465/

相关文章:

stripe-payments - strip redirect_uri将不起作用

node.js - 使用结帐 session 设置订阅时如何设置 billing_cycle_anchor?

python - 如何根据与序列相关的约束过滤行?

python - 查找子字符串在给定字符串中出现的次数

python - 如何使用 Django 从 Azure AD 检索员工 ID?

django - 如何在 django 中发送多个查询集?

ios - 自 Swift 3 上的 Xcode 8 GM 起,无法符合 STPAddCardViewControllerDelegate

python - 在 Python 中以列表理解的形式添加要设置的元素

python - 使用 Django 代替 app-engine 默认的 web 框架有什么优势?

python - Django 查询查找模型实例,其中 somefilefield == None?