Passed
Push — master ( 2c9822...4f6225 )
by mahdi
03:28 queued 42s
created

Sepehr::createReceipt()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
1
<?php
2
3
namespace Shetabit\Multipay\Drivers\Sepehr;
4
5
use Illuminate\Support\Facades\Log;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\Facades\Log was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Shetabit\Multipay\Abstracts\Driver;
7
use Shetabit\Multipay\Exceptions\InvalidPaymentException;
8
use Shetabit\Multipay\Exceptions\PurchaseFailedException;
9
use Shetabit\Multipay\Contracts\ReceiptInterface;
10
use Shetabit\Multipay\Invoice;
11
use Shetabit\Multipay\Receipt;
12
use Shetabit\Multipay\RedirectionForm;
13
use Shetabit\Multipay\Request;
14
15
class Sepehr extends Driver
16
{
17
18
    /**
19
     * Invoice
20
     *
21
     * @var Invoice
22
     */
23
    protected $invoice;
24
25
    /**
26
     * Driver settings
27
     *
28
     * @var object
29
     */
30
    protected $settings;
31
32
    /**
33
     * Sepehr constructor.
34
     * Construct the class with the relevant settings.
35
     *
36
     * @param Invoice $invoice
37
     * @param $settings
38
     */
39
    public function __construct(Invoice $invoice, $settings)
40
    {
41
        $this->invoice($invoice);
42
        $this->settings = (object)$settings;
43
    }
44
45
    /**
46
     * Purchase Invoice.
47
     *
48
     * @return string
49
     *
50
     * @throws PurchaseFailedException
51
     */
52
    public function purchase()
53
    {
54
        $amount = $this->invoice->getAmount() * 10; // convert to rial
55
56
        $data_query = 'Amount=' . $this->test_input($amount) . '&callbackURL=' . $this->test_input($this->settings->callbackUrl) . '&InvoiceID=' . $this->test_input($this->invoice->getUuid()) . '&TerminalID=' . $this->test_input($this->settings->terminalId) . '&Payload=' . $this->test_input("");
57
        $address_service_token = $this->settings->apiGetToken;
58
59
        $token_array = $this->makeHttpChargeRequest('POST', $data_query, $address_service_token);
60
61
        if ($token_array === false) {
62
            throw new PurchaseFailedException('درگاه مورد نظر پاسخگو نمی‌باشد، لطفا لحظاتی بعد امتحان کنید.');
63
        }
64
65
        $decode_token_array = json_decode($token_array);
0 ignored issues
show
Bug introduced by
It seems like $token_array can also be of type true; however, parameter $json of json_decode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

65
        $decode_token_array = json_decode(/** @scrutinizer ignore-type */ $token_array);
Loading history...
66
67
        $status = $decode_token_array->Status;
68
        $access_token = $decode_token_array->Accesstoken;
69
70
        if (empty($access_token) && $status != 0) {
71
            $this->purchaseFailed($status);
72
        }
73
74
        $this->invoice->transactionId($access_token);
75
        // return the transaction's id
76
        return $this->invoice->getTransactionId();
77
    }
78
79
    /**
80
     * Pay the Invoice
81
     *
82
     * @return RedirectionForm
83
     */
84
    public function pay(): RedirectionForm
85
    {
86
        return $this->redirectWithForm($this->settings->apiPaymentUrl, [
87
            'token' => $this->invoice->getTransactionId(),
88
            'terminalID' => $this->settings->terminalId
89
        ], 'POST');
90
    }
91
92
    /**
93
     * Verify payment
94
     *
95
     * @return ReceiptInterface
96
     *
97
     * @throws InvalidPaymentException
98
     *
99
     */
100
    public function verify(): ReceiptInterface
101
    {
102
        $resp_code = Request::input('respcode');
103
        $amount = $this->invoice->getAmount() * 10; // convert to rial
104
105
        if ($resp_code != 0) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $resp_code of type mixed|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
106
            $this->notVerified($resp_code);
107
        }
108
109
        $data_query = 'digitalreceipt=' . Request::input('‫‪digitalreceipt‬‬') . '&Tid=' . $this->settings->terminalId;
110
111
        $advice_array = makeHttpChargeRequest('POST', $data_query, $this->settings->apiVerificationUrl);
0 ignored issues
show
Bug introduced by
The function makeHttpChargeRequest was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

111
        $advice_array = /** @scrutinizer ignore-call */ makeHttpChargeRequest('POST', $data_query, $this->settings->apiVerificationUrl);
Loading history...
112
        $decode_advice_array = json_decode($advice_array);
113
114
        //var_dump($decode_TokenArray);
115
116
        $status = $decode_advice_array->Status;
117
        $return_id = $decode_advice_array->ReturnId;
118
119
        if ($resp_code == 0 && $status == "Ok") {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $resp_code of type mixed|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
120
            if (floatval($return_id) != floatval($amount)) {
121
                throw new InvalidPaymentException('مبلغ واریز با قیمت محصول برابر نیست');
122
            }
123
            return $this->createReceipt(Request::input('rrn'));
124
        } else {
125
            $message = 'تراکنش نا موفق بود در صورت کسر مبلغ از حساب شما حداکثر پس از 72 ساعت مبلغ به حسابتان برمیگردد.';
126
            throw new InvalidPaymentException($message);
127
        }
128
    }
