Passed
Pull Request — master (#158)
by
unknown
02:33
created

Sadad::translateStatus()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 55
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 50
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 55
rs 9.0909

How to fix   Long Method   

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\Sadad;
4
5
use GuzzleHttp\Client;
6
use Shetabit\Multipay\Abstracts\Driver;
7
use Shetabit\Multipay\Exceptions\InvalidPaymentException;
8
use Shetabit\Multipay\Exceptions\PurchaseFailedException;
9
use Shetabit\Multipay\Contracts\ReceiptInterface;
10
use Shetabit\Multipay\Invoice;
11
use Shetabit\Multipay\Receipt;
12
use Shetabit\Multipay\RedirectionForm;
13
use Shetabit\Multipay\Request;
14
use DateTimeZone;
15
use DateTime;
16
17
class Sadad extends Driver
18
{
19
    /**
20
     * Sadad Client.
21
     *
22
     * @var object
23
     */
24
    protected $client;
25
26
    /**
27
     * Invoice
28
     *
29
     * @var Invoice
30
     */
31
    protected $invoice;
32
33
    /**
34
     * Driver settings
35
     *
36
     * @var object
37
     */
38
    protected $settings;
39
40
    /**
41
     * Sadad constructor.
42
     * Construct the class with the relevant settings.
43
     *
44
     * @param Invoice $invoice
45
     * @param $settings
46
     */
47
    public function __construct(Invoice $invoice, $settings)
48
    {
49
        $this->invoice($invoice);
50
        $this->settings = (object) $settings;
51
        $this->client = new Client();
52
    }
53
54
    /**
55
     * Purchase Invoice.
56
     *
57
     * @return string
58
     *
59
     * @throws PurchaseFailedException
60
     * @throws \GuzzleHttp\Exception\GuzzleException
61
     */
62
    public function purchase()
63
    {
64
        $terminalId = $this->settings->terminalId;
65
        $orderId = crc32($this->invoice->getUuid());
66
        $amount = $this->invoice->getAmount() * 10; // convert to rial
67
        $key = $this->settings->key;
68
69
        $signData = $this->encrypt_pkcs7("$terminalId;$orderId;$amount", $key);
70
        $iranTime = new DateTime('now', new DateTimeZone('Asia/Tehran'));
71
72
        //set Description for payment
73
        if (!empty($this->invoice->getDetails()['description'])) {
74
            $description = $this->invoice->getDetails()['description'];
75
        } else {
76
            $description = $this->settings->description;
77
        }
78
79
        //set MobileNo for get user cards
80
        if (!empty($this->invoice->getDetails()['mobile'])) {
81
            $mobile = $this->invoice->getDetails()['mobile'];
82
        } else {
83
            $mobile = "";
84
        }
85
86
        $data = array(
87
            'MerchantId' => $this->settings->merchantId,
88
            'ReturnUrl' => $this->settings->callbackUrl,
89
            'PaymentIdentity' => $this->settings->PaymentIdentity,
90
            'LocalDateTime' => $iranTime->format("m/d/Y g:i:s a"),
91
            'SignData' => $signData,
92
            'TerminalId' => $terminalId,
93
            'Amount' => $amount,
94
            'OrderId' => $orderId,
95
            'additionalData' => $description,
96
            'UserId' => $mobile,
97
        );
98
99
        $response = $this
100
            ->client
101
            ->request(
102
                'POST',
103
                $this->getPaymentUrl(),
104
                [
105
                    "json" => $data,
106
                    "headers" => [
107
                        'Content-Type' => 'application/json',
108
                        'User-Agent' => '',
109
                    ],
110
                    "http_errors" => false,
111
                ]
112
            );
113
114
        $body = @json_decode($response->getBody()->getContents());
115
116
        if (empty($body)) {
117
            throw new PurchaseFailedException('دسترسی به صفحه مورد نظر امکان پذیر نمی باشد.');
118
        } elseif ($body->ResCode != 0) {
119
            throw new PurchaseFailedException($body->Description);
120
        }
121
122
        $this->invoice->transactionId($body->Token);
123
124
        // return the transaction's id
125
        return $this->invoice->getTransactionId();
126
    }
127
128
    /**
129
     * Pay the Invoice
130
     *
131
     * @return RedirectionForm
132
     */
133
    public function pay() : RedirectionForm
134
    {
135
        $token = $this->invoice->getTransactionId();
136
        $payUrl = $this->getPurchaseUrl();
137
138
        return $this->redirectWithForm($payUrl, ['Token' => $token], 'GET');
139
    }
140
141
    /**
142
     * Verify payment
143
     *
144
     * @return ReceiptInterface
145
     *
146
     * @throws InvalidPaymentException
147
     * @throws \GuzzleHttp\Exception\GuzzleException
148
     */
149
    public function verify() : ReceiptInterface
150
    {
151
        $key = $this->settings->key;
152
        $token = $this->invoice->getTransactionId() ?? Request::input('token');
153
        $resCode = Request::input('ResCode');
154
155
        if ($resCode != 0) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $resCode of type mixed|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
156
            throw new InvalidPaymentException($this->translateStatus($resCode), $resCode);
157
        }
158
159
        $data = array(
160
            'Token' => $token,
161
            'SignData' => $this->encrypt_pkcs7($token, $key)
162
        );
163
164
        $response = $this
165
            ->client
166
            ->request(
167
                'POST',
168
                $this->settings->apiVerificationUrl,
169
                [
170
                    "json" => $data,
171
                    "headers" => [
172
                        'Content-Type' => 'application/json',
173
                        'User-Agent' => '',
174
                    ],
175
                    "http_errors" => false,
176
                ]
177
            );
178
179
        $body = json_decode($response->getBody()->getContents());
180
181
        $bodyResponse = $body->ResCode;
182
        if ($bodyResponse != 0) {
183
            throw new InvalidPaymentException($this->translateStatus($bodyResponse), $bodyResponse);
184
        }
185
186
        /**
187
         * شماره سفارش : $orderId = Request::input('OrderId')
188
         * شماره پیگیری : $body->SystemTraceNo
189
         * شماره مرجع : $body->RetrievalRefNo
190
         */
191
192
        $receipt = $this->createReceipt($body->SystemTraceNo);
193
        $receipt->detail([
194
            'orderId' => $body->OrderId,
195
            'traceNo' => $body->SystemTraceNo,
196
            'referenceNo' => $body->RetrivalRefNo,
197
            'description' => $body->Description,
198
        ]);
199
200
        return $receipt;
201
    }
202
203
    /**
204
     * Generate the payment's receipt
205
     *
206
     * @param $referenceId
207
     *
208
     * @return Receipt
209
     */
210
    protected function createReceipt($referenceId)
211
    {
212
        $receipt = new Receipt('sadad', $referenceId);
213
214
        return $receipt;
215
    }
216
217
    /**
218
     * Create sign data(Tripledes(ECB,PKCS7))
219
     *
220
     * @param $str
221
     * @param $key
222
     *
223
     * @return string
224
     */
225
    protected function encrypt_pkcs7($str, $key)
226
    {
227
        $key = base64_decode($key);
228
        $ciphertext = OpenSSL_encrypt($str, "DES-EDE3", $key, OPENSSL_RAW_DATA);
229
230
        return base64_encode($ciphertext);
231
    }
232
233
    /**
234
     * Retrieve payment mode.
235
     *
236
     * @return string
237
     */
238
    protected function getMode() : string
239
    {
240
        return strtolower($this->settings->mode);
241
    }
242
243
244
    /**
245
     * Retrieve purchase url
246
     *
247
     * @return string
248
     */
249
    protected function getPurchaseUrl() : string
250
    {
251
        $mode = $this->getMode();
252
253
        switch ($mode) {
254
            case 'paymentbyidentity':
255
                $url = $this->settings->apiPurchaseUrl;
256
                break;
257
            default: // default: normal
258
                $url = $this->settings->apiPurchaseUrl;
259
                break;
260
        }
261
262
        return $url;
263
    }
264
265
    /**
266
     * Retrieve Payment url
267
     *
268
     * @return string
269
     */
270
    protected function getPaymentUrl() : string
271
    {
272
        $mode = $this->getMode();
273
274
        switch ($mode) {
275
            case 'paymentbyidentity':
276
                $url = $this->settings->apiPaymentByIdentityUrl;
277
                break;
278
            default: // default: normal
279
                $url = $this->settings->apiPaymentUrl;
280
                break;
281
        }
282
283
        return $url;
284
    }
285
286
    /**
287
     * Convert status to a readable message.
288
     *
289
     * @param $status
290
     *
291
     * @return mixed|string
292
     */
293
    private function translateStatus($status)
294
    {
295
        $translations = [
296
            '0' => 'تراکنش با موفقیت انجام شد',
297
            '3' => 'پذيرنده کارت فعال نیست لطفا با بخش امور پذيرندگان، تماس حاصل فرمائید',
298
            '23' => 'پذيرنده کارت نا معتبر لطفا با بخش امور پذيرندگان، تماس حاصل فرمائید',
299
            '58' => 'انجام تراکنش مربوطه توسط پايانه ی انجام دهنده مجاز نمی باشد',
300
            '61' => 'مبلغ تراکنش از حد مجاز بالاتر است',
301
            '101' => 'مهلت ارسال تراکنش به پايان رسیده است',
302
            '1000' => 'ترتیب پارامترهای ارسالی اشتباه می باشد',
303
            '1001' => 'پارامترهای پرداخت اشتباه می باشد',
304
            '1002' => 'خطا در سیستم- تراکنش ناموفق',
305
            '1003' => 'IP پذيرنده اشتباه است',
306
            '1004' => 'شماره پذيرنده اشتباه است',
307
            '1005' => 'خطای دسترسی:لطفا بعدا تلاش فرمايید',
308
            '1006' => 'خطا در سیستم',
309
            '1011' => 'درخواست تکراری- شماره سفارش تکراری می باشد',
310
            '1012' => 'اطلاعات پذيرنده صحیح نیست، يکی از موارد تاريخ،زمان يا کلید تراکنش اشتباه است',
311
            '1015' => 'پاسخ خطای نامشخص از سمت مرکز',
312
            '1017' => 'مبلغ درخواستی شما جهت پرداخت از حد مجاز تعريف شده برای اين پذيرنده بیشتر است',
313
            '1018' => 'اشکال در تاريخ و زمان سیستم. لطفا تاريخ و زمان سرور خود را با بانک هماهنگ نمايید',
314
            '1019' => 'امکان پرداخت از طريق سیستم شتاب برای اين پذيرنده امکان پذير نیست',
315
            '1020' => 'پذيرنده غیرفعال شده است',
316
            '1023' => 'آدرس بازگشت پذيرنده نامعتبر است',
317
            '1024' => 'مهر زمانی پذيرنده نامعتبر است',
318
            '1025' => 'امضا تراکنش نامعتبر است',
319
            '1026' => 'شماره سفارش تراکنش نامعتبر است',
320
            '1027' => 'شماره پذيرنده نامعتبر است',
321
            '1028' => 'شماره ترمینال پذيرنده نامعتبر است',
322
            '1029' => 'آدرس IP پرداخت در محدوده آدرس های معتبر اعلام شده توسط پذيرنده نیست',
323
            '1030' => 'آدرس Domain پرداخت در محدوده آدرس های معتبر اعلام شده توسط پذیرنده نیست',
324
            '1031' => 'مهلت زمانی شما جهت پرداخت به پايان رسیده است.لطفا مجددا سعی بفرمایید',
325
            '1032' => 'پرداخت با اين کارت , برای پذيرنده مورد نظر شما امکان پذير نیست',
326
            '1033' => 'به علت مشکل در سايت پذيرنده, پرداخت برای اين پذيرنده غیرفعال شده است',
327
            '1036' => 'اطلاعات اضافی ارسال نشده يا دارای اشکال است',
328
            '1037' => 'شماره پذيرنده يا شماره ترمینال پذيرنده صحیح نمیباشد',
329
            '1053' => 'خطا: درخواست معتبر، از سمت پذيرنده صورت نگرفته است لطفا اطلاعات پذيرنده خود را چک کنید',
330
            '1055' => 'مقدار غیرمجاز در ورود اطلاعات',
331
            '1056' => 'سیستم موقتا قطع میباشد.لطفا بعدا تلاش فرمايید',
332
            '1058' => 'سرويس پرداخت اينترنتی خارج از سرويس می باشد.لطفا بعدا سعی بفرمایید',
333
            '1061' => 'اشکال در تولید کد يکتا. لطفا مرورگر خود را بسته و با اجرای مجدد عملیات پرداخت را انجام دهید',
334
            '1064' => 'لطفا مجددا سعی بفرمايید',
335
            '1065' => 'ارتباط ناموفق .لطفا چند لحظه ديگر مجددا سعی کنید',
336
            '1066' => 'سیستم سرويس دهی پرداخت موقتا غیر فعال شده است',
337
            '1068' => 'با عرض پوزش به علت بروزرسانی , سیستم موقتا قطع میباشد',
338
            '1072' => 'خطا در پردازش پارامترهای اختیاری پذيرنده',
339
            '1101' => 'مبلغ تراکنش نامعتبر است',
340
            '1103' => 'توکن ارسالی نامعتبر است',
341
            '1104' => 'اطلاعات تسهیم صحیح نیست',
342
            '1105' => 'تراکنش بازگشت داده شده است(مهلت زمانی به پايان رسیده است)'
343
        ];
344
345
        $unknownError = 'خطای ناشناخته رخ داده است. در صورت کسر مبلغ از حساب حداکثر پس از 72 ساعت به حسابتان برمیگردد';
346
347
        return array_key_exists($status, $translations) ? $translations[$status] : $unknownError;
348
    }
349
}
350