Skip to main content
 首页 » 编程设计

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

2025年01月19日12daizhj

为了澄清一些问题,我在这里提出这个问题并分享我目前学到的知识。

首先,如果你想要一个简单、易于开发的交易系统,Braintree 就是它。非常简单,并且与 Django 配合得很好。

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

首先..一些假设。

工作流程

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

(请不要向我发送有关如何在控制面板中执行此操作的文档。可以在此处找到订阅工作流程的非常广泛的描述:https://developers.braintreepayments.com/guides/recurring-billing/create/python)

  1. 使用 braintree.ClientToken.generate() 创建一个客户端 token
  2. 使用添加付款方式的 braintree.Customer.create() 创建客户
  3. 从 Customer.create() 响应中获取客户 ID
  4. 使用 braintree.Subscription.create() 传入新客户和名为 payment_method_token 的新客户 token 创建订阅

如果您想知道,这是 Django,我正在尝试在一个 View 中完成这一切。

示例代码

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) 

问题?

我如何获得该 token ?什么是“the_token”?它从哪里来?

我看不到它是如何创建的,也看不到它是从哪里提取的。我想做类似 custy_result.customer.token 的事情,但这显然是错误的。

作为引用,以下是我在文档中查看的内容:

Customers

Payment Methods

Recurring Payments

Testing

Create Subscription

Customer.response

Credit Card Response

请您参考如下方法:

您的 custy_result 应该有 payment_methods 属性:

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