Passed
Pull Request — master (#85)
by
unknown
04:04 queued 01:04
created

JibitBase::getOrderById()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 1
eloc 1
c 2
b 0
f 2
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
namespace Shetabit\Multipay\Drivers\Jibit;
3
4
class JibitBase
5
{
6
    public $accessToken;
7
    private $apiKey;
8
    private $secretKey;
9
    private $refreshToken;
10
    private $cache;
11
    public $base_url;
12
13
    public function __construct($apiKey, $secretKey, $base_url)
14
    {
15
        $this->base_url = $base_url;
16
        $this->apiKey = $apiKey;
17
        $this->secretKey = $secretKey;
18
        $this->cache = new JibitCache('jibit');
19
    }
20
21
    /**
22
     * @param int $amount
23
     * @param string $referenceNumber
24
     * @param string $userIdentifier
25
     * @param string $callbackUrl
26
     * @param string $currency
27
     * @param null $description
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $description is correct as it would always require null to be passed?
Loading history...
28
     * @param $additionalData
29
     * @return bool|mixed|string
30
     * @throws Exception
31
     */
32
    public function paymentRequest($amount, $referenceNumber, $userIdentifier, $callbackUrl, $currency = 'RIALS', $description = null, $additionalData = null)
33
    {
34
        $this->generateToken();
35
        $data = [
36
            'merchantCode' => $this->apiKey,
37
            'password' => $this->secretKey,
38
            'amount' => $amount,
39
            'referenceNumber' => $referenceNumber,
40
            'userIdentifier' => $userIdentifier,
41
            'callbackUrl' => $callbackUrl,
42
            'currency' => $currency,
43
            'description' => $description,
44
            'additionalData' => $additionalData,
45
        ];
46
        return $this->callCurl('/orders', $data, true);
47
    }
48
49
    /**
50
     * @param $id
51
     * @return bool|mixed|string
52
     * @throws Exception
53
     */
54
    public function getOrderById($id)
55
    {
56
        return  $this->callCurl('/orders/' .$id, [], true, 0, 'GET');
57
    }
58
59
    /**
60
     * @param bool $isForce
61
     * @return string
62
     * @throws Exception
63
     */
64
    private function generateToken($isForce = false)
65
    {
66
        $this->cache->eraseExpired();
67
68
        if ($isForce === false && $this->cache->isCached('accessToken')) {
69
            return $this->setAccessToken($this->cache->retrieve('accessToken'));
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->setAccessToken($t...etrieve('accessToken')) targeting Shetabit\Multipay\Driver...tBase::setAccessToken() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
70
        } elseif ($this->cache->isCached('refreshToken')) {
71
            $refreshToken = $this->refreshTokens();
72
            if ($refreshToken !== 'ok') {
73
                return $this->generateNewToken();
74
            }
75
        } else {
76
            return $this->generateNewToken();
77
        }
78
79
        throw new \Shetabit\Multipay\Exceptions\PurchaseFailedException('unExcepted Err in generateToken.');
80
    }
81
82
    private function refreshTokens()
83
    {
84
        echo 'refreshing';
85
        $data = [
86
            'accessToken' => str_replace('Bearer ', '', $this->cache->retrieve('accessToken')),
87
            'refreshToken' => $this->cache->retrieve('refreshToken'),
88
        ];
89
        $result = $this->callCurl('/tokens/refresh', $data, false);
90
        if (empty($result['accessToken'])) {
91
            throw new \Shetabit\Multipay\Exceptions\PurchaseFailedException('Err in refresh token.');
92
        }
93
        if (!empty($result['accessToken'])) {
94
            $this->cache->store('accessToken', 'Bearer ' . $result['accessToken'], 24 * 60 * 60 - 60);
95
            $this->cache->store('refreshToken', $result['refreshToken'], 48 * 60 * 60 - 60);
96
            $this->setAccessToken('Bearer ' . $result['accessToken']);
97
            $this->setRefreshToken($result['refreshToken']);
98
            return 'ok';
99
        }
100
        throw new \Shetabit\Multipay\Exceptions\PurchaseFailedException('unExcepted Err in refreshToken.');
101
    }
102
103
    /**
104
     * @param $url
105
     * @param $arrayData
106
     * @param bool $haveAuth
107
     * @param int $try
108
     * @param string $method
109
     * @return bool|mixed|string
110
     * @throws Exception
111
     */
112
    private function callCurl($url, $arrayData, $haveAuth = false, $try = 0, $method = 'POST')
113
    {
114
        $data = $arrayData;
115
        $jsonData = json_encode($data);
116
        $accessToken = '';
117
        if ($haveAuth) {
118
            $accessToken = $this->getAccessToken();
119
        }
120
        $ch = curl_init($this->base_url . $url);
121
        curl_setopt($ch, CURLOPT_USERAGENT, 'Jibit.class Rest Api');
122
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
123
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
124
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
125
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
126
            'Content-Type: application/json',
127
            'Authorization: ' . $accessToken,
128
            'Content-Length: ' . strlen($jsonData)
129
        ));
130
        $result = curl_exec($ch);
131
        $err = curl_error($ch);
132
        $result = json_decode($result, true);
0 ignored issues
show
Bug introduced by
It seems like $result 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

132
        $result = json_decode(/** @scrutinizer ignore-type */ $result, true);
Loading history...
133
        curl_close($ch);
134
135
        if ($err) {
136
            throw new \Shetabit\Multipay\Exceptions\PurchaseFailedException('cURL Error #:' . $err);
137
        }
138
        if (empty($result['errors'])) {
139
            return $result;
140
        }
141
        if ($haveAuth === true && $result['errors'][0]['code'] === 'security.auth_required') {
142
            $this->generateToken(true);
143
            if ($try === 0) {
144
                return $this->callCurl($url, $arrayData, $haveAuth, 1, $method);
145
            }
146
            throw new \Shetabit\Multipay\Exceptions\PurchaseFailedException('Err in auth.');
147
        }
148
149
        return $result;
150
    }
