从 webhook 事件解析 Stripe 数据 invoice.payment_succeeded

Parsing Stripe data from webhook event invoice.payment_succeeded

我正在从 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

我想从 'plan' 中提取数据并解析它以便在 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,它将 return 变成 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 不同)。此字符串是有效的 python dict 对象。 "u" 前缀标记 python pre python3.

中的 unicode 类型