Passed
Push — master ( 17e09c...21d5d9 )
by mahdi
08:10
created

Omidpay   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 231
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 107
c 1
b 0
f 0
dl 0
loc 231
rs 10
wmc 11

7 Methods

Rating   Name   Duplication   Size   Complexity  
A createReceipt() 0 3 1
A __construct() 0 5 1
A purchase() 0 46 3
A translateStatus() 0 54 2
A verify() 0 33 2
A pay() 0 6 1
A isSucceed() 0 3 1
1
<?php
2
3
namespace Shetabit\Multipay\Drivers\Omidpay;
4
5
use GuzzleHttp\Client;
6
use Shetabit\Multipay\Abstracts\Driver;
7
use Shetabit\Multipay\Contracts\ReceiptInterface;
8
use Shetabit\Multipay\Exceptions\InvalidPaymentException;
9
use Shetabit\Multipay\Exceptions\PurchaseFailedException;
10
use Shetabit\Multipay\Invoice;
11
use Shetabit\Multipay\Receipt;
12
use Shetabit\Multipay\RedirectionForm;
13
use Shetabit\Multipay\Request;
14
15
class Omidpay extends Driver
16
{
17
    /**
18
     * Sadad Client.
19
     *
20
     * @var object
21
     */
22
    protected $client;
23
24
    /**
25
     * Invoice
26
     *
27
     * @var Invoice
28
     */
29
    protected $invoice;
30
31
    /**
32
     * Driver settings
33
     *
34
     * @var object
35
     */
36
    protected $settings;
37
38
    /**
39
     * Sadad constructor.
40
     * Construct the class with the relevant settings.
41
     *
42
     * @param Invoice $invoice
43
     * @param $settings
44
     */
45
    public function __construct(Invoice $invoice, $settings)
46
    {
47
        $this->invoice($invoice);
48
        $this->settings = (object) $settings;
49
        $this->client = new Client();
50
    }
51
52
    /**
53
     * Purchase Invoice.
54
     *
55
     * @return string
56
     *
57
     * @throws PurchaseFailedException
58
     * @throws \GuzzleHttp\Exception\GuzzleException
59
     */
60
    public function purchase(): string
61
    {
62
        $data = array(
63
            'WSContext' => [
64
                'UserId' => $this->settings->username,
65
                'Password' => $this->settings->password,
66
            ],
67
            'TransType' => 'EN_GOODS',
68
            'ReserveNum' => $this->invoice->getUuid(),
69
            'MerchantId' => $this->settings->merchantId,
70
            'Amount' => $this->invoice->getAmount() * 10,
71
            'RedirectUrl' => $this->settings->callbackUrl,
72
        );
73
74
        $response = $this->client->request(
75
            "POST",
76
            $this->settings->apiGenerateTokenUrl,
77
            [
78
                'json' => $data,
79
                "headers" => [
80
                    'Content-Type' => 'application/json',
81
                    'Accept' => 'application/json',
82
                    'User-Agent' => '',
83
                ],
84
            ]
85
        );
86
87
        $responseStatus = $response->getStatusCode();
88
89
        if ($responseStatus != 200) {
90
            throw new PurchaseFailedException($this->translateStatus("unknown_error"));
91
        }
92
93
        $jsonBody = $response->getBody()->getContents();
94
        $responseData = json_decode($jsonBody, true);
95
96
        $result = $responseData['Result'];
97
        if (!$this->isSucceed($result)) {
98
            throw new PurchaseFailedException($this->translateStatus($result));
99
        }
100
101
        // set transaction id
102
        $this->invoice->transactionId($responseData['Token']);
103
104
        // return the transaction’s id
105
        return $this->invoice->getTransactionId();
106
    }
107
108
    /**
109
     * Pay the Invoice
110
     *
111
     * @return RedirectionForm
112
     */
113
    public function pay(): RedirectionForm
114
    {
115
        $token = $this->invoice->getTransactionId();
116
        $payUrl = $this->settings->apiPaymentUrl;
117
118
        return $this->redirectWithForm($payUrl, ['token' => $token, 'language' => 'fa']);
119
    }
120
121
    /**
122
     * Verify payment
123
     *
124
     * @return ReceiptInterface
125
     *
126
     * @throws InvalidPaymentException
127
     * @throws \GuzzleHttp\Exception\GuzzleException
128
     */
129
    public function verify(): ReceiptInterface
130
    {
131
        $token = $this->invoice->getTransactionId() ?? Request::input('token');
132
        $refNum = Request::input('RefNum');
133
134
        $response = $this->client->request(
135
            "POST",
136
            $this->settings->apiVerificationUrl,
137
            [
138
                "json" => [
139
                    'WSContext' => [
140
                        'UserId' => $this->settings->username,
141
                        'Password' => $this->settings->password,
142
                    ],
143
                    'Token' => $token,
144
                    'RefNum' => $refNum
145
                ],
146
                "headers" => [
147
                    'Content-Type' => 'application/json',
148
                    'Accept' => 'application/json',
149
                    'User-Agent' => '',
150
                ],
151
            ]
152
        );
153
154
        $body = json_decode($response->getBody()->getContents());
155
156
        $result = $body->Result;
157
        if (!$this->isSucceed($result)) {
158
            throw new InvalidPaymentException($this->translateStatus($result));
159
        }
160
161
        return $this->createReceipt($body->RefNum);
162
    }
163
164
    /**
165
     * Generate the payment's receipt
166
     *
167
     * @param $referenceId
168
     *
169
     * @return Receipt
170
     */
171
    protected function createReceipt($referenceId): Receipt
172
    {
173
        return new Receipt('omidpay', $referenceId);
174
    }
175
176
    /**
177
     * @param string $status
178
     * @return bool
179
     */
180
    private function isSucceed(string $status): bool
181
    {
182
        return $status == "erSucceed";
183
    }
184
185
    /**
186
     * Convert status to a readable message.
187
     *
188
     * @param $status
189
     *
190
     * @return mixed|string
191
     */
192
    private function translateStatus($status): string
193
    {
194
        $translations = [
195
            'erSucceed' => 'سرویس با موفقیت اجراء شد.',
196
            'erAAS_UseridOrPassIsRequired' => 'کد کاربری و رمز الزامی هست.',
197
            'erAAS_InvalidUseridOrPass' => 'کد کاربری یا رمز صحیح نمی باشد.',
198
            'erAAS_InvalidUserType' => 'نوع کاربر صحیح نمی‌باشد.',
199
            'erAAS_UserExpired' => 'کاربر منقضی شده است.',
200
            'erAAS_UserNotActive' => 'کاربر غیر فعال هست.',
201
            'erAAS_UserTemporaryInActive' => 'کاربر موقتا غیر فعال شده است.',
202
            'erAAS_UserSessionGenerateError' => 'خطا در تولید شناسه لاگین',
203
            'erAAS_UserPassMinLengthError' => 'حداقل طول رمز رعایت نشده است.',
204
            'erAAS_UserPassMaxLengthError' => 'حداکثر طول رمز رعایت نشده است.',
205
            'erAAS_InvalidUserCertificate' => 'برای کاربر فایل سرتیفکیت تعریف نشده است.',
206
            'erAAS_InvalidPasswordChars' => 'کاراکترهای غیر مجاز در رمز',
207
            'erAAS_InvalidSession' => 'شناسه لاگین معتبر نمی‌باشد ',
208
            'erAAS_InvalidChannelId' => 'کانال معتبر نمی‌باشد.',
209
            'erAAS_InvalidParam' => 'پارامترها معتبر نمی‌باشد.',
210
            'erAAS_NotAllowedToService' => 'کاربر مجوز سرویس را ندارد.',
211
            'erAAS_SessionIsExpired' => 'شناسه الگین معتبر نمی‌باشد.',
212
            'erAAS_InvalidData' => 'داده‌ها معتبر نمی‌باشد.',
213
            'erAAS_InvalidSignature' => 'امضاء دیتا درست نمی‌باشد.',
214
            'erAAS_InvalidToken' => 'توکن معتبر نمی‌باشد.',
215
            'erAAS_InvalidSourceIp' => 'آدرس آی پی معتبر نمی‌باشد.',
216
217
            'erMts_ParamIsNull' => 'پارمترهای ورودی خالی می‌باشد.',
218
            'erMts_UnknownError' => 'خطای ناشناخته',
219
            'erMts_InvalidAmount' => 'مبلغ معتبر نمی‌باشد.',
220
            'erMts_InvalidBillId' => 'شناسه قبض معتبر نمی‌باشد.',
221
            'erMts_InvalidPayId' => 'شناسه پرداخت معتبر نمی‌باشد.',
222
            'erMts_InvalidEmailAddLen' => 'طول ایمیل معتبر نمی‌باشد.',
223
            'erMts_InvalidGoodsReferenceIdLen' => 'طول شناسه خرید معتبر نمی‌باشد.',
224
            'erMts_InvalidMerchantGoodsReferenceIdLen' => 'طول شناسه خرید پذیرنده معتبر نمی‌باشد.',
225
            'erMts_InvalidMobileNo' => 'فرمت شماره موبایل معتبر نمی‌باشد.',
226
            'erMts_InvalidPorductId' => 'طول یا فرمت کد محصول معتبر نمی‌باشد.',
227
            'erMts_InvalidRedirectUrl' => 'طول یا فرمت آدرس صفحه رجوع معتبر نمی‌باشد.',
228
            'erMts_InvalidReferenceNum' => 'طول یا فرمت شماره رفرنس معتبر نمی‌باشد.',
229
            'erMts_InvalidRequestParam' => 'پارامترهای درخواست معتبر نمی‌باشد.',
230
            'erMts_InvalidReserveNum' => 'طول یا فرمت شماره رزرو معتبر نمی‌باشد.',
231
            'erMts_InvalidSessionId' => 'شناسه الگین معتبر نمی‌باشد.',
232
            'erMts_InvalidSignature' => 'طول یا فرمت امضاء دیتا معتبر نمی‌باشد.',
233
            'erMts_InvalidTerminal' => 'کد ترمینال معتبر نمی‌باشد.',
234
            'erMts_InvalidToken' => 'توکن معتبر نمی‌باشد.',
235
            'erMts_InvalidTransType' => 'نوع تراکنش معتبر نمی‌باشد.',
236
            'erMts_InvalidUniqueId' => 'کد یکتا معتبر نمی‌باشد.',
237
            'erMts_InvalidUseridOrPass' => 'رمز یا کد کاربری معتبر نمی باشد.',
238
            'erMts_RepeatedBillId' => 'پرداخت قبض تکراری می باشد.',
239
            'erMts_AASError' => 'کد کاربری و رمز الزامی هست.',
240
            'erMts_SCMError' => 'خطای سرور مدیریت کانال',
241
        ];
242
243
        $unknownError = 'خطای ناشناخته رخ داده است. در صورت کسر مبلغ از حساب حداکثر پس از 72 ساعت به حسابتان برمیگردد.';
244
245
        return array_key_exists($status, $translations) ? $translations[$status] : $unknownError;
246
    }
247
}
248