diff --git a/src/Billable.php b/src/Billable.php index f257fe4e..09444b5a 100644 --- a/src/Billable.php +++ b/src/Billable.php @@ -7,6 +7,7 @@ use Laravel\Cashier\Concerns\ManagesInvoices; use Laravel\Cashier\Concerns\ManagesPaymentMethods; use Laravel\Cashier\Concerns\ManagesSubscriptions; +use Laravel\Cashier\Concerns\ManagesUsageBilling; use Laravel\Cashier\Concerns\PerformsCharges; trait Billable @@ -16,5 +17,6 @@ trait Billable use ManagesInvoices; use ManagesPaymentMethods; use ManagesSubscriptions; + use ManagesUsageBilling; use PerformsCharges; } diff --git a/src/Concerns/ManagesUsageBilling.php b/src/Concerns/ManagesUsageBilling.php new file mode 100644 index 00000000..c6d75d0f --- /dev/null +++ b/src/Concerns/ManagesUsageBilling.php @@ -0,0 +1,77 @@ +stripe()->billing->meters->all($options, $requestOptions)->data); + } + + /** + * Report usage for a metered product. + * + * @param string $meter + * @param int $quantity + * @param string|null $price + * @param array $options + * @param array $requestOptions + * @return \Stripe\Billing\MeterEvent + */ + public function reportMeterEvent( + string $meter, + int $quantity = 1, + array $options = [], + array $requestOptions = [] + ): MeterEvent { + $this->assertCustomerExists(); + + return $this->stripe()->billing->meterEvents->create([ + 'event_name' => $meter, + 'payload' => [ + 'stripe_customer_id' => $this->stripeId(), + 'value' => $quantity, + ], + ...$options, + ], $requestOptions); + } + + /** + * Get the usage records for a meter using its ID. + * + * @param string $meterId + * @param array $options + * @param array $requestOptions + * @return \Illuminate\Support\Collection + */ + public function meterEventSummaries(string $meterId, int $startTime = 1, ?int $endTime = null, array $options = [], array $requestOptions = []): Collection + { + $this->assertCustomerExists(); + + if (!isset($endTime)) { + $endTime = time(); + } + + return new Collection($this->stripe()->billing->meters->allEventSummaries( + $meterId, + [ + 'customer' => $this->stripeId(), + 'start_time' => $startTime, + 'end_time' => $endTime, + ...$options, + ], + $requestOptions + )->data); + } +}