-
Notifications
You must be signed in to change notification settings - Fork 680
/
Billable.php
647 lines (553 loc) · 16.8 KB
/
Billable.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
<?php
namespace Laravel\Cashier;
use Exception;
use Illuminate\Support\Collection;
use InvalidArgumentException;
use Stripe\BankAccount as StripeBankAccount;
use Stripe\Card as StripeCard;
use Stripe\Charge as StripeCharge;
use Stripe\Customer as StripeCustomer;
use Stripe\Error\InvalidRequest as StripeErrorInvalidRequest;
use Stripe\Invoice as StripeInvoice;
use Stripe\InvoiceItem as StripeInvoiceItem;
use Stripe\Refund as StripeRefund;
use Stripe\Token as StripeToken;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
trait Billable
{
/**
* The Stripe API key.
*
* @var string
*/
protected static $stripeKey;
/**
* Make a "one off" charge on the customer for the given amount.
*
* @param int $amount
* @param array $options
* @return \Stripe\Charge
* @throws \InvalidArgumentException
*/
public function charge($amount, array $options = [])
{
$options = array_merge([
'currency' => $this->preferredCurrency(),
], $options);
$options['amount'] = $amount;
if (! array_key_exists('source', $options) && $this->stripe_id) {
$options['customer'] = $this->stripe_id;
}
if (! array_key_exists('source', $options) && ! array_key_exists('customer', $options)) {
throw new InvalidArgumentException('No payment source provided.');
}
return StripeCharge::create($options, ['api_key' => $this->getStripeKey()]);
}
/**
* Refund a customer for a charge.
*
* @param string $charge
* @param array $options
* @return \Stripe\Refund
* @throws \InvalidArgumentException
*/
public function refund($charge, array $options = [])
{
$options['charge'] = $charge;
return StripeRefund::create($options, ['api_key' => $this->getStripeKey()]);
}
/**
* Determines if the customer currently has a card on file.
*
* @return bool
*/
public function hasCardOnFile()
{
return (bool) $this->card_brand;
}
/**
* Add an invoice item to the customer's upcoming invoice.
*
* @param string $description
* @param int $amount
* @param array $options
* @return \Stripe\InvoiceItem
* @throws \InvalidArgumentException
*/
public function tab($description, $amount, array $options = [])
{
if (! $this->stripe_id) {
throw new InvalidArgumentException(class_basename($this).' is not a Stripe customer. See the createAsStripeCustomer method.');
}
$options = array_merge([
'customer' => $this->stripe_id,
'amount' => $amount,
'currency' => $this->preferredCurrency(),
'description' => $description,
], $options);
return StripeInvoiceItem::create($options, ['api_key' => $this->getStripeKey()]);
}
/**
* Invoice the customer for the given amount and generate an invoice immediately.
*
* @param string $description
* @param int $amount
* @param array $tabOptions
* @param array $invoiceOptions
* @return \Stripe\Invoice|bool
*/
public function invoiceFor($description, $amount, array $tabOptions = [], array $invoiceOptions = [])
{
$this->tab($description, $amount, $tabOptions);
return $this->invoice($invoiceOptions);
}
/**
* Begin creating a new subscription.
*
* @param string $subscription
* @param string $plan
* @return \Laravel\Cashier\SubscriptionBuilder
*/
public function newSubscription($subscription, $plan)
{
return new SubscriptionBuilder($this, $subscription, $plan);
}
/**
* Determine if the Stripe model is on trial.
*
* @param string $subscription
* @param string|null $plan
* @return bool
*/
public function onTrial($subscription = 'default', $plan = null)
{
if (func_num_args() === 0 && $this->onGenericTrial()) {
return true;
}
$subscription = $this->subscription($subscription);
if (is_null($plan)) {
return $subscription && $subscription->onTrial();
}
return $subscription && $subscription->onTrial() &&
$subscription->stripe_plan === $plan;
}
/**
* Determine if the Stripe model is on a "generic" trial at the model level.
*
* @return bool
*/
public function onGenericTrial()
{
return $this->trial_ends_at && $this->trial_ends_at->isFuture();
}
/**
* Determine if the Stripe model has a given subscription.
*
* @param string $subscription
* @param string|null $plan
* @return bool
*/
public function subscribed($subscription = 'default', $plan = null)
{
$subscription = $this->subscription($subscription);
if (is_null($subscription)) {
return false;
}
if (is_null($plan)) {
return $subscription->valid();
}
return $subscription->valid() &&
$subscription->stripe_plan === $plan;
}
/**
* Get a subscription instance by name.
*
* @param string $subscription
* @return \Laravel\Cashier\Subscription|null
*/
public function subscription($subscription = 'default')
{
return $this->subscriptions->sortByDesc(function ($value) {
return $value->created_at->getTimestamp();
})->first(function ($value) use ($subscription) {
return $value->name === $subscription;
});
}
/**
* Get all of the subscriptions for the Stripe model.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function subscriptions()
{
return $this->hasMany(Subscription::class, $this->getForeignKey())->orderBy('created_at', 'desc');
}
/**
* Invoice the billable entity outside of regular billing cycle.
*
* @param array $options
* @return \Stripe\Invoice|bool
*/
public function invoice(array $options = [])
{
if ($this->stripe_id) {
$parameters = array_merge($options, ['customer' => $this->stripe_id]);
try {
return StripeInvoice::create($parameters, $this->getStripeKey())->pay();
} catch (StripeErrorInvalidRequest $e) {
return false;
}
}
return true;
}
/**
* Get the entity's upcoming invoice.
*
* @return \Laravel\Cashier\Invoice|null
*/
public function upcomingInvoice()
{
try {
$stripeInvoice = StripeInvoice::upcoming(
['customer' => $this->stripe_id], ['api_key' => $this->getStripeKey()]
);
return new Invoice($this, $stripeInvoice);
} catch (StripeErrorInvalidRequest $e) {
//
}
}
/**
* Find an invoice by ID.
*
* @param string $id
* @return \Laravel\Cashier\Invoice|null
*/
public function findInvoice($id)
{
try {
$stripeInvoice = StripeInvoice::retrieve(
$id, $this->getStripeKey()
);
$stripeInvoice->lines = StripeInvoice::retrieve($id, $this->getStripeKey())
->lines
->all(['limit' => 1000]);
return new Invoice($this, $stripeInvoice);
} catch (Exception $e) {
//
}
}
/**
* Find an invoice or throw a 404 error.
*
* @param string $id
* @return \Laravel\Cashier\Invoice
*/
public function findInvoiceOrFail($id)
{
$invoice = $this->findInvoice($id);
if (is_null($invoice)) {
throw new NotFoundHttpException;
}
if ($invoice->customer !== $this->stripe_id) {
throw new AccessDeniedHttpException;
}
return $invoice;
}
/**
* Create an invoice download Response.
*
* @param string $id
* @param array $data
* @return \Symfony\Component\HttpFoundation\Response
*/
public function downloadInvoice($id, array $data)
{
return $this->findInvoiceOrFail($id)->download($data);
}
/**
* Get a collection of the entity's invoices.
*
* @param bool $includePending
* @param array $parameters
* @return \Illuminate\Support\Collection
*/
public function invoices($includePending = false, $parameters = [])
{
$invoices = [];
$parameters = array_merge(['limit' => 24], $parameters);
$stripeInvoices = $this->asStripeCustomer()->invoices($parameters);
// Here we will loop through the Stripe invoices and create our own custom Invoice
// instances that have more helper methods and are generally more convenient to
// work with than the plain Stripe objects are. Then, we'll return the array.
if (! is_null($stripeInvoices)) {
foreach ($stripeInvoices->data as $invoice) {
if ($invoice->paid || $includePending) {
$invoices[] = new Invoice($this, $invoice);
}
}
}
return new Collection($invoices);
}
/**
* Get an array of the entity's invoices.
*
* @param array $parameters
* @return \Illuminate\Support\Collection
*/
public function invoicesIncludingPending(array $parameters = [])
{
return $this->invoices(true, $parameters);
}
/**
* Get a collection of the entity's cards.
*
* @param array $parameters
* @return \Illuminate\Support\Collection
*/
public function cards($parameters = [])
{
$cards = [];
$parameters = array_merge(['limit' => 24], $parameters);
$stripeCards = $this->asStripeCustomer()->sources->all(
['object' => 'card'] + $parameters
);
if (! is_null($stripeCards)) {
foreach ($stripeCards->data as $card) {
$cards[] = new Card($this, $card);
}
}
return new Collection($cards);
}
/**
* Get the default card for the entity.
*
* @return \Stripe\Card|null
*/
public function defaultCard()
{
if (! $this->hasStripeId()) {
return;
}
$customer = $this->asStripeCustomer();
foreach ($customer->sources->data as $card) {
if ($card->id === $customer->default_source) {
return $card;
}
}
}
/**
* Update customer's credit card.
*
* @param string $token
* @return void
*/
public function updateCard($token)
{
$customer = $this->asStripeCustomer();
$token = StripeToken::retrieve($token, ['api_key' => $this->getStripeKey()]);
// If the given token already has the card as their default source, we can just
// bail out of the method now. We don't need to keep adding the same card to
// a model's account every time we go through this particular method call.
if ($token[$token->type]->id === $customer->default_source) {
return;
}
$card = $customer->sources->create(['source' => $token]);
$customer->default_source = $card->id;
$customer->save();
// Next we will get the default source for this model so we can update the last
// four digits and the card brand on the record in the database. This allows
// us to display the information on the front-end when updating the cards.
$source = $customer->default_source
? $customer->sources->retrieve($customer->default_source)
: null;
$this->fillCardDetails($source);
$this->save();
}
/**
* Synchronises the customer's card from Stripe back into the database.
*
* @return $this
*/
public function updateCardFromStripe()
{
$defaultCard = $this->defaultCard();
if ($defaultCard) {
$this->fillCardDetails($defaultCard)->save();
} else {
$this->forceFill([
'card_brand' => null,
'card_last_four' => null,
])->save();
}
return $this;
}
/**
* Fills the model's properties with the source from Stripe.
*
* @param \Stripe\Card|\Stripe\BankAccount|null $card
* @return $this
*/
protected function fillCardDetails($card)
{
if ($card instanceof StripeCard) {
$this->card_brand = $card->brand;
$this->card_last_four = $card->last4;
} elseif ($card instanceof StripeBankAccount) {
$this->card_brand = 'Bank Account';
$this->card_last_four = $card->last4;
}
return $this;
}
/**
* Deletes the entity's cards.
*
* @return void
*/
public function deleteCards()
{
$this->cards()->each(function ($card) {
$card->delete();
});
$this->updateCardFromStripe();
}
/**
* Apply a coupon to the billable entity.
*
* @param string $coupon
* @return void
*/
public function applyCoupon($coupon)
{
$customer = $this->asStripeCustomer();
$customer->coupon = $coupon;
$customer->save();
}
/**
* Determine if the Stripe model is actively subscribed to one of the given plans.
*
* @param array|string $plans
* @param string $subscription
* @return bool
*/
public function subscribedToPlan($plans, $subscription = 'default')
{
$subscription = $this->subscription($subscription);
if (! $subscription || ! $subscription->valid()) {
return false;
}
foreach ((array) $plans as $plan) {
if ($subscription->stripe_plan === $plan) {
return true;
}
}
return false;
}
/**
* Determine if the entity is on the given plan.
*
* @param string $plan
* @return bool
*/
public function onPlan($plan)
{
return ! is_null($this->subscriptions->first(function ($value) use ($plan) {
return $value->stripe_plan === $plan && $value->valid();
}));
}
/**
* Determine if the entity has a Stripe customer ID.
*
* @return bool
*/
public function hasStripeId()
{
return ! is_null($this->stripe_id);
}
/**
* Create a Stripe customer for the given model.
*
* @param array $options
* @return \Stripe\Customer
*/
public function createAsStripeCustomer(array $options = [])
{
$options = array_key_exists('email', $options)
? $options
: array_merge($options, ['email' => $this->email]);
// Here we will create the customer instance on Stripe and store the ID of the
// user from Stripe. This ID will correspond with the Stripe user instances
// and allow us to retrieve users from Stripe later when we need to work.
$customer = StripeCustomer::create(
$options, $this->getStripeKey()
);
$this->stripe_id = $customer->id;
$this->save();
return $customer;
}
/**
* Update the underlying Stripe customer information for the model.
*
* @param array $options
* @return \Stripe\Customer
*/
public function updateStripeCustomer(array $options = [])
{
$customer = StripeCustomer::update(
$this->stripe_id, $options, $this->getStripeKey()
);
return $customer;
}
/**
* Get the Stripe customer for the model.
*
* @return \Stripe\Customer
*/
public function asStripeCustomer()
{
return StripeCustomer::retrieve($this->stripe_id, $this->getStripeKey());
}
/**
* Get the Stripe supported currency used by the entity.
*
* @return string
*/
public function preferredCurrency()
{
return Cashier::usesCurrency();
}
/**
* Get the tax percentage to apply to the subscription.
*
* @return int|float
*/
public function taxPercentage()
{
return 0;
}
/**
* Get the Stripe API key.
*
* @return string
*/
public static function getStripeKey()
{
if (static::$stripeKey) {
return static::$stripeKey;
}
if ($key = getenv('STRIPE_SECRET')) {
return $key;
}
return config('services.stripe.secret');
}
/**
* Set the Stripe API key.
*
* @param string $key
* @return void
*/
public static function setStripeKey($key)
{
static::$stripeKey = $key;
}
}