Passed
Pull Request — master (#48)
by Rafael
06:13
created

handleCustomerSubscriptionUpdated()   C

Complexity

Conditions 12
Paths 74

Size

Total Lines 45
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 0
Metric Value
cc 12
eloc 25
nc 74
nop 1
dl 0
loc 45
ccs 0
cts 36
cp 0
crap 156
rs 6.9666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gewaer\Api\Controllers;
6
7
use Phalcon\Http\Response;
8
use Gewaer\Models\Users;
9
use Carbon\Carbon;
10
use Gewaer\Exception\NotFoundHttpException;
11
use Gewaer\Traits\EmailTrait;
12
13
/**
14
 * Class PaymentsController
15
 *
16
 * Class to handle payment webhook from our cashier library
17
 *
18
 * @package Gewaer\Api\Controllers
19
 *
20
 */
21
class PaymentsController extends BaseController
22
{
23
    /**
24
     * Handle stripe webhoook calls
25
     *
26
     * @return Response
27
     */
28
    public function handleWebhook(): Response
29
    {
30
        //we cant processs if we dont find the stripe header
31
        if (!$this->request->hasHeader('Stripe-Signature')) {
32
            throw new NotFoundHttpException('Route not found for this call');
33
        }
34
35
        $request = $this->request->getPost();
36
37
        if (empty($request)) {
38
            $request = $this->request->getJsonRawBody(true);
39
        }
40
        $type = str_replace('.', '', ucwords(str_replace('_', '', $request['type']), '.'));
41
        $method = 'handle' . $type;
42
        if (method_exists($this, $method)) {
43
            return $this->{$method}($request);
44
        } else {
45
            return $this->response(['Missing Method to Handled']);
46
        }
47
    }
48
49
    /**
50
     * Handle customer subscription updated.
51
     *
52
     * @param  array $payload
53
     * @return Response
54
     */
55
    protected function handleCustomerSubscriptionUpdated(array $payload): Response
56
    {
57
        $user = Users::findFirstByStripeId($payload['data']['object']['customer']);
58
        if ($user) {
59
            $data = $payload['data']['object'];
60
            //get the current subscription they are updating
61
            $subscription = $user->getAllSubscriptions('stripe_id =' . $data['id']);
62
63
            if (is_object($subscription)) {
64
                // Quantity...
65
                if (isset($data['quantity'])) {
66
                    $subscription->quantity = $data['quantity'];
67
                }
68
                // Plan...
69
                if (isset($data['plan']['id'])) {
70
                    $subscription->stripe_plan = $data['plan']['id'];
71
                }
72
                // Trial ending date...
73
                if (isset($data['trial_end'])) {
74
                    $trial_ends = Carbon::createFromTimestamp($data['trial_end']);
75
                    if (!$subscription->trial_ends_at || $subscription->trial_ends_at->ne($trial_ends)) {
76
                        $subscription->trial_ends_at = $trial_ends;
77
                    }
78
                }
79
                // Cancellation date...
80
                if (isset($data['cancel_at_period_end']) && $data['cancel_at_period_end']) {
81
                    $subscription->ends_at = $subscription->onTrial()
82
                        ? $subscription->trial_ends_at
83
                        : Carbon::createFromTimestamp($data['current_period_end']);
84
                }
85
86
                if ($subscription->update()) {
87
                    $subject = "{$user->firstname} {$user->lastname} Updated Subscription";
88
                    $content = "Dear user {$user->firstname} {$user->lastname}, your subscription has been updated.";
89
90
                    $template = [
91
                        'subject' => $subject,
92
                        'content' => $content
93
                    ];
94
                    //We need to send a mail to the user
95
                    EmailTrait::sendWebhookEmail($user->email, $template);
96
                }
97
            }
98
        }
99
        return $this->response(['Webhook Handled']);
100
    }
101
102
    /**
103
     * Handle a cancelled customer from a Stripe subscription.
104
     *
105
     * @param  array  $payload
106
     * @return Response
107
     */
108
    protected function handleCustomerSubscriptionDeleted(array $payload): Response
109
    {
110
        $user = Users::findFirstByStripeId($payload['data']['object']['customer']);
111
        if ($user) {
112
            $subscription = $user->getAllSubscriptions('stripe_id =' . $payload['data']['object']['id']);
113
114
            if (is_object($subscription)) {
115
                $subscription->markAsCancelled();
116
            }
117
        }
118
        return $this->response(['Webhook Handled']);
119
    }
120
121
    /**
122
     * Handle customer subscription free trial ending.
123
     *
124
     * @param  array $payload
125
     * @return Response
126
     */
127
    protected function handleCustomerSubscriptionTrialwillend(array $payload): Response
128
    {
129
        $user = Users::findFirstByStripeId($payload['data']['object']['customer']);
130
        if ($user) {
131
            $subject = "{$user->firstname} {$user->lastname} Free Trial Ending";
132
            $content = "Dear user {$user->firstname} {$user->lastname}, your free trial is coming to an end.Please choose one of our available subscriptions. Thank you";
133
134
            $template = [
135
                'subject' => $subject,
136
                'content' => $content
137
            ];
138
            //We need to send a mail to the user
139
            EmailTrait::sendWebhookEmail($user->email, $template);
140
        }
141
        return $this->response(['Webhook Handled']);
142
    }
143
144
    /**
145
     * Handle customer updated.
146
     *
147
     * @param  array $payload
148
     * @return Response
149
     */
150
    protected function handleCustomerUpdated(array $payload): Response
151
    {
152
        if ($user = Users::findFirstByStripeId($payload['data']['object']['id'])) {
153
            $user->updateCardFromStripe();
154
        }
155
        return $this->response(['Webhook Handled']);
156
    }
157
158
    /**
159
     * Handle customer source deleted.
160
     *
161
     * @param  array $payload
162
     * @return Response
163
     */
164
    protected function handleCustomerSourceDeleted(array $payload) : Response
165
    {
166
        if ($user = Users::findFirstByStripeId($payload['data']['object']['customer'])) {
167
            $user->updateCardFromStripe();
168
        }
169
        return $this->response(['Webhook Handled']);
170
    }
171
172
    /**
173
     * Handle deleted customer.
174
     *
175
     * @param  array $payload
176
     * @return Response
177
     */
178
    protected function handleCustomerDeleted(array $payload) : Response
179
    {
180
        $user = Users::findFirstByStripeId($payload['data']['object']['id']);
181
        if ($user) {
182
            foreach ($user->subscriptions as $subscription) {
183
                $subscription->skipTrial()->markAsCancelled();
184
            }
185
186
            $user->stripe_id = null;
187
            $user->trial_ends_at = null;
188
            $user->card_brand = null;
189
            $user->card_last_four = null;
190
            $user->update();
191
        }
192
        return $this->response(['Webhook Handled']);
193
    }
194
195
    /**
196
     * Handle sucessfull payment
197
     *
198
     * @todo send email
199
     * @param array $payload
200
     * @return Response
201
     */
202
    protected function handleChargeSucceeded(array $payload): Response
203
    {
204
        $user = Users::findFirstByStripeId($payload['data']['object']['customer']);
205
        if ($user) {
206
            $subject = "{$user->firstname} {$user->lastname} Successful Payment";
207
            $content = "Dear user {$user->firstname} {$user->lastname}, your subscription payment of {$payload['data']['object']['amount']} was successful. Thank you";
208
209
            $template = [
210
                'subject' => $subject,
211
                'content' => $content
212
            ];
213
            //We need to send a mail to the user
214
            EmailTrait::sendWebhookEmail($user->email, $template);
215
        }
216
        return $this->response(['Webhook Handled']);
217
    }
218
219
    /**
220
     * Handle bad payment
221
     *
222
     * @todo send email
223
     * @param array $payload
224
     * @return Response
225
     */
226
    protected function handleChargeFailed(array $payload) : Response
227
    {
228
        $user = Users::findFirstByStripeId($payload['data']['object']['customer']);
229
        if ($user) {
230
            $subject = "{$user->firstname} {$user->lastname} Failed Payment";
231
            $content = "Dear user {$user->firstname} {$user->lastname}, your subscription presents a failed payment of the amount of {$payload['data']['object']['amount']}. Please check card expiration date";
232
233
            $template = [
234
                'subject' => $subject,
235
                'content' => $content
236
            ];
237
            //We need to send a mail to the user
238
            EmailTrait::sendWebhookEmail($user->email, $template);
239
        }
240
        return $this->response(['Webhook Handled']);
241
    }
242
243
    /**
244
     * Handle looking for refund
245
     *
246
     * @todo send email
247
     * @param array $payload
248
     * @return Response
249
     */
250
    protected function handleChargeDisputeCreated(array $payload) : Response
251
    {
252
        return $this->response(['Webhook Handled']);
253
    }
254
255
    /**
256
     * Handle pending payments
257
     *
258
     * @todo send email
259
     * @param array $payload
260
     * @return Response
261
     */
262
    protected function handleChargePending(array $payload) : Response
263
    {
264
        $user = Users::findFirstByStripeId($payload['data']['object']['customer']);
265
        if ($user) {
266
            $subject = "{$user->firstname} {$user->lastname} Pending Payment";
267
            $content = "Dear user {$user->firstname} {$user->lastname}, your subscription presents a pending payment of {$payload['data']['object']['amount']}";
268
269
            $template = [
270
                'subject' => $subject,
271
                'content' => $content
272
            ];
273
            //We need to send a mail to the user
274
            EmailTrait::sendWebhookEmail($user->email, $template);
275
        }
276
        return $this->response(['Webhook Handled']);
277
    }
278
}
279