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

Payir::extractDetails()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Shetabit\Payment\Drivers\Payir;
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 Payir extends Driver
11
{
12
    /**
13
     * Payir 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
     * Payir 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
     * Retrieve data from details using its name.
49
     *
50
     * @return string
51
     */
52
    private function extractDetails($name)
53
    {
54
        return empty($this->invoice->getDetails()[$name]) ? null : $this->invoice->getDetails()[$name];
55
    }
56
57
    /**
58
     * Purchase Invoice.
59
     *
60
     * @return string
61
     *
62
     * @throws PurchaseFailedException
63
     * @throws \GuzzleHttp\Exception\GuzzleException
64
     */
65
    public function purchase()
66
    {
67
        $mobile = $this->extractDetails('mobile');
68
        $description = $this->extractDetails('description');
69
        $validCardNumber = $this->extractDetails('validCardNumber');
70
71
        $data = array(
72
            'api' => $this->settings->merchantId,
73
            'amount' => $this->invoice->getAmount(),
74
            'redirect' => $this->settings->callbackUrl,
75
            'mobile' => $mobile,
76
            'description' => $description,
77
            'factorNumber' => $this->invoice->getUuid(),
78
            'validCardNumber' => $validCardNumber
79
        );
80
81
        $response = $this->client->request(
82
            'POST',
83
            $this->settings->apiPurchaseUrl,
84
            [
85
                "form_params" => $data,
86
                "http_errors" => false,
87
            ]
88
        );
89
        $body = json_decode($response->getBody()->getContents(), true);
90
91
        if ($body['status'] == 1) {
92
            $this->invoice->transactionId($body['token']);
93
        } else {
94
            // some error has happened
95
            throw new PurchaseFailedException($body['id']);
96
        }
97
98
        // return the transaction's id
99
        return $this->invoice->getTransactionId();
100
    }
101
102
    /**
103
     * Pay the Invoice
104
     *
105
     * @return \Illuminate\Http\RedirectResponse|mixed
106
     */
107
    public function pay()
108
    {
109
        $payUrl = $this->settings->apiPaymentUrl.$this->invoice->getTransactionId();
110
111
        // redirect using laravel logic
112
        return redirect()->to($payUrl);
113
    }
114
115
    /**
116
     * Verify payment
117
     *
118
     * @return ReceiptInterface
119
     *
120
     * @throws InvalidPaymentException
121
     * @throws \GuzzleHttp\Exception\GuzzleException
122
     */
123
    public function verify() : ReceiptInterface
124
    {
125
        $data = [
126
            'api' => $this->settings->merchantId,
127
            'token'  => $this->invoice->getTransactionId() ?? request()->input('token'),
128
        ];
129
130
        $response = $this->client->request(
131
            'POST',
132
            $this->settings->apiVerificationUrl,
133
            [
134
                "form_params" => $data,
135
                "http_errors" => false,
136
            ]
137
        );
138
        $body = json_decode($response->getBody()->getContents(), true);
139
140
        if ($body['status'] != 1) {
141
            $this->notVerified($body['errorCode']);
142
        }
143
144
        return $this->createReceipt($body['transId']);
145
    }
146
147
148
    /**
149
     * Generate the payment's receipt
150
     *
151
     * @param $referenceId
152
     *
153
     * @return Receipt
154
     */
155
    public function createReceipt($referenceId)
156
    {
157
        $receipt = new Receipt('payir', $referenceId);
158
159
        return $receipt;
160
    }
161
162
    /**
163
     * Trigger an exception
164
     *
165
     * @param $status
166
     *
167
     * @throws InvalidPaymentException
168
     */
169
    private function notVerified($status)
170
    {
171
        $translations = array(
172
            "-1" => "ارسال api الزامی می باشد",
173
            "-2" => "ارسال transId الزامی می باشد",
174
            "-3" => "درگاه پرداختی با api ارسالی یافت نشد و یا غیر فعال می باشد",
175
            "-4" => "فروشنده غیر فعال می باشد",
176
            "-5" => "تراکنش با خطا مواجه شده است",
177
        );
178
179
        if (array_key_exists($status, $translations)) {
180
            throw new InvalidPaymentException($translations[$status]);
181
        } else {
182
            throw new InvalidPaymentException('خطای ناشناخته ای رخ داده است.');
183
        }
184
    }
185
}
186