From 0d7720cdc089b75345364223fd9cebb4ca44d5fe Mon Sep 17 00:00:00 2001 From: Adam Wathan Date: Wed, 18 Jan 2017 09:47:54 -0500 Subject: [PATCH] 63 - Capturing Charges with Callbacks --- app/Billing/StripePaymentGateway.php | 23 +++++++++++++++++++ .../unit/Billing/StripePaymentGatewayTest.php | 3 +-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/app/Billing/StripePaymentGateway.php b/app/Billing/StripePaymentGateway.php index ac177b5..14d2c83 100644 --- a/app/Billing/StripePaymentGateway.php +++ b/app/Billing/StripePaymentGateway.php @@ -38,4 +38,27 @@ class StripePaymentGateway implements PaymentGateway ] ], ['api_key' => $this->apiKey])->id; } + + public function newChargesDuring($callback) + { + $latestCharge = $this->lastCharge(); + $callback($this); + return $this->newChargesSince($latestCharge)->pluck('amount'); + } + + private function lastCharge() + { + return array_first(\Stripe\Charge::all([ + 'limit' => 1 + ], ['api_key' => $this->apiKey])['data']); + } + + private function newChargesSince($charge = null) + { + $newCharges = \Stripe\Charge::all([ + 'ending_before' => $charge ? $charge->id : null, + ], ['api_key' => $this->apiKey])['data']; + + return collect($newCharges); + } } diff --git a/tests/unit/Billing/StripePaymentGatewayTest.php b/tests/unit/Billing/StripePaymentGatewayTest.php index 61b846b..e17f353 100644 --- a/tests/unit/Billing/StripePaymentGatewayTest.php +++ b/tests/unit/Billing/StripePaymentGatewayTest.php @@ -24,8 +24,7 @@ class StripePaymentGatewayTest extends TestCase { $paymentGateway = $this->getPaymentGateway(); - // How could we make this API work? - $newCharges = $paymentGateway->newChargesDuring(function () { + $newCharges = $paymentGateway->newChargesDuring(function ($paymentGateway) { $paymentGateway->charge(2500, $paymentGateway->getValidTestToken()); });