Passed
Pull Request — master (#95)
by
unknown
02:47
created

Walleta::callApi()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 9
c 1
b 0
f 1
nc 1
nop 3
dl 0
loc 15
rs 9.9666
1
<?php
2
3
namespace Shetabit\Multipay\Drivers\Walleta;
4
5
use GuzzleHttp\Client;
6
use Shetabit\Multipay\Abstracts\Driver;
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\RedirectionForm;
12
13
class Walleta extends Driver
14
{
15
    /**
16
     * Invoice
17
     *
18
     * @var Invoice
19
     */
20
    protected $invoice;
21
22
    /**
23
     * Response
24
     *
25
     * @var object
26
     */
27
    protected $response;
28
29
    /**
30
     * Driver settings
31
     *
32
     * @var object
33
     */
34
    protected $settings;
35
36
    /**
37
     * Walleta constructor.
38
     * Construct the class with the relevant settings.
39
     *
40
     * @param Invoice $invoice
41
     * @param $settings
42
     */
43
    public function __construct(Invoice $invoice, $settings)
44
    {
45
        $this->invoice($invoice);
46
        $this->settings = (object)$settings;
47
    }
48
49
    /**
50
     * Purchase Invoice.09214125578
51
     *
52
     * @return string
53
     *
54
     * @throws PurchaseFailedException
55
     */
56
    public function purchase()
57
    {
58
        $result = $this->token();
59
60
        if (!isset($result['status_code']) or $result['status_code'] != 200) {
61
            $this->purchaseFailed($result['content']['type']);
62
        }
63
64
        $this->invoice->transactionId($result['content']['token']);
65
66
        // return the transaction's id
67
        return $this->invoice->getTransactionId();
68
    }
69
70
    /**
71
     * Pay the Invoice
72
     *
73
     * @return RedirectionForm
74
     */
75
    public function pay(): RedirectionForm
76
    {
77
        return $this->redirectWithForm($this->settings->apiPaymentUrl . $this->invoice->getTransactionId(), [], 'GET');
78
    }
79
80
    /**
81
     * Verify payment
82
     *
83
     * @return mixed|Receipt
84
     *
85
     * @throws PurchaseFailedException
86
     */
87
    public function verify(): ReceiptInterface
88
    {
89
        $result = $this->verifyTransaction();
90
91
        if (!isset($result['status_code']) or $result['status_code'] != 200) {
92
            $this->purchaseFailed($result['status_code']['type']);
93
        }
94
95
        $receipt = $this->createReceipt($this->invoice->getUuid());
96
97
        return $receipt;
98
    }
99
100
    /**
101
     * send request to Walleta
102
     *
103
     * @param $method
104
     * @param $url
105
     * @param array $data
106
     * @return array
107
     */
108
    protected function callApi($method, $url, $data = []): array
109
    {
110
        $client = new Client();
111
112
        $response = $client->request($method, $url, [
113
            "json" => $data,
114
            "headers" => [
115
                'Content-Type' => 'application/json',
116
            ],
117
            "http_errors" => false,
118
        ]);
119
120
        return [
121
            'status_code' => $response->getStatusCode(),
122
            'content' => json_decode($response->getBody()->getContents(), true)
123
        ];
124
    }
125
126
    /**
127
     * Generate the payment's receipt
128
     *
129
     * @param $referenceId
130
     *
131
     * @return Receipt
132
     */
133
    protected function createReceipt($referenceId): Receipt
134
    {
135
        $receipt = new Receipt('walleta', $referenceId);
136
137
        return $receipt;
138
    }
139
140
    /**
141
     * call create token request
142
     *
143
     * @return array
144
     */
145
    public function token(): array
146
    {
147
        return $this->callApi('POST', $this->settings->apiPurchaseUrl, [
148
            'merchant_code' => $this->settings->merchantId,
149
            'invoice_reference' => $this->invoice->getUuid(),
150
            'invoice_date' => date('Y-m-d H:i:s'),
151
            'invoice_amount' => $this->invoice->getAmount(),
152
            'payer_first_name' => $this->invoice->getDetails()['first_name'],
153
            'payer_last_name' => $this->invoice->getDetails()['last_name'],
154
            'payer_national_code' => $this->invoice->getDetails()['national_code'],
155
            'payer_mobile' => $this->invoice->getDetails()['mobile'],
156
            'callback_url' => $this->settings->callbackUrl,
157
            'items' => $this->getItems(),
158
        ]);
159
    }
160
161
    /**
162
     * call verift transaction request
163
     *
164
     * @return array
165
     */
166
    public function verifyTransaction(): array
167
    {
168
        return $this->callApi('POST', $this->settings->apiVerificationUrl, [
169
            'merchant_code' => $this->settings->merchantId,
170
            'token' => $this->invoice->getTransactionId(),
171
            'invoice_reference' => $this->invoice->getUuid(),
172
            'invoice_amount' => $this->invoice->getAmount(),
173
        ]);
174
    }
175
176
    /**
177
     * get Items for
178
     *
179
     *
180
     */
181
    private function getItems()
182
    {
183
        /**
184
         * example data
185
         *
186
         *   $items = [
187
         *       [
188
         *           "reference" => "string",
189
         *           "name" => "string",
190
         *           "quantity" => 0,
191
         *           "unit_price" => 0,
192
         *           "unit_discount" => 0,
193
         *           "unit_tax_amount" => 0,
194
         *           "total_amount" => 0
195
         *       ]
196
         *   ];
197
         */
198
        return $this->invoice->getDetails()['items'];
199
    }
200
201
202
    /**
203
     * Trigger an exception
204
     *
205
     * @param $status
206
     *
207
     * @throws PurchaseFailedException
208
     */
209
    protected function purchaseFailed($status)
210
    {
211
        $translations = [
212
            "server_error" => "یک خطای داخلی رخ داده است.",
213
            "ip_address_error" => "آدرس IP پذیرنده صحیح نیست.",
214
            "validation_error" => "اطلاعات ارسال شده صحیح نیست.",
215
            "merchant_error" => "کد پذیرنده معتبر نیست.",
216
            "payment_token_error" => "شناسه پرداخت معتبر نیست.",
217
            "invoice_amount_error" => "مبلغ تراکنش با مبلغ پرداخت شده مطابقت ندارد.",
218
        ];
219
220
        if (array_key_exists($status, $translations)) {
221
            throw new PurchaseFailedException($translations[$status]);
222
        } else {
223
            throw new PurchaseFailedException('خطای ناشناخته ای رخ داده است.');
224
        }
225
    }
226
}
227