首页 > 解决方案 > 从 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。

标签: pythonjsonparsingstripe-paymentszapier

解决方案


您可以尝试使用ast.literal_valwhich 将返回一个 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 中标记了一个类型。


推荐阅读