Search code examples
phpstripe-paymentsunix-timestamp

PHP - Understanding timestamp argument (usage records)


I'm trying to setup upcoming invoices for metered billing from stripe. In order to do this I need to run usage records. My understanding is that a Usage record will need to run in order to generate an accurate upcoming invoice. I created a function called stripeUsageRecord() that I call before generating the invoice.

  public function stripeUsageRecord()
  {
    $authUser = auth()->user();
    $sub_item = $authUser['subscription_item'];
    \Stripe\Stripe::setApiKey(env("STRIPE_SECRET"));
    return \Stripe\UsageRecord::create(array(
      "quantity" => 11,
      // "timestamp" => time(),
      "timestamp" => 1540225312,
      "subscription_item" => $sub_item,
      "action" => "set"
    ));
  }

This function does do its desired outcome. The only problem I am running into is that I cannot set the timestamp dynamically. If I run a static timestamp (within the subscription date range) it works the way I want it to, which is not increment it. but If i use the php time() to set the time stamp to the current time it increments the quantity (when I need it to be updating it).

(In my code the quantity is determined by a query which counts all the users that have shopped at the location within the subscription time frame. here I just add a number so it would be easier to understand.)

how can I set the timestamp dynamically updating the quantity instead of adding it on top of the previous usage record ran with a different time stamp?


Solution

  • When creating a UsageRecord, set will overwrite the usage quantity at a given timestamp. If the new record you create has a different timestamp, it will just add to the total to be charged at the end of period rather than overwriting.

    The way to work around this is you could set-up the underlying plan with the option aggregate_usage=last_during_period, so that only the last record for the timestamp is used on the final invoice!

    Something like this:

    \Stripe\Plan::create(array(
      "amount" => 100,
      "interval" => "month",
      "product" => array(
        "name" => "Gold Metered"
      ),
      "currency" => "usd",
      "id" => "gold-metered",
      "usage_type" => "metered",
      "aggregate_usage" => "last_during_period"
    ));
    

    More context is here: https://stripe.com/docs/billing/subscriptions/metered-billing#reporting-usage