Как уничтожить объект Stripe

#stripe-payments

Вопрос:

Я написал следующий веб-хук для захвата событий, поступающих из stripe после того, как пользователь внес изменения в подписку:

 export const stripeWebhookEvents = functions.https.onRequest( async ( request: any, response: any ) => {
    // Retrieve the event by verifying the signature using the raw body and secret.
    let event;
    const signature = request.headers["stripe-signature"];
    try {
        event = stripe.webhooks.constructEvent(
            request.rawBody,
            signature,
            STRIPE_WEBHOOK
        );
    } catch (err) {
        console.log("⚠️  Webhook signature verification failed.", err);
        return response.sendStatus(400);
    }
    // Extract the object from the event.
    const eventType = event.type;
    console.log(`Scripe event type: ${eventType}.`);
    // Handle the event
    switch (eventType) {
        case "customer.subscription.created": {
            // Occurs whenever a customer is signed up for a new plan.
            console.log("customer.subscription.created");
            try {
                const session = event.data.object;
                console.log("stripe customer: ", session.customer);
                const userRecord = await getUserWithStripeCustomerID(session.customer);
                console.log("userRecord: ", userRecord);
                const data = {
                    "subscription_status": session.status,
                };
                await updateUser(userRecord, data);
            } catch (error) {
                console.log(error);
            }
            break;
        }
        case "customer.subscription.updated": {
            // Occurs whenever a subscription changes (e.g., switching from one plan to another,
            // or changing the status from trial to active).
            break;
        }
        case "customer.subscription.deleted": {
            // The subscription has been deleted so update the user document so that it shows
            // that the subscription is inactive.
        }
        case "invoice.payment_failed": {
            // The payment failed or the customer does not have a valid payment method.
            // The subscription becomes past_due. Notify your customer and send them to the
            // customer portal to update their payment information.
            // update the user document so that it shows that the subscription is inactive.
            break;
        }
        default: {
        // Unexpected event type
        console.log(`Unhandled event type ${eventType}.`);
        }
    }
    response.sendStatus(200);
});
 

Объект подписки, полученный от stripe, является:

 {
  "id": "sub_JhxDD458se1T1c",
  "object": "subscription",
  "application_fee_percent": null,
  "automatic_tax": {
    "enabled": false
  },
  "billing_cycle_anchor": 1624221102,
  "billing_thresholds": null,
  "cancel_at": null,
  "cancel_at_period_end": false,
  "canceled_at": null,
  "collection_method": "charge_automatically",
  "created": 1624221102,
  "current_period_end": 1626813102,
  "current_period_start": 1624221102,
  "customer": "cus_FJ9HCZk3rCSlxD",
  "days_until_due": null,
  "default_payment_method": null,
  "default_source": null,
  "default_tax_rates": [],
  "discount": null,
  "ended_at": null,
  "items": {
    "object": "list",
    "data": [
      {
        "id": "si_JhxDPLJExCLmnu",
        "object": "subscription_item",
        "billing_thresholds": null,
        "created": 1624221103,
        "metadata": {},
        "price": {
          "id": "price_1J3q2zHx6drz9dmy2bMdkXOs",
          "object": "price",
          "active": true,
          "billing_scheme": "per_unit",
          "created": 1624054821,
          "currency": "gbp",
          "livemode": false,
          "lookup_key": null,
          "metadata": {},
          "nickname": null,
          "product": "prod_JhEWBSIjTi2nlt",
          "recurring": {
            "aggregate_usage": null,
            "interval": "month",
            "interval_count": 1,
            "usage_type": "licensed"
          },
          "tax_behavior": "unspecified",
          "tiers_mode": null,
          "transform_quantity": null,
          "type": "recurring",
          "unit_amount": 1299,
          "unit_amount_decimal": "1299"
        },
        "quantity": 1,
        "subscription": "sub_JhxDD458se1T1c",
        "tax_rates": []
      }
    ],
    "has_more": false,
    "url": "/v1/subscription_items?subscription=sub_JhxDD458se1T1c"
  },
  "latest_invoice": null,
  "livemode": false,
  "metadata": {},
  "next_pending_invoice_item_invoice": null,
  "pause_collection": null,
  "pending_invoice_item_interval": null,
  "pending_setup_intent": null,
  "pending_update": null,
  "schedule": null,
  "start_date": 1624221102,
  "status": "active",
  "transfer_data": null,
  "trial_end": null,
  "trial_start": null
}
 

Когда «клиент.подписка.создана», я хочу обновить идентификатор цены («price_1J3q2zHx6drz9dmy2bMdkXOs»), но я не уверен, как его получить. Я пытался:

 session.items.data[price.id]
 

но это не работает. Как мне получить доступ к идентификатору цены?

Комментарии:

1. сессия.элементы.данные[0].price.id

2. Да, то, что сказала Нисала.

3. Спасибо, Нисала — это сработало идеально!