Passed
Push — master ( 437f23...0ad4c0 )
by mahdi
03:18
created

Idpay::verify()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 29
rs 9.7
c 0
b 0
f 0
cc 3
nc 2
nop 0
1
<?php
2
3
namespace Shetabit\Payment\Drivers\Idpay;
4
5
use GuzzleHttp\Client;
6
use Shetabit\Payment\Abstracts\Driver;
7
use Shetabit\Payment\Exceptions\{InvalidPaymentException, PurchaseFailedException};
8
use Shetabit\Payment\{Contracts\ReceiptInterface, Invoice, Receipt};
9
10
class Idpay extends Driver
11
{
12
    /**
13
     * Idpay Client.
14
     *
15
     * @var object
16
     */
17
    protected $client;
18
19
    /**
20
     * Invoice
21
     *
22
     * @var Invoice
23
     */
24
    protected $invoice;
25
26
    /**
27
     * Driver settings
28
     *
29
     * @var object
30
     */
31
    protected $settings;
32
33
    /**
34
     * Idpay constructor.
35
     * Construct the class with the relevant settings.
36
     *
37
     * @param Invoice $invoice
38
     * @param $settings
39
     */
40
    public function __construct(Invoice $invoice, $settings)
41
    {
42
        $this->invoice($invoice);
43
        $this->settings = (object) $settings;
44
        $this->client = new Client();
45
    }
46
47
    /**
48
     * Purchase Invoice.
49
     *
50
     * @return string
51
     *
52
     * @throws PurchaseFailedException
53
     * @throws \GuzzleHttp\Exception\GuzzleException
54
     */
55
    public function purchase()
56
    {
57
        $details = $this->invoice->getDetails();
58
59
        $data = array(
60
            'order_id' => $this->invoice->getUuid(),
61
            'amount' => $this->invoice->getAmount(),
62
            'name' => $details['name'] ?? null,
63
            'phone' => $details['mobile'] ?? $details['phone'] ?? null,
64
            'mail' => $details['email'] ?? $details['mail'] ?? null,
65
            'desc' => $details['description'] ?? $details['desc'] ?? $this->settings->description,
66
            'callback' => $this->settings->callbackUrl,
67
            'reseller' => $details['reseller'] ?? null,
68
        );
69
70
        $response = $this
71
            ->client
72
            ->request(
73
                'POST',
74
                $this->settings->apiPurchaseUrl,
75
                [
76
                    "json" => $data,
77
                    "headers" => [
78
                        'X-API-KEY' => $this->settings->merchantId,
79
                        'Content-Type' => 'application/json',
80
                        'X-SANDBOX' => (int) $this->settings->sandbox,
81
                    ],
82
                    "http_errors" => false,
83
                ]
84
            );
85
86
        $body = json_decode($response->getBody()->getContents(), true);
87
88
        if (empty($body['id'])) {
89
            // error has happened
90
            $message = 'خطا در هنگام درخواست برای پرداخت با کد '.$body['id'].' رخ داده است.';
91
            throw new PurchaseFailedException($message);
92
        }
93
94
        $this->invoice->transactionId($body['id']);
95
96
        // return the transaction's id
97
        return $this->invoice->getTransactionId();
98
    }
99
100
    /**
101
     * Pay the Invoice
102
     *
103
     * @return \Illuminate\Http\RedirectResponse|mixed
104
     */
105
    public function pay()
106
    {
107
        $apiUrl =  $this->settings->apiPaymentUrl;
108
109
        // use sandbox url if we are in sandbox mode
110
        if (!empty($this->settings->sandbox)) {
111
            $apiUrl = $this->settings->apiSandboxPaymentUrl;
112
        }
113
114
        $payUrl = $apiUrl.$this->invoice->getTransactionId();
115
116
        // redirect using laravel logic
117
        return redirect()->to($payUrl);
118
    }
119
120
    /**
121
     * Verify payment
122
     *
123
     * @return mixed|void
124
     *
125
     * @throws InvalidPaymentException
126
     * @throws \GuzzleHttp\Exception\GuzzleException
127
     */
128
    public function verify() : ReceiptInterface
129
    {
130
        $data = [
131
            'id' => $this->invoice->getTransactionId() ?? request()->input('id'),
132
            'order_id' => request()->input('order_id'),
133
        ];
134
135
        $response = $this->client->request(
136
            'POST',
137
            $this->settings->apiVerificationUrl,
138
            [
139
                'json' => $data,
140
                "headers" => [
141
                    'X-API-KEY' => $this->settings->merchantId,
142
                    'Content-Type' => 'application/json',
143
                    'X-SANDBOX' => (int) $this->settings->sandbox,
144
                ],
145
                "http_errors" => false,
146
            ]
147
        );
148
        $body = json_decode($response->getBody()->getContents(), true);
149
150
        if (isset($body['error_code']) || $body['status'] != 100) {
151
            $errorCode = $body['status'] ?? $body['error_code'];
152
153
            $this->notVerified($errorCode);
154
        }
155
156
        return $this->createReceipt($body['track_id']);
157
    }
158
159
    /**
160
     * Generate the payment's receipt
161
     *
162
     * @param $referenceId
163
     *
164
     * @return Receipt
165
     */
166
    public function createReceipt($referenceId)
167
    {
168
        $receipt = new Receipt('idpay', $referenceId);
169
170
        return $receipt;
171
    }
172
173
    /**
174
     * Trigger an exception
175
     *
176
     * @param $status
177
     *
178
     * @throws InvalidPaymentException
179
     */
180
    private function notVerified($status)
181
    {
182
        $translations = array(
183
            "1" => "پرداخت انجام نشده است.",
184
            "2" => "پرداخت ناموفق بوده است.",
185
            "3" => "خطا رخ داده است.",
186
            "4" => "بلوکه شده.",
187
            "5" => "برگشت به پرداخت کننده.",
188
            "6" => "برگشت خورده سیستمی.",
189
            "10" => "در انتظار تایید پرداخت.",
190
            "100" => "پرداخت تایید شده است.",
191
            "101" => "پرداخت قبلا تایید شده است.",
192
            "200" => "به دریافت کننده واریز شد.",
193
            "11" => "کاربر مسدود شده است.",
194
            "12" => "API Key یافت نشد.",
195
            "13" => "درخواست شما از {ip} ارسال شده است. این IP با IP های ثبت شده در وب سرویس همخوانی ندارد.",
196
            "14" => "وب سرویس تایید نشده است.",
197
            "21" => "حساب بانکی متصل به وب سرویس تایید نشده است.",
198
            "31" => "کد تراکنش id نباید خالی باشد.",
199
            "32" => "شماره سفارش order_id نباید خالی باشد.",
200
            "33" => "مبلغ amount نباید خالی باشد.",
201
            "34" => "مبلغ amount باید بیشتر از {min-amount} ریال باشد.",
202
            "35" => "مبلغ amount باید کمتر از {max-amount} ریال باشد.",
203
            "36" => "مبلغ amount بیشتر از حد مجاز است.",
204
            "37" => "آدرس بازگشت callback نباید خالی باشد.",
205
            "38" => "درخواست شما از آدرس {domain} ارسال شده است. دامنه آدرس بازگشت callback با آدرس ثبت شده در وب سرویس همخوانی ندارد.",
206
            "51" => "تراکنش ایجاد نشد.",
207
            "52" => "استعلام نتیجه ای نداشت.",
208
            "53" => "تایید پرداخت امکان پذیر نیست.",
209
            "54" => "مدت زمان تایید پرداخت سپری شده است.",
210
        );
211
        if (array_key_exists($status, $translations)) {
212
            throw new InvalidPaymentException($translations[$status]);
213
        } else {
214
            throw new InvalidPaymentException('خطای ناشناخته ای رخ داده است.');
215
        }
216
    }
217
}
218