python - 从 webhook 事件 invoice.payment_succeeded 解析 Stripe 数据
问题描述
我正在从 Stripe 捕获成功的发票的 webhook,它为我提供了这个
amount: 7500
currency: usd
description: None
discountable: True
id: sub_DfLYbarfoo
livemode: True
metadata: {}
object: line_item
period: {u'start': 1537694450, u'end': 1569930450}
plan: {u'active': True, u'product': u'prod_Bzxbarfoo', u'transform_usage': None, u'name': u'Agent - Yearly', u'aggregate_usage': None, u'created': 1513986904, u'tiers_mode': None, u'interval': u'year', u'tiers': None, u'object': u'plan', u'id': u'ra-yearly', u'currency': u'usd', u'amount': 7500, u'interval_count': 1, u'trial_period_days': 2, u'livemode': True, u'usage_type': u'licensed', u'metadata': {u'qb_product': u'71'}, u'nickname': u'Agent - Yearly', u'statement_descriptor': u'foobar.com/charge', u'billing_scheme': u'per_unit'}
proration: False
quantity: 1
subscription: None
subscription_item: si_DfLYfoo
type: subscription
我想从“计划”中提取数据并解析它以用于 Zapier 流程。我已经使用以下代码缩小了我需要的确切数据范围
data = input['data']
begin_index = data.find('plan:') + 6
end_index = data.rfind('}') + 1
plan = data[begin_index:end_index]
这为我提供了
{u'active': True, u'product': u'prod_Bzxbarfoo', u'transform_usage': None, u'name': u'Agent - Yearly', u'aggregate_usage': None, u'created': 1513986904, u'tiers_mode': None, u'interval': u'year', u'tiers': None, u'object': u'plan', u'id': u'ra-yearly', u'currency': u'usd', u'amount': 7500, u'interval_count': 1, u'trial_period_days': 2, u'livemode': True, u'usage_type': u'licensed', u'metadata': {u'qb_product': u'71'}, u'nickname': u'Agent - Yearly', u'statement_descriptor': u'foobar.com/charge', u'billing_scheme': u'per_unit'}
我不确定前导 'u' 字符在每个键和值上做了什么,但它阻止我将其解析为可用的 json。
解决方案
您可以尝试使用ast.literal_val
which 将返回一个 python dict
。例如,在您的代码中:
import ast
import json
data = input['data']
begin_index = data.find('plan:') + 6
end_index = data.rfind('}') + 1
plan = ast.literal_eval(data[begin_index:end_index])
json_plan = json.dumps(plan)
ast.literal_eval
只是将字符串解析为文字(它不执行任何代码,因此可以安全使用,与 eval 不同)。这个字符串是一个有效的 pythondict
对象。“u”前缀unicode
在 python pre python3 中标记了一个类型。
推荐阅读
- javascript - WordPress - 如何阻止 Gutenberg Block 触发多个 GET 请求?
- reactjs - 使用 create react app 和 typescript 设置测试覆盖率和阈值
- c# - PageIterator 作为 GetAsync() 上的通用扩展方法
- javascript - 该条件在 ajax 请求中不起作用
- flutter - 如何将变量从一个类传递给另一个类并将更改后的变量返回?
- python - 我正在尝试对熊猫聚合进行排序
- android - 在 Android Studio 中找不到 \gradle-wrapper.properties
- c++ - Boost logger的深拷贝
- c++ - 按顶点数对 3D 对象进行排序 C++
- wpf - 文本在 WPF 应用程序的 UI 中可见,但 WinAppdriver 无法识别文本