Helper   A
last analyzed

Complexity

Total Complexity 25

Size/Duplication

Total Lines 182
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 99
c 3
b 0
f 0
dl 0
loc 182
rs 10
wmc 25

6 Methods

Rating   Name   Duplication   Size   Complexity  
B apiRequest() 0 32 6
A createOrder() 0 16 3
A createPaymentPluginOrder() 0 15 3
B getAccessToken() 0 30 7
A orderStatus() 0 16 3
A calculateSecureHash() 0 38 3
1
<?php
2
3
4
namespace bSecure\Payments\Helpers;
5
6
use bSecure\Payments\Models\Merchant;
7
8
use Exception;
9
use GuzzleHttp\Client;
10
use GuzzleHttp\Exception\RequestException;
11
12
class Helper
13
{
14
    public static function apiRequest($method, $url, $queryParams = [], $body = [], $headers = [], $contentType = 'json', $returnWithStatusCode = false)
15
    {
16
        $response = [];
17
18
        try {
19
            if (is_array($queryParams) && count($queryParams) > 0) {
20
                $url .= '?' . http_build_query($queryParams);
21
            }
22
23
            $payload = [
24
                $contentType => $body,
25
                'headers' => $headers,
26
                'http_errors' => false,
27
                'timeout' => 30,
28
                'connect_timeout' => 30
29
            ];
30
31
            $client = new Client();
32
            $curlResponse = $client->request($method, $url, $payload);
33
34
            if ($returnWithStatusCode) {
35
                $response['code'] = $curlResponse->getStatusCode();
36
                $response['content'] = json_decode($curlResponse->getBody()->getContents(), true);
37
            } else {
38
                $response = json_decode($curlResponse->getBody()->getContents(), true);
39
            }
40
        } catch (RequestException $e) {
41
//            AppException::log($e);
42
        } catch (Exception $e) {
43
//            AppException::log($e);
44
        } finally {
45
            return $response;
46
        }
47
    }
48
49
    /**
50
     * Author: Sara Hasan
51
     * Date: 10-November-2020
52
     */
53
    static function getAccessToken($data)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
54
    {
55
        $accessToken = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $accessToken is dead and can be removed.
Loading history...
56
57
        $http = new Client();
58
        $authUrl = Constant::AUTH_SERVER_URL . Constant::API_ENDPOINTS['oauth'];
59
60
        $storeId =  array_key_exists('store_id',$data) ? $data['store_id'] : null;
61
        $clientId = !empty($storeId) ? $data['client_id'].':'.$storeId : $data['client_id'];
62
63
        $response = $http->post($authUrl, [
64
            'form_params' => [
65
                'grant_type' => 'client_credentials',
66
                'client_id' => $clientId,
67
                'client_secret' => $data['client_secret'],
68
                'scope' => "",
69
            ],
70
        ]);
71
72
        $result = json_decode((string)$response->getBody("access_token"), true);
0 ignored issues
show
Unused Code introduced by
The call to Psr\Http\Message\MessageInterface::getBody() has too many arguments starting with 'access_token'. ( Ignorable by Annotation )

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

72
        $result = json_decode((string)$response->/** @scrutinizer ignore-call */ getBody("access_token"), true);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
73
74
        if (isset($result['status']) && $result['status'] == Constant::HTTP_RESPONSE_STATUSES['success']) {
75
76
            $merchantEnvironmentCheck = config('bSecure.integration_type') ?? 'sandbox';
0 ignored issues
show
Bug introduced by
The function config 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

76
            $merchantEnvironmentCheck = /** @scrutinizer ignore-call */ config('bSecure.integration_type') ?? 'sandbox';
Loading history...
77
78
            if ($merchantEnvironmentCheck == $result['body']['environment']) {
79
                $accessToken = isset($result['body']['access_token']) ? $result['body']['access_token'] : null;
80
                return ['client_id' => '', 'error' => false, 'accessToken' => $accessToken];
81
            } else {
82
                return ['client_id' => '', 'error' => true, 'message' => trans('bSecurePayments::messages.client.environment.invalid')];
0 ignored issues
show
Bug introduced by
The function trans 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

82
                return ['client_id' => '', 'error' => true, 'message' => /** @scrutinizer ignore-call */ trans('bSecurePayments::messages.client.environment.invalid')];
Loading history...
83
            }
84
        }
85
    }
86
87
    /**
88
     * Author: Sara Hasan
89
     * Date: 10-November-2020
90
     */
91
    static function createPaymentPluginOrder($orderPayload)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
92
    {
93
        $method = 'POST';
94
95
        $url = Constant::AUTH_SERVER_URL . Constant::API_ENDPOINTS['payment_plugin_order'];
96
        $headers = [];
97
98
        $result = Helper::apiRequest($method, $url, [], $orderPayload, $headers, 'form_params');
99
100
        if (isset($result['status']) && $result['status'] == Constant::HTTP_RESPONSE_STATUSES['success']) {
101
            $response = ['error' => false, 'body' => $result['body']];
102
        } else {
103
            $response = ['error' => true, 'body' => $result];
104
        }
105
        return $response;
106
    }
107
108
109
110
    /**
111
     * Author: Sara Hasan
112
     * Date: 10-November-2020
113
     */
114
    static function createOrder($merchantAccessToken, $orderPayload)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
115
    {
116
        $method = 'POST';
117
118
        $url = Constant::AUTH_SERVER_URL . Constant::API_ENDPOINTS['create_order'];
119
120
        $headers = ['Authorization' => 'Bearer ' . $merchantAccessToken];
121
122
        $result = Helper::apiRequest($method, $url, [], $orderPayload, $headers, 'form_params');
123
124
        if (isset($result['status']) && $result['status'] == Constant::HTTP_RESPONSE_STATUSES['success']) {
125
            $response = ['error' => false, 'body' => $result['body']];
126
        } else {
127
            $response = ['error' => true, 'body' => $result];
128
        }
129
        return $response;
130
    }
131
132
133
    /**
134
     * Author: Sara Hasan
135
     * Date: 10-November-2020
136
     */
137
    static function orderStatus($merchantAccessToken, $order_ref)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
138
    {
139
        $method = 'POST';
140
141
        $url = Constant::AUTH_SERVER_URL . Constant::API_ENDPOINTS['order_status'];
142
143
        $headers = ['Authorization' => 'Bearer ' . $merchantAccessToken];
144
145
        $result = Helper::apiRequest($method, $url, [], $order_ref, $headers, 'form_params');
146
147
        if (isset($result['status']) && $result['status'] == Constant::HTTP_RESPONSE_STATUSES['success']) {
148
            $response = ['error' => false, 'body' => $result['body']];
149
        } else {
150
            $response = ['error' => true, 'body' => $result];
151
        }
152
        return $response;
153
    }
154
155
156
    static function calculateSecureHash($payload){
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
157
        $details = [
158
            '__00trid__' => $payload['order']['order_id'],
159
            '__01curr__' => $payload['order']['currency'],
160
            '__02trdt__' => $payload['txn_reference'],
161
            '__03stamt__' => $payload['order']['sub_total_amount'],
162
            '__04damt__' => $payload['order']['discount_amount'],
163
            '__05tamt__' => $payload['order']['total_amount'],
164
            '__06cname__' => $payload['customer']['name'],
165
            '__07ccc__' => $payload['customer']['country_code'],
166
            '__08cphn__' => $payload['customer']['phone_number'],
167
            '__09cemail__' => $payload['customer']['email'],
168
            '__10ccc__' => $payload['customer_address']['country'],
169
            '__11cstate__' => $payload['customer_address']['province'],
170
            '__12ccity__' => $payload['customer_address']['city'],
171
            '__13carea__' => $payload['customer_address']['area'],
172
            '__14cfadd__' => $payload['customer_address']['address'],
173
            '__15mid__' => $payload['merchant_id'],
174
            '__16stid__' => $payload['store_id'],
175
            '__18ver__' => $payload['plugin_version'],
176
            '__19lan__' => 'EN',
177
            '__20red__' => $payload['redirect_url'],
178
            '__21cenv__' => $payload['env_id'],
179
        ];
180
181
        $salt = config('bSecurePayments.client_id');
0 ignored issues
show
Bug introduced by
The function config 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

181
        $salt = /** @scrutinizer ignore-call */ config('bSecurePayments.client_id');
Loading history...
182
        ksort($details);
183
        $signature = $salt."&";
184
        foreach($details as $key => $value)
185
        {
186
            $signature .= preg_replace("/\s+/", "", $value);
187
            if(next($details)) {
188
                $signature .= "&";
189
            }
190
        }
191
        $setSignature = hash_hmac('sha256', $signature, $salt);
192
193
        return strtoupper($setSignature);
194
    }
195
196
197
}
198
199