Passed
Push — master ( c6cf66...362d3b )
by mahdi
02:09
created

Behpardakht::translateStatus()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 52
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 47
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 52
rs 9.1563

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\Behpardakht;
4
5
use Shetabit\Multipay\Abstracts\Driver;
6
use Shetabit\Multipay\Exceptions\InvalidPaymentException;
7
use Shetabit\Multipay\Exceptions\PurchaseFailedException;
8
use Shetabit\Multipay\Contracts\ReceiptInterface;
9
use Shetabit\Multipay\Invoice;
10
use Shetabit\Multipay\Receipt;
11
use Shetabit\Multipay\Request;
12
use Carbon\Carbon;
13
use Shetabit\Multipay\RedirectionForm;
14
15
class Behpardakht extends Driver
16
{
17
    /**
18
     * Invoice
19
     *
20
     * @var Invoice
21
     */
22
    protected $invoice;
23
24
    /**
25
     * Driver settings
26
     *
27
     * @var object
28
     */
29
    protected $settings;
30
31
    /**
32
     * Behpardakht constructor.
33
     * Construct the class with the relevant settings.
34
     *
35
     * @param Invoice $invoice
36
     * @param $settings
37
     */
38
    public function __construct(Invoice $invoice, $settings)
39
    {
40
        $this->invoice($invoice);
41
        $this->settings = (object) $settings;
42
    }
43
44
    /**
45
     * Purchase Invoice.
46
     *
47
     * @return string
48
     *
49
     * @throws PurchaseFailedException
50
     * @throws \SoapFault
51
     */
52
53
    public function purchase()
54
    {
55
        $soap = new \SoapClient($this->settings->apiPurchaseUrl);
56
        $response = $soap->bpPayRequest($this->preparePurchaseData());
57
58
        // fault has happened in bank gateway
59
        if ($response->return == 21) {
60
            throw new PurchaseFailedException('پذیرنده معتبر نیست.', 21);
61
        }
62
63
        $data = explode(',', $response->return);
64
65
        // purchase was not successful
66
        if ($data[0] != "0") {
67
            throw new PurchaseFailedException($this->translateStatus($data[0]), $data[0]);
0 ignored issues
show
Bug introduced by
$data[0] of type string is incompatible with the type integer expected by parameter $code of Shetabit\Multipay\Except...xception::__construct(). ( Ignorable by Annotation )

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

67
            throw new PurchaseFailedException($this->translateStatus($data[0]), /** @scrutinizer ignore-type */ $data[0]);
Loading history...
68
        }
69
70
        $this->invoice->transactionId($data[1]);
71
72
        // return the transaction's id
73
        return $this->invoice->getTransactionId();
74
    }
75
76
    /**
77
     * Pay the Invoice
78
     *
79
     * @return RedirectionForm
80
     */
81
    public function pay() : RedirectionForm
82
    {
83
        $payUrl = $this->settings->apiPaymentUrl;
84
85
        return $this->redirectWithForm(
86
            $payUrl,
87
            [
88
                'RefId' => $this->invoice->getTransactionId(),
89
            ],
90
            'POST'
91
        );
92
    }
93
94
    /**
95
     * Verify payment
96
     *
97
     * @return mixed|Receipt
98
     *
99
     * @throws InvalidPaymentException
100
     * @throws \SoapFault
101
     */
102
    public function verify() : ReceiptInterface
103
    {
104
        $resCode = Request::input('ResCode');
105
        if ($resCode != '0') {
106
            throw new InvalidPaymentException($this->translateStatus($resCode), $resCode);
107
        }
108
109
        $data = $this->prepareVerificationData();
110
        $soap = new \SoapClient($this->settings->apiVerificationUrl);
111
112
        // step1: verify request
113
        $verifyResponse = (int)$soap->bpVerifyRequest($data)->return;
114
        if ($verifyResponse != 0) {
115
            // rollback money and throw exception
116
            $soap->bpReversalRequest($data);
117
            throw new InvalidPaymentException($this->translateStatus($verifyResponse), $verifyResponse);
118
        }
119
120
        // step2: settle request
121
        $settleResponse = $soap->bpSettleRequest($data)->return;
122
        if ($settleResponse != 0) {
123
            // rollback money and throw exception
124
            $soap->bpReversalRequest($data);
125
            throw new InvalidPaymentException($this->translateStatus($settleResponse), $settleResponse);
126
        }
127
128
        return $this->createReceipt($data['saleReferenceId']);
129
    }
130
131
    /**
132
     * Generate the payment's receipt
133
     *
134
     * @param $referenceId
135
     *
136
     * @return Receipt
137
     */
138
    protected function createReceipt($referenceId)
139
    {
140
        return new Receipt('behpardakht', $referenceId);
141
    }
142
143
    /**
144
     * Prepare data for payment verification
145
     *
146
     * @return array
147
     */
148
    protected function prepareVerificationData()
149
    {
150
        $orderId = Request::input('SaleOrderId');
151
        $verifySaleOrderId = Request::input('SaleOrderId');
152
        $verifySaleReferenceId = Request::input('SaleReferenceId');
153
154
        return array(
155
            'terminalId'        => $this->settings->terminalId,
156
            'userName'          => $this->settings->username,
157
            'userPassword'      => $this->settings->password,
158
            'orderId'           => $orderId,
159
            'saleOrderId'       => $verifySaleOrderId,
160
            'saleReferenceId'   => $verifySaleReferenceId
161
        );
162
    }
163
164
    /**
165
     * Prepare data for purchasing invoice
166
     *
167
     * @return array
168
     */
169
    protected function preparePurchaseData()
170
    {
171
        if (!empty($this->invoice->getDetails()['description'])) {
172
            $description = $this->invoice->getDetails()['description'];
173
        } else {
174
            $description = $this->settings->description;
175
        }
176
177
        $payerId = $this->invoice->getDetails()['payerId'] ?? 0;
178
179
        return array(
180
            'terminalId'        => $this->settings->terminalId,
181
            'userName'          => $this->settings->username,
182
            'userPassword'      => $this->settings->password,
183
            'callBackUrl'       => $this->settings->callbackUrl,
184
            'amount'            => $this->invoice->getAmount() * 10, // convert to rial
185
            'localDate'         => Carbon::now()->format('Ymd'),
186
            'localTime'         => Carbon::now()->format('Gis'),
187
            'orderId'           => crc32($this->invoice->getUuid()),
188
            'additionalData'    => $description,
189
            'payerId'           => $payerId
190
        );
191
    }
192
193
    /**
194
     * Convert status to a readable message.
195
     *
196
     * @param $status
197
     *
198
     * @return mixed|string
199
     */
200
    private function translateStatus($status)
201
    {
202
        $translations = [
203
            '0' => 'تراکنش با موفقیت انجام شد',
204
            '11' => 'شماره کارت نامعتبر است',
205
            '12' => 'موجودی کافی نیست',
206
            '13' => 'رمز نادرست است',
207
            '14' => 'تعداد دفعات وارد کردن رمز بیش از حد مجاز است',
208
            '15' => 'کارت نامعتبر است',
209
            '16' => 'دفعات برداشت وجه بیش از حد مجاز است',
210
            '17' => 'کاربر از انجام تراکنش منصرف شده است',
211
            '18' => 'تاریخ انقضای کارت گذشته است',
212
            '19' => 'مبلغ برداشت وجه بیش از حد مجاز است',
213
            '111' => 'ضادر کننده کارت نامعتبر است',
214
            '112' => 'خطای سوییچ صادر کننده کارت',
215
            '113' => 'پاسخی از صادر کننده کارت دریافت نشد',
216
            '114' => 'دارنده کارت مجاز به انجام این تراکنش نیست',
217
            '21' => 'پذیرنده نامعتبر است',
218
            '23' => 'خطای امنیتی رخ داده است',
219
            '24' => 'اطلاعات کاربری پذیرنده نامعتبر است',
220
            '25' => 'مبلغ نامعتبر است',
221
            '31' => 'پاسخ نامعتبر است',
222
            '32' => 'فرمت اطلاعات وارد شده صحیح نمی باشد',
223
            '33' => 'حساب نامعتبر است',
224
            '34' => 'خطای سیستمی',
225
            '35' => 'تاریخ نامعتبر است',
226
            '41' => 'شماره درخواست تکراری است',
227
            '42' => 'تراکنش Sale یافت نشد',
228
            '43' => 'قبلا درخواست Verify داده شده است',
229
            '44' => 'درخواست Verify یافت نشد',
230
            '45' => 'تراکنش Settle شده است',
231
            '46' => 'تراکنش Settle نشده است',
232
            '47' => 'تراکنش Settle یافت نشد',
233
            '48' => 'تراکنش Reverse شده است',
234
            '412' => 'شناسه قبض نادرست است',
235
            '413' => 'شناسه پرداخت نادرست است',
236
            '414' => 'سازمان صادر کننده قبض نامعتبر است',
237
            '415' => 'زمان جلسه کاری به پایان رسیده است',
238
            '416' => 'خطا در ثبت اطلاعات',
239
            '417' => 'شناسه پرداخت کننده نامعتبر است',
240
            '418' => 'اشکال در تعریف اطلاعات مشتری',
241
            '419' => 'تعداد دفعات ورود اطلاعات از حد مجاز گذشته است',
242
            '421' => 'IP نامعتبر است',
243
            '51' => 'تراکنش تکراری است',
244
            '54' => 'تراکنش مرجع موجود نیست',
245
            '55' => 'تراکنش نامعتبر است',
246
            '61' => 'خطا در واریز'
247
        ];
248
249
        $unknownError = 'خطای ناشناخته رخ داده است.';
250
251
        return array_key_exists($status, $translations) ? $translations[$status] : $unknownError;
252
    }
253
}
254