Nextpay::purchase()   D
last analyzed

Complexity

Conditions 10
Paths 512

Size

Total Lines 55
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 10
eloc 30
c 5
b 0
f 0
nc 512
nop 0
dl 0
loc 55
rs 4.1777

How to fix   Long Method    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
namespace Shetabit\Multipay\Drivers\Nextpay;
4
5
use GuzzleHttp\Client;
6
use Shetabit\Multipay\Abstracts\Driver;
7
use Shetabit\Multipay\Contracts\ReceiptInterface;
8
use Shetabit\Multipay\Exceptions\InvalidPaymentException;
9
use Shetabit\Multipay\Exceptions\PurchaseFailedException;
10
use Shetabit\Multipay\Invoice;
11
use Shetabit\Multipay\Receipt;
12
use Shetabit\Multipay\RedirectionForm;
13
use Shetabit\Multipay\Request;
14
15
class Nextpay extends Driver
16
{
17
    /**
18
     * Nextpay Client.
19
     *
20
     * @var Client
21
     */
22
    protected $client;
23
24
    /**
25
     * Invoice
26
     *
27
     * @var Invoice
28
     */
29
    protected $invoice;
30
31
    /**
32
     * Driver settings
33
     *
34
     * @var object
35
     */
36
    protected $settings;
37
38
    /**
39
     * Nextpay constructor.
40
     * Construct the class with the relevant settings.
41
     *
42
     * @param Invoice $invoice
43
     * @param $settings
44
     */
45
    public function __construct(Invoice $invoice, $settings)
46
    {
47
        $this->invoice($invoice);
48
        $this->settings = (object)$settings;
49
        $this->client = new Client();
50
    }
51
52
    /**
53
     * Purchase Invoice.
54
     *
55
     * @return string
56
     *
57
     * @throws PurchaseFailedException
58
     * @throws \GuzzleHttp\Exception\GuzzleException
59
     */
60
    public function purchase()
61
    {
62
        $data = [
63
            'api_key' => $this->settings->merchantId,
64
            'order_id' => intval(1, time()) . crc32($this->invoice->getUuid()),
65
            'amount' => $this->invoice->getAmount() / ($this->settings->currency == 'T' ? 1 : 10), // convert to toman
66
            'callback_uri' => $this->settings->callbackUrl,
67
        ];
68
69
        if (isset($this->invoice->getDetails()['customer_phone'])) {
70
            $data['customer_phone'] = $this->invoice->getDetails()['customer_phone'];
71
        }
72
73
        if (isset($this->invoice->getDetails()['custom_json_fields'])) {
74
            $data['custom_json_fields'] = $this->invoice->getDetails()['custom_json_fields'];
75
        }
76
77
        if (isset($this->invoice->getDetails()['payer_name'])) {
78
            $data['payer_name'] = $this->invoice->getDetails()['payer_name'];
79
        }
80
81
        if (isset($this->invoice->getDetails()['payer_desc'])) {
82
            $data['payer_desc'] = $this->invoice->getDetails()['payer_desc'];
83
        }
84
85
        if (isset($this->invoice->getDetails()['auto_verify'])) {
86
            $data['auto_verify'] = $this->invoice->getDetails()['auto_verify'];
87
        }
88
89
        if (isset($this->invoice->getDetails()['allowed_card'])) {
90
            $data['allowed_card'] = $this->invoice->getDetails()['allowed_card'];
91
        }
92
93
        $response = $this
94
            ->client
95
            ->request(
96
                'POST',
97
                $this->settings->apiPurchaseUrl,
98
                [
99
                    "form_params" => $data,
100
                    "http_errors" => false,
101
                ]
102
            );
103
104
        $body = json_decode($response->getBody()->getContents(), true);
105
        $code = isset($body['code']) ? $body['code'] : '';
106
107
        if ($code != -1) {
108
            throw new PurchaseFailedException($this->translateStatusCode($code), $code);
0 ignored issues
show
Bug introduced by
It seems like $code can also be of type string; however, parameter $code of Shetabit\Multipay\Except...xception::__construct() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

108
            throw new PurchaseFailedException($this->translateStatusCode($code), /** @scrutinizer ignore-type */ $code);
Loading history...
109
        }
110
111
        $this->invoice->transactionId($body['trans_id']);
112
113
        // return the transaction's id
114
        return $this->invoice->getTransactionId();
115
    }
116
117
    /**
118
     * Pay the Invoice
119
     *
120
     * @return RedirectionForm
121
     */
122
    public function pay(): RedirectionForm
123
    {
124
        $payUrl = $this->settings->apiPaymentUrl . $this->invoice->getTransactionId();
125
126
        return $this->redirectWithForm($payUrl, [], 'GET');
127
    }
128
129
    /**
130
     * Verify payment
131
     *
132
     * @return ReceiptInterface
133
     *
134
     * @throws InvalidPaymentException
135
     * @throws \GuzzleHttp\Exception\GuzzleException
136
     */
137
    public function verify(): ReceiptInterface
138
    {
139
        $transactionId = $this->invoice->getTransactionId() ?? Request::input('trans_id');
140
141
        $data = [
142
            'api_key' => $this->settings->merchantId,
143
            'order_id' => Request::input('order_id'),
144
            'amount' => $this->invoice->getAmount() / ($this->settings->currency == 'T' ? 1 : 10), // convert to toman
145
            'trans_id' => $transactionId,
146
        ];
147
148
        $response = $this
149
            ->client
150
            ->request(
151
                'POST',
152
                $this->settings->apiVerificationUrl,
153
                [
154
                    "form_params" => $data,
155
                    "http_errors" => false,
156
                ]
157
            );
158
159
        $body = json_decode($response->getBody()->getContents(), true);
160
        $code = isset($body['code']) ? $body['code'] : '';
161
162
        if ($code != 0) {
163
            throw new InvalidPaymentException($this->translateStatusCode($code), $code);
0 ignored issues
show
Bug introduced by
It seems like $code can also be of type string; however, parameter $code of Shetabit\Multipay\Except...xception::__construct() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

163
            throw new InvalidPaymentException($this->translateStatusCode($code), /** @scrutinizer ignore-type */ $code);
Loading history...
164
        }
165
166
        return $this->createReceipt($body['Shaparak_Ref_Id']);
167
    }
168
169
    /**
170
     * Generate the payment's receipt
171
     *
172
     * @param $referenceId
173
     *
174
     * @return Receipt
175
     */
176
    protected function createReceipt($referenceId)
177
    {
178
        $receipt = new Receipt('nextpay', $referenceId);
179
180
        return $receipt;
181
    }
182
183
184
    /**
185
     * Convert status to a readable message.
186
     *
187
     * @param $code
188
     *
189
     * @return string
190
     */
191
    private function translateStatusCode($code): string
192
    {
193
        $translations = [
194
            0 => 'پرداخت تکمیل و با موفقیت انجام شده است',
195
            -1 => 'منتظر ارسال تراکنش و ادامه پرداخت',
196
            -2 => 'پرداخت رد شده توسط کاربر یا بانک',
197
            -3 => 'پرداخت در حال انتظار جواب بانک',
198
            -4 => 'پرداخت لغو شده است',
199
            -20 => 'کد api_key ارسال نشده است',
200
            -21 => 'کد trans_id ارسال نشده است',
201
            -22 => 'مبلغ ارسال نشده',
202
            -23 => 'لینک ارسال نشده',
203
            -24 => 'مبلغ صحیح نیست',
204
            -25 => 'تراکنش قبلا انجام و قابل ارسال نیست',
205
            -26 => 'مقدار توکن ارسال نشده است',
206
            -27 => 'شماره سفارش صحیح نیست',
207
            -28 => 'مقدار فیلد سفارشی [custom_json_fields] از نوع json نیست',
208
            -29 => 'کد بازگشت مبلغ صحیح نیست',
209
            -30 => 'مبلغ کمتر از حداقل پرداختی است',
210
            -31 => 'صندوق کاربری موجود نیست',
211
            -32 => 'مسیر بازگشت صحیح نیست',
212
            -33 => 'کلید مجوز دهی صحیح نیست',
213
            -34 => 'کد تراکنش صحیح نیست',
214
            -35 => 'ساختار کلید مجوز دهی صحیح نیست',
215
            -36 => 'شماره سفارش ارسال نشد است',
216
            -37 => 'شماره تراکنش یافت نشد',
217
            -38 => 'توکن ارسالی موجود نیست',
218
            -39 => 'کلید مجوز دهی موجود نیست',
219
            -40 => 'کلید مجوزدهی مسدود شده است',
220
            -41 => 'خطا در دریافت پارامتر، شماره شناسایی صحت اعتبار که از بانک ارسال شده موجود نیست',
221
            -42 => 'سیستم پرداخت دچار مشکل شده است',
222
            -43 => 'درگاه پرداختی برای انجام درخواست یافت نشد',
223
            -44 => 'پاسخ دریاف شده از بانک نامعتبر است',
224
            -45 => 'سیستم پرداخت غیر فعال است',
225
            -46 => 'درخواست نامعتبر',
226
            -47 => 'کلید مجوز دهی یافت نشد [حذف شده]',
227
            -48 => 'نرخ کمیسیون تعیین نشده است',
228
            -49 => 'تراکنش مورد نظر تکراریست',
229
            -50 => 'حساب کاربری برای صندوق مالی یافت نشد',
230
            -51 => 'شناسه کاربری یافت نشد',
231
            -52 => 'حساب کاربری تایید نشده است',
232
            -60 => 'ایمیل صحیح نیست',
233
            -61 => 'کد ملی صحیح نیست',
234
            -62 => 'کد پستی صحیح نیست',
235
            -63 => 'آدرس پستی صحیح نیست و یا بیش از ۱۵۰ کارکتر است',
236
            -64 => 'توضیحات صحیح نیست و یا بیش از ۱۵۰ کارکتر است',
237
            -65 => 'نام و نام خانوادگی صحیح نیست و یا بیش از ۳۵ کاکتر است',
238
            -66 => 'تلفن صحیح نیست',
239
            -67 => 'نام کاربری صحیح نیست یا بیش از ۳۰ کارکتر است',
240
            -68 => 'نام محصول صحیح نیست و یا بیش از ۳۰ کارکتر است',
241
            -69 => 'آدرس ارسالی برای بازگشت موفق صحیح نیست و یا بیش از ۱۰۰ کارکتر است',
242
            -70 => 'آدرس ارسالی برای بازگشت ناموفق صحیح نیست و یا بیش از ۱۰۰ کارکتر است',
243
            -71 => 'موبایل صحیح نیست',
244
            -72 => 'بانک پاسخگو نبوده است لطفا با نکست پی تماس بگیرید',
245
            -73 => 'مسیر بازگشت دارای خطا میباشد یا بسیار طولانیست',
246
            -90 => 'بازگشت مبلغ بدرستی انجام شد',
247
            -91 => 'عملیات ناموفق در بازگشت مبلغ',
248
            -92 => 'در عملیات بازگشت مبلغ خطا رخ داده است',
249
            -93 => 'موجودی صندوق کاربری برای بازگشت مبلغ کافی نیست',
250
            -94 => 'کلید بازگشت مبلغ یافت نشد',
251
        ];
252
        $unknownError = 'خطای ناشناخته رخ داده است. در صورت کسر مبلغ از حساب حداکثر پس از 72 ساعت به حسابتان برمیگردد';
253
254
        return array_key_exists($code, $translations) ? $translations[$code] : $unknownError;
255
    }
256
}
257