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

Parsian::purchase()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 24
rs 9.5555
cc 5
nc 3
nop 0
1
<?php
2
3
namespace Shetabit\Payment\Drivers\Parsian;
4
5
use Shetabit\Payment\Abstracts\Driver;
6
use Shetabit\Payment\Exceptions\{InvalidPaymentException, PurchaseFailedException};
7
use Shetabit\Payment\{Contracts\ReceiptInterface, Invoice, Receipt};
8
9
class Parsian extends Driver
10
{
11
    /**
12
     * Invoice
13
     *
14
     * @var Invoice
15
     */
16
    protected $invoice;
17
18
    /**
19
     * Driver settings
20
     *
21
     * @var object
22
     */
23
    protected $settings;
24
25
    /**
26
     * Parsian constructor.
27
     * Construct the class with the relevant settings.
28
     *
29
     * @param Invoice $invoice
30
     * @param $settings
31
     */
32
    public function __construct(Invoice $invoice, $settings)
33
    {
34
        $this->invoice($invoice);
35
        $this->settings = (object)$settings;
36
    }
37
38
    /**
39
     * Purchase Invoice.
40
     *
41
     * @return string
42
     *
43
     * @throws PurchaseFailedException
44
     * @throws \SoapFault
45
     */
46
    public function purchase()
47
    {
48
        $soap = new \SoapClient($this->settings->apiPurchaseUrl);
49
        $response = $soap->SalePaymentRequest(
50
            $this->preparePurchaseData(),
51
            $this->settings->apiNamespaceUrl
52
        );
53
54
        // no response from bank
55
        if (empty($response['SalePaymentRequestResult'])) {
56
            throw new PurchaseFailedException('bank gateway not response');
57
        }
58
59
        $result = $response['SalePaymentRequestResult'];
60
61
        if (isset($result['Status']) && $result['Status'] == 0 && !empty($result['Token'])) {
62
            $this->invoice->transactionId($result['Token']);
63
        } else {
64
            // an error has happened
65
            throw new PurchaseFailedException($result['Status']);
66
        }
67
68
        // return the transaction's id
69
        return $this->invoice->getTransactionId();
70
    }
71
72
    /**
73
     * Pay the Invoice
74
     *
75
     * @return \Illuminate\Http\RedirectResponse|mixed
76
     */
77
    public function pay()
78
    {
79
        $payUrl = $this->settings->apiPaymentUrl;
80
81
        return $this->redirectWithForm(
82
            $payUrl,
83
            [
84
                'RefId' => $this->invoice->getTransactionId(),
85
            ],
86
            'POST'
87
        );
88
    }
89
90
    /**
91
     * Verify payment
92
     *
93
     * @return ReceiptInterface
94
     *
95
     * @throws InvalidPaymentException
96
     * @throws \SoapFault
97
     */
98
    public function verify() : ReceiptInterface
99
    {
100
        $status = request()->get('status');
101
        $token = request()->get('Token');
102
        $rrn = request()->get('RRN');
0 ignored issues
show
Unused Code introduced by
The assignment to $rrn is dead and can be removed.
Loading history...
103
104
        if ($status != 0 || empty($token)) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $status 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...
105
            throw new InvalidPaymentException('تراکنش توسط کاربر کنسل شده است.');
106
        }
107
108
        $data = $this->prepareVerificationData();
109
        $soap = new \SoapClient($this->settings->apiVerificationUrl);
110
111
        $response = $soap->ConfirmPayment(['requestData' => $data]);
112
113
        if (empty($response['ConfirmPaymentResult'])) {
114
            throw new InvalidPaymentException('از سمت بانک پاسخی دریافت نشد.');
115
        }
116
117
        $result = $response['ConfirmPaymentResult'];
118
119
        if (!isset($result['Status']) || $result['Status'] != 0 || !isset($result['RRN']) || $result['RRN'] <= 0) {
120
            $message = 'خطا از سمت بانک با کد ' . $result['Status'] . ' رخ داده است.';
121
            throw new InvalidPaymentException($message);
122
        }
123
124
        $bankReference = (isset($result['RRN']) && $result['RRN'] > 0) ? $result['RRN'] : "";
125
        // $cardNumberMasked = !empty($result['CardNumberMasked']) ? $result['CardNumberMasked'] : "";
126
127
        return $this->createReceipt($bankReference);
128
    }
129
130
    /**
131
     * Generate the payment's receipt
132
     *
133
     * @param $referenceId
134
     *
135
     * @return Receipt
136
     */
137
    public function createReceipt($referenceId)
138
    {
139
        $receipt = new Receipt('parsian', $referenceId);
140
141
        return $receipt;
142
    }
143
144
    /**
145
     * Prepare data for payment verification
146
     *
147
     * @return array
148
     */
149
    public function prepareVerificationData()
150
    {
151
        $transactionId = $this->invoice->getTransactionId() ?? request()->get('Token');
152
153
        return array(
154
            'LoginAccount' 		=> $this->settings->loginAccount,
155
            'Token' 		=> $transactionId,
156
        );
157
    }
158
159
    /**
160
     * Prepare data for purchasing invoice
161
     *
162
     * @return array
163
     */
164
    protected function preparePurchaseData()
165
    {
166
        if (!empty($this->invoice->getDetails()['description'])) {
167
            $description = $this->invoice->getDetails()['description'];
168
        } else {
169
            $description = $this->settings->description;
170
        }
171
172
        return array(
173
            'LoginAccount' 		=> $this->settings->loginAccount,
174
            'Amount' 			=> $this->invoice->getAmount() * 10, // convert to rial
175
            'OrderId' 			=> crc32($this->invoice->getUuid()),
176
            'CallBackUrl' 		=> $this->settings->callbackUrl,
177
            'AdditionalData' 	=> $description,
178
        );
179
    }
180
}
181