151
152
    /**
153
     * @return mixed
154
     */
155
    public function getAccessToken()
156
    {
157
        return $this->accessToken;
158
    }
159
160
    /**
161
     * @param mixed $accessToken
162
     */
163
    public function setAccessToken($accessToken)
164
    {
165
        $this->accessToken = $accessToken;
166
    }
167
168
    /**
169
     * @param mixed $refreshToken
170
     */
171
    public function setRefreshToken($refreshToken)
172
    {
173
        $this->refreshToken = $refreshToken;
174
    }
175
176
    private function generateNewToken()
177
    {
178
        $data = [
179
            'merchantCode' => $this->apiKey,
180
            'password' => $this->secretKey,
181
        ];
182
        $result = $this->callCurl('/tokens/generate', $data);
183
184
        if (empty($result['accessToken'])) {
185
            throw new \Shetabit\Multipay\Exceptions\PurchaseFailedException('Err in generate new token.');
186
        }
187
        if (!empty($result['accessToken'])) {
188
            $this->cache->store('accessToken', 'Bearer ' . $result['accessToken'], 24 * 60 * 60 - 60);
189
            $this->cache->store('refreshToken', $result['refreshToken'], 48 * 60 * 60 - 60);
190
            $this->setAccessToken('Bearer ' . $result['accessToken']);
191
            $this->setRefreshToken($result['refreshToken']);
192
            return 'ok';
193
        }
194
        throw new \Shetabit\Multipay\Exceptions\PurchaseFailedException('unExcepted Err in generateNewToken.');
195
    }
196
197
    /**
198
     * @param string $refNum
199
     * @return bool|mixed|string
200
     * @throws Exception
201
     */
202
    public function paymentVerify($refNum)
203
    {
204
        $this->generateToken();
205
        $data = [
206
        ];
207
        return $this->callCurl('/orders/' . $refNum . '/verify', $data, true, 0, 'GET');
208
    }
209
}
210