129
130
    /**
131
     * Generate the payment's receipt
132
     *
133
     * @param $referenceId
134
     *
135
     * @return Receipt
136
     */
137
    protected function createReceipt($referenceId)
138
    {
139
        $receipt = new Receipt('sepehr', $referenceId);
140
141
        return $receipt;
142
    }
143
144
    /**
145
     * Trigger an exception
146
     *
147
     * @param $status
148
     *
149
     * @throws PurchaseFailedException
150
     */
151
    protected function purchaseFailed($status)
152
    {
153
        $translations = array(
154
            -1 => 'تراکنش پیدا نشد.',
155
            -2 => 'عدم تطابق ip و یا بسته بودن port 8081',
156
            -3 => '‫ها‬ ‫‪Exception‬‬ ‫خطای‬ ‫–‬ ‫عمومی‬ ‫خطای‬ ‫‪Total‬‬ ‫‪Error‬‬',
157
            -4 => '‫ندارد‬ ‫وجود‬ ‫تراکنش‬ ‫این‬ ‫برای‬ ‫درخواست‬ ‫انجام‬ ‫امکان‬',
158
            -5 => 'آدرس ip نامعتبر می‌باشد.',
159
            -6 => 'عدم فعال بودن سرویس برگشت تراکنش برای پذیرنده',
160
        );
161
162
        if (array_key_exists($status, $translations)) {
163
            throw new PurchaseFailedException($translations[$status]);
164
        } else {
165
            throw new PurchaseFailedException('خطای ناشناخته ای رخ داده است.');
166
        }
167
    }
168
169
    /**
170
     * Trigger an exception
171
     *
172
     * @param $status
173
     *
174
     * @throws InvalidPaymentException
175
     */
176
    private function notVerified($status)
177
    {
178
        $translations = array(
179
            -1 => ' تراکنش توسط خریدار کنسل شده است.',
180
            -2 => 'زمان انجام تراکنش برای کاربر به پایان رسیده است.',
181
        );
182
183
        if (array_key_exists($status, $translations)) {
184
            throw new InvalidPaymentException($translations[$status]);
185
        } else {
186
            throw new InvalidPaymentException('خطای ناشناخته ای رخ داده است.');
187
        }
188
    }
189
190
    private function test_input($data)
191
    {
192
        $data = trim($data);
193
        $data = stripslashes($data);
194
        $data = htmlspecialchars($data);
195
        return $data;
196
    }
197
198
    private function makeHttpChargeRequest($_Method, $_Data, $_Address)
199
    {
200
        $curl = curl_init();
201
        curl_setopt($curl, CURLOPT_URL, $_Address);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_setopt() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

201
        curl_setopt(/** @scrutinizer ignore-type */ $curl, CURLOPT_URL, $_Address);
Loading history...
202
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $_Method);
203
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
204
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
205
        curl_setopt($curl, CURLOPT_POSTFIELDS, $_Data);
206
        $result = curl_exec($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_exec() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

206
        $result = curl_exec(/** @scrutinizer ignore-type */ $curl);
Loading history...
207
        curl_close($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_close() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

207
        curl_close(/** @scrutinizer ignore-type */ $curl);
Loading history...
208
        return $result;
209
    }
210
}
211