Passed
Push — master ( bf8341...afcebc )
by mahdi
02:32
created

Zibal::purchase()   C

Complexity

Conditions 10
Paths 216

Size

Total Lines 69
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 10
eloc 42
c 3
b 0
f 0
nc 216
nop 0
dl 0
loc 69
rs 6.6333

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Shetabit\Multipay\Drivers\Zibal;
4
5
use GuzzleHttp\Client;
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 Zibal extends Driver
16
{
17
    /**
18
     * Zibal 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
     * Zibal 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 \GuzzleHttp\Exception\GuzzleException
58
     */
59
    public function purchase()
60
    {
61
        $details = $this->invoice->getDetails();
62
63
        // convert to toman
64
        $toman = $this->invoice->getAmount() * 10;
65
66
        $orderId = crc32($this->invoice->getUuid()).time();
67
        if (!empty($details['orderId'])) {
68
            $orderId = $details['orderId'];
69
        } elseif (!empty($details['order_id'])) {
70
            $orderId = $details['order_id'];
71
        }
72
73
        $mobile = null;
74
        if (!empty($details['mobile'])) {
75
            $mobile = $details['mobile'];
76
        } elseif (!empty($details['phone'])) {
77
            $mobile = $details['phone'];
78
        }
79
80
        $description = null;
81
        if (!empty($details['description'])) {
82
            $description = $details['description'];
83
        } else {
84
            $description = $this->settings->description;
85
        }
86
87
        $data = array(
88
            "merchant"=> $this->settings->merchantId, //required
89
            "callbackUrl"=> $this->settings->callbackUrl, //required
90
            "amount"=> $toman, //required
91
            "orderId"=> $orderId, //optional
92
            'mobile' => $mobile, //optional for mpg
93
            "description" => $description, //optional
94
        );
95
96
        //checking if optional allowedCards parameter exists
97
        $allowedCards = null;
98
        if (!empty($details['allowedCards'])) {
99
            $allowedCards = $details['allowedCards'];
100
        } else if(!empty($this->settings->allowedCards)) {
101
            $allowedCards = $this->settings->allowedCards;
102
        }
103
104
        if ($allowedCards != null) {
105
            $allowedCards = array(
106
                'allowedCards' => $allowedCards,
107
            );
108
            $data = array_merge($data, $allowedCards);
109
        }
110
111
        $response = $this->client->request(
112
            'POST',
113
            $this->settings->apiPurchaseUrl,
114
            ["json" => $data, "http_errors" => false]
115
        );
116
117
        $body = json_decode($response->getBody()->getContents(), false);
118
119
        if ($body->result != 100) {
120
            // some error has happened
121
            throw new PurchaseFailedException($body->message);
122
        }
123
124
        $this->invoice->transactionId($body->trackId);
125
126
        // return the transaction's id
127
        return $this->invoice->getTransactionId();
128
    }
129
130
    /**
131
     * Pay the Invoice
132
     *
133
     * @return RedirectionForm
134
     */
135
    public function pay() : RedirectionForm
136
    {
137
        $payUrl = $this->settings->apiPaymentUrl.$this->invoice->getTransactionId();
138
139
        if (strtolower($this->settings->mode) == 'direct') {
140
            $payUrl .= '/direct';
141
        }
142
143
        return $this->redirectWithForm($payUrl);
144
    }
145
146
    /**
147
     * Verify payment
148
     *
149
     * @return mixed|void
150
     *
151
     * @throws InvalidPaymentException
152
     * @throws \GuzzleHttp\Exception\GuzzleException
153
     */
154
    public function verify() : ReceiptInterface
155
    {
156
        $successFlag = Request::input('success');
157
        $orderId = Request::input('orderId');
158
        $transactionId = $this->invoice->getTransactionId() ?? Request::input('trackId');
159
160
        if ($successFlag != 1) {
161
            $this->notVerified('پرداخت با شکست مواجه شد');
162
        }
163
164
        //start verfication
165
        $data = array(
166
            "merchant" => $this->settings->merchantId, //required
167
            "trackId" => $transactionId, //required
168
        );
169
170
        $response = $this->client->request(
171
            'POST',
172
            $this->settings->apiVerificationUrl,
173
            ["json" => $data, "http_errors" => false]
174
        );
175
176
        $body = json_decode($response->getBody()->getContents(), false);
177
178
        if ($body->result != 100) {
179
            $this->notVerified($body->message);
180
        }
181
182
        /*
183
            for more info:
184
            var_dump($body);
185
        */
186
187
        return $this->createReceipt($orderId);
188
    }
189
190
    /**
191
     * Generate the payment's receipt
192
     *
193
     * @param $referenceId
194
     *
195
     * @return Receipt
196
     */
197
    protected function createReceipt($referenceId)
198
    {
199
        $receipt = new Receipt('Zibal', $referenceId);
200
201
        return $receipt;
202
    }
203
204
    /**
205
     * Trigger an exception
206
     *
207
     * @param $message
208
     * @throws InvalidPaymentException
209
     */
210
    private function notVerified($message)
211
    {
212
        if (empty($message)) {
213
            throw new InvalidPaymentException('خطای ناشناخته ای رخ داده است.');
214
        } else {
215
            throw new InvalidPaymentException($message);
216
        }
217
    }
218
}
219