-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathBillable.php
551 lines (483 loc) · 13.9 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
<?php
namespace yii2mod\cashier;
use Carbon\Carbon;
use Exception;
use InvalidArgumentException;
use Stripe\Charge;
use Stripe\Customer;
use Stripe\Error\Card;
use Stripe\Error\InvalidRequest;
use Stripe\Invoice as StripeInvoice;
use Stripe\InvoiceItem as StripeInvoiceItem;
use Stripe\Refund as StripeRefund;
use Stripe\Token;
use Yii;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii2mod\cashier\models\SubscriptionModel;
/**
* Class Billable
*
* @package yii2mod\cashier
*/
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 Charge
*
* @throws Card
*/
public function charge($amount, array $options = []): Charge
{
$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 Charge::create($options, ['api_key' => $this->getStripeKey()]);
}
/**
* Refund a customer for a charge.
*
* @param $charge
* @param array $options
*
* @return StripeRefund
*/
public function refund($charge, array $options = []): StripeRefund
{
$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(): bool
{
return (bool) $this->card_brand;
}
/**
* Invoice the customer for the given amount.
*
* @param string $description
* @param int $amount
* @param array $options
*
* @return bool|StripeInvoice
*
* @throws Card
*/
public function invoiceFor($description, $amount, array $options = [])
{
if (!$this->stripe_id) {
throw new InvalidArgumentException('User is not a customer. See the createAsStripeCustomer method.');
}
$options = array_merge([
'customer' => $this->stripe_id,
'amount' => $amount,
'currency' => $this->preferredCurrency(),
'description' => $description,
], $options);
StripeInvoiceItem::create(
$options, ['api_key' => $this->getStripeKey()]
);
return $this->invoice();
}
/**
* Begin creating a new subscription.
*
* @param string $subscription
* @param string $plan
*
* @return SubscriptionBuilder
*/
public function newSubscription(string $subscription, string $plan): SubscriptionBuilder
{
return new SubscriptionBuilder($this, $subscription, $plan);
}
/**
* Determine if the user is on trial.
*
* @param string $subscription
* @param string|null $plan
*
* @return bool
*/
public function onTrial(string $subscription = 'default', ?string $plan = null): bool
{
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->stripePlan === $plan;
}
/**
* Determine if the user is on a "generic" trial at the user level.
*
* @return bool
*/
public function onGenericTrial(): bool
{
return $this->trial_ends_at && Carbon::now()->lt(Carbon::createFromFormat('Y-m-d H:i:s', $this->trial_ends_at));
}
/**
* Determine if the user has a given subscription.
*
* @param string $subscription
* @param string|null $plan
*
* @return bool
*/
public function subscribed(string $subscription = 'default', ?string $plan = null): bool
{
$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 SubscriptionModel|null
*/
public function subscription(string $subscription = 'default'): ?SubscriptionModel
{
return $this->getSubscriptions()->where(['name' => $subscription])->one();
}
/**
* @return mixed
*/
public function getSubscriptions()
{
return $this->hasMany(SubscriptionModel::class, ['user_id' => 'id'])->orderBy(['created_at' => SORT_DESC]);
}
/**
* Invoice the billable entity outside of regular billing cycle.
*
* @return bool|StripeInvoice
*/
public function invoice()
{
if ($this->stripe_id) {
try {
return StripeInvoice::create(['customer' => $this->stripe_id], $this->getStripeKey())->pay();
} catch (InvalidRequest $e) {
return false;
}
}
return true;
}
/**
* Get the entity's upcoming invoice.
*
* @return Invoice|null
*/
public function upcomingInvoice(): ?Invoice
{
try {
$stripeInvoice = StripeInvoice::upcoming(
['customer' => $this->stripe_id], ['api_key' => $this->getStripeKey()]
);
return new Invoice($this, $stripeInvoice);
} catch (InvalidRequest $e) {
}
}
/**
* Find an invoice by ID.
*
* @param string $id
*
* @return Invoice|null
*/
public function findInvoice(string $id): Invoice
{
try {
return new Invoice($this, StripeInvoice::retrieve($id, $this->getStripeKey()));
} catch (Exception $e) {
}
}
/**
* Find an invoice or throw a 404 error.
*
* @param string $id
*
* @return Invoice
*
* @throws NotFoundHttpException
*/
public function findInvoiceOrFail(string $id)
{
$invoice = $this->findInvoice($id);
if (is_null($invoice)) {
throw new NotFoundHttpException('The requested page does not exist.');
}
return $invoice;
}
/**
* Create an invoice download Response.
*
* @param string $id
* @param array $data
*
* @return Response
*/
public function downloadInvoice(string $id, array $data)
{
return $this->findInvoiceOrFail($id)->download($data);
}
/**
* Get a collection of the entity's invoices.
*
* @param bool $includePending
* @param array $parameters
*
* @return array
*/
public function invoices(bool $includePending = false, array $parameters = []): array
{
$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 $invoices;
}
/**
* Get an array of the entity's invoices.
*
* @param array $parameters
*
* @return array
*/
public function invoicesIncludingPending(array $parameters = []): array
{
return $this->invoices(true, $parameters);
}
/**
* Update customer's credit card.
*
* @param string $token
*/
public function updateCard(string $token): void
{
$customer = $this->asStripeCustomer();
$token = Token::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
// the user's account each time we go through this particular method call.
if ($token->card->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 user so we can update the last
// four digits and the card brand on this user record in the database, which
// is convenient when displaying 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()
{
$customer = $this->asStripeCustomer();
$defaultCard = null;
foreach ($customer->sources->data as $card) {
if ($card->id === $customer->default_source) {
$defaultCard = $card;
break;
}
}
if ($defaultCard) {
$this->fillCardDetails($defaultCard)->save();
} else {
$this->card_brand = null;
$this->card_last_four = null;
$this->update(false);
}
return $this;
}
/**
* Fills the user's properties with the source from Stripe.
*
* @param \Stripe\Card|null $card
*
* @return $this
*/
protected function fillCardDetails($card)
{
if ($card) {
$this->card_brand = $card->brand;
$this->card_last_four = $card->last4;
}
return $this;
}
/**
* Apply a coupon to the billable entity.
*
* @param string $coupon
*/
public function applyCoupon($coupon)
{
$customer = $this->asStripeCustomer();
$customer->coupon = $coupon;
$customer->save();
}
/**
* Determine if the user is actively subscribed to one of the given plans.
*
* @param array|string $plans
* @param string $subscription
*
* @return bool
*/
public function subscribedToPlan($plans, $subscription = 'default'): bool
{
$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): bool
{
$plan = $this->getSubscriptions()->where(['stripe_plan' => $plan])->one();
return !is_null($plan) && $plan->valid();
}
/**
* Determine if the entity has a Stripe customer ID.
*
* @return bool
*/
public function hasStripeId(): bool
{
return !is_null($this->stripe_id);
}
/**
* Create a Stripe customer for the given user.
*
* @param string $token
* @param array $options
*
* @return Customer
*/
public function createAsStripeCustomer(string $token, array $options = []): Customer
{
$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 = Customer::create($options, $this->getStripeKey());
$this->stripe_id = $customer->id;
$this->save();
// Next we will add the credit card to the user's account on Stripe using this
// token that was provided to this method. This will allow us to bill users
// when they subscribe to plans or we need to do one-off charges on them.
if (!is_null($token)) {
$this->updateCard($token);
}
return $customer;
}
/**
* Get the Stripe customer for the user.
*
* @return Customer
*/
public function asStripeCustomer(): Customer
{
return Customer::retrieve($this->stripe_id, $this->getStripeKey());
}
/**
* Get the Stripe supported currency used by the entity.
*
* @return string
*/
public function preferredCurrency(): string
{
return Cashier::usesCurrency();
}
/**
* Get the tax percentage to apply to the subscription.
*
* @return int
*/
public function taxPercentage(): int
{
return 0;
}
/**
* Get the Stripe API key.
*
* @return string
*/
public static function getStripeKey(): string
{
return static::$stripeKey ?: Yii::$app->params['stripe']['apiKey'];
}
/**
* Set the Stripe API key.
*
* @param string $key
*/
public static function setStripeKey($key): void
{
static::$stripeKey = $key;
}
}