这是使用API​​在Python中为Braintree创建订阅的正确方法

时间:2017-11-04 00:20:34

标签: python django django-views braintree braintree-sandbox

为了清楚起见,我在这里提出这个问题并分享我迄今为止所学到的知识。

首先,如果你想要一个简单易开发的交易系统,Braintree就是这样。非常简单,与Django一起玩得非常好。

然而,订阅方面的事情并不那么清楚。因此,我分享了一些代码以获得反馈并帮助简化。

首先......一些假设。

工作流程

使用API​​创建订阅的过程如下:

(请不要在控制面板中向我发送有关如何操作的文档。有关订阅工作流程的详细说明,请访问:https://developers.braintreepayments.com/guides/recurring-billing/create/python < / p>

  1. 使用braintree.ClientToken.generate()
  2. 创建客户端令牌
  3. 使用braintree.Customer.create()创建添加付款方式的客户
  4. Customer.create()回复
  5. 获取客户ID
  6. 使用braintree.Subscription.create()传递新客户和名为payment_method_token
  7. 的新客户令牌创建订阅

    如果您想知道,这是Django,我试图在一个视图中完成所有操作。

    示例代码

    custy_result = braintree.Customer.create({
        "first_name": self.request.POST.get('first_name'),
        "last_name": self.request.POST.get('last_name'),
        "company": self.request.POST.get('company_name'),
        "email": self.request.POST.get('office_email'),
        "phone": self.request.POST.get('office_phone'),
        'payment_method_nonce': 'fake-valid-nonce', # for testing
        "credit_card": {
            "billing_address": {
                "street_address": self.request.POST.get('address'),
                "locality": self.request.POST.get('city'),
                "region": self.request.POST.get('state'),
                "postal_code": self.request.POST.get('postal'),
            }
        }
    })
    
    if custy_result.is_success:
        print("Customer Success!")
    else:
        for error in custy_result.errors.deep_errors:
            print(error.code)
            print(error.message)
    
    # Create the subscription in braintree
    sub_result = braintree.Subscription.create({
        "payment_method_token": "the_token", # <-- How do I get this token?
        "plan_id": "the_plan_id_in_braintree"
    })
    
    if sub_result.is_success:
        print("Subscription Success!")
    else:
        for error in sub_result.errors.deep_errors:
            print(error.code)
            print(error.message)
    

    问题?

    我如何获得该令牌?什么是&#34; the_token&#34;?它来自哪里?

    我无法看到它是如何创建的,我无法看到它从何处被拉出来。我想做custy_result.customer.token之类的事情,但这显然是错误的。

    供参考,以下是我在文档中看到的内容:

    Customers

    Payment Methods

    Recurring Payments

    Testing

    Create Subscription

    Customer.response

    Credit Card Response

1 个答案:

答案 0 :(得分:1)

您的custy_result应具有payment_methods属性:

result = braintree.Subscription.create({
    "payment_method_token": custy_result.payment_methods[0].token,
    "plan_id": "planID"
})