Passed
Pull Request — master (#20)
by odenktools
02:02
created

BcaHttp::__construct()   B

Complexity

Conditions 9
Paths 192

Size

Total Lines 69
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 44
c 1
b 0
f 0
dl 0
loc 69
rs 7.0471
cc 9
nc 192
nop 6

How to fix   Long Method   

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 Bca;
4
5
use Carbon\Carbon;
6
use Unirest\Request;
7
use Unirest\Request\Body;
8
9
/**
10
 * BCA REST API Library.
11
 *
12
 * @author     Pribumi Technology
13
 * @license    MIT
14
 * @copyright  (c) 2017-2021, Pribumi Technology
15
 */
16
class BcaHttp
17
{
18
    public static $VERSION = '2.3.3';
19
20
    /**
21
     * Default Timezone.
22
     *
23
     * @var string
24
     */
25
    private static $timezone = 'Asia/Jakarta';
26
27
    /**
28
     * Default BCA Port.
29
     *
30
     * @var int
31
     */
32
    private static $port = 443;
33
34
    /**
35
     * Default BCA Host.
36
     *
37
     * @var string
38
     */
39
    private static $hostName = 'sandbox.bca.co.id';
40
41
    /**
42
     * Default BCA Host.
43
     *
44
     * @var string
45
     */
46
    private static $scheme = 'https';
47
48
    /**
49
     * Timeout curl.
50
     *
51
     * @var int
52
     */
53
    private static $timeOut = 60;
54
55
    /**
56
     * Default Curl Options.
57
     *
58
     * @var int
59
     */
60
    private static $curlOptions = array(
61
        CURLOPT_SSL_VERIFYHOST => 0,
62
        CURLOPT_SSLVERSION => 6,
63
        CURLOPT_SSL_VERIFYPEER => false,
64
        CURLOPT_TIMEOUT => 60
65
    );
66
67
    /**
68
     * Default BCA Settings.
69
     *
70
     * @var array
71
     */
72
    protected $settings = array(
73
        'corp_id' => '',
74
        'client_id' => '',
75
        'client_secret' => '',
76
        'api_key' => '',
77
        'secret_key' => '',
78
        'curl_options' => array(),
79
        // Backward compatible
80
        'host' => 'sandbox.bca.co.id',
81
        'scheme' => 'https',
82
        'timeout' => 60,
83
        'port' => 443,
84
        'timezone' => 'Asia/Jakarta',
85
        // New Options
86
        'options' => array(
87
            'host' => 'sandbox.bca.co.id',
88
            'scheme' => 'https',
89
            'timeout' => 60,
90
            'port' => 443,
91
            'timezone' => 'Asia/Jakarta'
92
        )
93
    );
94
95
    /**
96
     * Default Constructor.
97
     *
98
     * @param string $corp_id nilai corp id
99
     * @param string $client_id nilai client key
100
     * @param string $client_secret nilai client secret
101
     * @param string $api_key niali oauth key
102
     * @param string $secret_key nilai oauth secret
103
     * @param array $options opsi ke server bca
104
     */
105
    public function __construct($corp_id, $client_id, $client_secret, $api_key, $secret_key, array $options = [])
106
    {
107
        // Required parameters.
108
        $this->settings['corp_id'] = $corp_id;
109
        $this->settings['client_id'] = $client_id;
110
        $this->settings['client_secret'] = $client_secret;
111
        $this->settings['api_key'] = $api_key;
112
        $this->settings['secret_key'] = $secret_key;
113
        $this->settings['host'] =
114
            preg_replace('/http[s]?\:\/\//', '', $this->settings['host'], 1);
115
116
        foreach ($options as $key => $value) {
117
            if (isset($this->settings[$key])) {
118
                $this->settings[$key] = $value;
119
            }
120
        }
121
122
        // Setup optional scheme, if scheme is empty
123
        if (isset($options['scheme'])) {
124
            $this->settings['scheme'] = $options['scheme'];
125
            $this->settings['options']['scheme'] = $options['scheme'];
126
        } else {
127
            $this->settings['scheme'] = self::getScheme();
128
            $this->settings['options']['scheme'] = self::getScheme();
129
        }
130
131
        // Setup optional host, if host is empty
132
        if (isset($options['host'])) {
133
            $this->settings['host'] = $options['host'];
134
            $this->settings['options']['host'] = $options['host'];
135
        } else {
136
            $this->settings['host'] = self::getHostName();
137
            $this->settings['options']['host'] = self::getHostName();
138
        }
139
140
        // Setup optional port, if port is empty
141
        if (isset($options['port'])) {
142
            $this->settings['port'] = $options['port'];
143
            $this->settings['options']['port'] = $options['port'];
144
        } else {
145
            $this->settings['port'] = self::getPort();
146
            $this->settings['options']['port'] = self::getPort();
147
        }
148
149
        // Setup optional timezone, if timezone is empty
150
        if (isset($options['timezone'])) {
151
            $this->settings['timezone'] = $options['timezone'];
152
            $this->settings['options']['timezone'] = $options['timezone'];
153
        } else {
154
            $this->settings['timezone'] = self::getTimeZone();
155
            $this->settings['options']['timezone'] = self::getTimeZone();
156
        }
157
158
        // Setup optional timeout, if timeout is empty
159
        if (isset($options['timeout'])) {
160
            $this->settings['timeout'] = $options['timeout'];
161
            $this->settings['options']['timeout'] = $options['timeout'];
162
        } else {
163
            $this->settings['timeout'] = self::getTimeOut();
164
            $this->settings['options']['timeout'] = self::getTimeOut();
165
        }
166
167
        // Set Default Curl Options.
168
        Request::curlOpts(self::$curlOptions);
0 ignored issues
show
Bug introduced by
self::curlOptions of type integer is incompatible with the type array expected by parameter $options of Unirest\Request::curlOpts(). ( Ignorable by Annotation )

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

168
        Request::curlOpts(/** @scrutinizer ignore-type */ self::$curlOptions);
Loading history...
169
170
        // Set custom curl options
171
        if (!empty($this->settings['curl_options'])) {
172
            $data = self::mergeCurlOptions(self::$curlOptions, $this->settings['curl_options']);
0 ignored issues
show
Bug introduced by
self::curlOptions of type integer is incompatible with the type array expected by parameter $existing_options of Bca\BcaHttp::mergeCurlOptions(). ( Ignorable by Annotation )

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

172
            $data = self::mergeCurlOptions(/** @scrutinizer ignore-type */ self::$curlOptions, $this->settings['curl_options']);
Loading history...
173
            Request::curlOpts($data);
174
        }
175
    }
176
177
    /**
178
     * Ambil Nilai settings.
179
     *
180
     * @return array
181
     */
182
    public function getSettings()
183
    {
184
        return $this->settings;
185
    }
186
187
    /**
188
     * Build the ddn domain.
189
     * output = 'https://sandbox.bca.co.id:443'
190
     * scheme = http(s)
191
     * host = sandbox.bca.co.id
192
     * port = 80 ? 443
193
     *
194
     * @return string
195
     */
196
    private function ddnDomain()
197
    {
198
        return $this->settings['scheme'] . '://' . $this->settings['host'] . ':' . $this->settings['port'] . '/';
199
    }
200
201
    /**
202
     * Generate authentifikasi ke server berupa OAUTH.
203
     *
204
     * @return \Unirest\Response
205
     */
206
    public function httpAuth()
207
    {
208
        $client_id = $this->settings['client_id'];
209
        $client_secret = $this->settings['client_secret'];
210
211
        $headerToken = base64_encode("$client_id:$client_secret");
212
213
        $headers = array('Accept' => 'application/json', 'Authorization' => "Basic $headerToken");
214
215
        $request_path = "api/oauth/token";
216
        $domain = $this->ddnDomain();
217
        $full_url = $domain . $request_path;
218
219
        $data = array('grant_type' => 'client_credentials');
220
        $body = Body::form($data);
221
        $response = Request::post($full_url, $headers, $body);
222
223
        return $response;
224
    }
225
226
    /**
227
     * Ambil informasi saldo berdasarkan nomor akun BCA.
228
     *
229
     * @param string $oauth_token nilai token yang telah didapatkan setelah login
230
     * @param array $sourceAccountId nomor akun yang akan dicek
231
     *
232
     * @throws BcaHttpException error
233
     * @return \Unirest\Response
234
     */
235
    public function getBalanceInfo($oauth_token, $sourceAccountId = [])
236
    {
237
        $corp_id = $this->settings['corp_id'];
238
239
        $this->validateArray($sourceAccountId);
240
241
        ksort($sourceAccountId);
242
        $arraySplit = implode(",", $sourceAccountId);
243
        $arraySplit = urlencode($arraySplit);
244
245
        $uriSign = "GET:/banking/v3/corporates/$corp_id/accounts/$arraySplit";
246
        $isoTime = self::generateIsoTime();
247
        $authSignature = self::generateSign($uriSign, $oauth_token, $this->settings['secret_key'], $isoTime, null);
248
249
        $headers = array();
250
        $headers['Accept'] = 'application/json';
251
        $headers['Content-Type'] = 'application/json';
252
        $headers['Authorization'] = "Bearer $oauth_token";
253
        $headers['X-BCA-Key'] = $this->settings['api_key'];
254
        $headers['X-BCA-Timestamp'] = $isoTime;
255
        $headers['X-BCA-Signature'] = $authSignature;
256
257
        $request_path = "banking/v3/corporates/$corp_id/accounts/$arraySplit";
258
        $domain = $this->ddnDomain();
259
        $full_url = $domain . $request_path;
260
261
        $data = array('grant_type' => 'client_credentials');
262
263
        $body = Body::form($data);
264
        $response = Request::get($full_url, $headers, $body);
265
266
        return $response;
267
    }
268
269
    /**
270
     * Ambil Daftar transaksi pertanggal.
271
     *
272
     * @param string $oauth_token nilai token yang telah didapatkan setelah login
273
     * @param string $sourceAccount nomor akun yang akan dicek
274
     * @param string $startDate tanggal awal
275
     * @param string $endDate tanggal akhir
276
     *
277
     * @return \Unirest\Response
278
     */
279
    public function getAccountStatement($oauth_token, $sourceAccount, $startDate, $endDate)
280
    {
281
        $corp_id = $this->settings['corp_id'];
282
        $uriSign = "GET:/banking/v3/corporates/$corp_id/accounts/$sourceAccount/statements?EndDate=$endDate&StartDate=$startDate";
283
        $isoTime = self::generateIsoTime();
284
        $authSignature = self::generateSign($uriSign, $oauth_token, $this->settings['secret_key'], $isoTime, null);
285
        $headers = array();
286
        $headers['Accept'] = 'application/json';
287
        $headers['Content-Type'] = 'application/json';
288
        $headers['Authorization'] = "Bearer $oauth_token";
289
        $headers['X-BCA-Key'] = $this->settings['api_key'];
290
        $headers['X-BCA-Timestamp'] = $isoTime;
291
        $headers['X-BCA-Signature'] = $authSignature;
292
        $request_path = "banking/v3/corporates/$corp_id/accounts/$sourceAccount/statements?EndDate=$endDate&StartDate=$startDate";
293
        $domain = $this->ddnDomain();
294
        $full_url = $domain . $request_path;
295
296
        $data = array('grant_type' => 'client_credentials');
297
        $body = Body::form($data);
298
        $response = Request::get($full_url, $headers, $body);
299
        return $response;
300
    }
301
302
    /**
303
     * Ambil informasi ATM berdasarkan lokasi GEO.
304
     *
305
     * @param string $oauth_token nilai token yang telah didapatkan setelah login
306
     * @param string $latitude Langitude GPS
307
     * @param string $longitude Longitude GPS
308
     * @param string $count Jumlah ATM BCA yang akan ditampilkan
309
     * @param string $radius Nilai radius dari lokasi GEO
310
     *
311
     * @throws BcaHttpException error
312
     * @return \Unirest\Response
313
     */
314
    public function getAtmLocation(
315
        $oauth_token,
316
        $latitude,
317
        $longitude,
318
        $count = '10',
319
        $radius = '20'
320
    )
321
    {
322
        $params = array();
323
        $params['SearchBy'] = 'Distance';
324
        $params['Latitude'] = $latitude;
325
        $params['Longitude'] = $longitude;
326
        $params['Count'] = $count;
327
        $params['Radius'] = $radius;
328
        ksort($params);
329
330
        $auth_query_string = self::arrayImplode('=', '&', $params);
331
332
        $uriSign = "GET:/general/info-bca/atm?$auth_query_string";
333
        $isoTime = self::generateIsoTime();
334
        $authSignature = self::generateSign($uriSign, $oauth_token, $this->settings['secret_key'], $isoTime, null);
335
336
        $headers = array();
337
        $headers['Accept'] = 'application/json';
338
        $headers['Content-Type'] = 'application/json';
339
        $headers['Authorization'] = "Bearer $oauth_token";
340
        $headers['X-BCA-Key'] = $this->settings['api_key'];
341
        $headers['X-BCA-Timestamp'] = $isoTime;
342
        $headers['X-BCA-Signature'] = $authSignature;
343
344
        $request_path = "general/info-bca/atm?SearchBy=Distance&Latitude=$latitude&Longitude=$longitude&Count=$count&Radius=$radius";
345
        $domain = $this->ddnDomain();
346
        $full_url = $domain . $request_path;
347
348
        $data = array('grant_type' => 'client_credentials');
349
        $body = Body::form($data);
350
        $response = Request::get($full_url, $headers, $body);
351
352
        return $response;
353
    }
354
355
    /**
356
     * Transfer dana kepada akun yang berbeda bank dengan jumlah nominal tertentu.
357
     *
358
     * @param string $oauth_token nilai token yang telah didapatkan setelah login.
359
     * @param string $channelId Unknown description.
360
     * @param int $amount nilai dana dalam RUPIAH yang akan ditransfer, Format: 13.2
361
     * @param string $sourceAccountNumber Source of Fund Account Number
362
     * @param string $beneficiaryAccountNumber BCA Account number to be credited (Destination)
363
     * @param string $beneficiaryBankCode Kode Bank to be credited (Destination)
364
     * @param string $beneficiaryCustResidence 1 = Resident 2 = Non Resident *mandatory, if transfer_type = LLG/RTG
365
     * @param string $beneficiaryCustType 1 = Personal 2 = Corporate 3 = Government *mandatory, if transfer_type = LLG/RTG
366
     * @param string $beneficiaryName Nama penerima.
367
     * @param string $beneficiaryEmail Email penerima.
368
     * @param string $transactionID Transcation ID unique per day (using UTC+07 Time Zone). Format: Number
369
     * @param string $transactionType ONL (Switching) ; LLG; RTG (RTGS)
370
     * @param string $remark1 Transfer remark for receiver
371
     * @param string $remark2 ransfer remark for receiver
372
     * @param string $currencyCode nilai MATA Uang [Optional]
373
     *
374
     * @return \Unirest\Response
375
     */
376
    public function fundTransfersDomestic(
377
        $oauth_token,
378
        $channelId,
379
        $amount,
380
        $sourceAccountNumber,
381
        $beneficiaryAccountNumber,
382
        $beneficiaryBankCode,
383
        $beneficiaryCustResidence,
384
        $beneficiaryCustType,
385
        $beneficiaryName,
386
        $beneficiaryEmail,
387
        $transactionID,
388
        $transactionType,
389
        $remark1,
390
        $remark2,
391
        $currencyCode = 'IDR'
392
    )
393
    {
394
        $uriSign = "POST:/banking/corporates/transfers/v2/domestic";
395
        $isoTime = self::generateIsoTime();
396
        $headers = array();
397
        $headers['Accept'] = 'application/json';
398
        $headers['Content-Type'] = 'application/json';
399
        $headers['Authorization'] = "Bearer $oauth_token";
400
        $headers['X-BCA-Key'] = $this->settings['api_key'];
401
        $headers['X-BCA-Timestamp'] = $isoTime;
402
        $headers['channel-id'] = $channelId;
403
        $headers['credential-id'] = $this->settings['corp_id'];
404
405
        $request_path = "banking/corporates/transfers/v2/domestic";
406
        $domain = $this->ddnDomain();
407
        $full_url = $domain . $request_path;
408
409
        $bodyData = array();
410
        $bodyData['amount'] = $amount;
411
        $bodyData['beneficiary_account_number'] = strtolower(str_replace(' ', '', $beneficiaryAccountNumber));
412
        $bodyData['beneficiary_bank_code'] = strtolower(str_replace(' ', '', $beneficiaryBankCode));
413
        $bodyData['beneficiary_cust_residence'] = $beneficiaryCustResidence;
414
        $bodyData['beneficiary_cust_type'] = $beneficiaryCustType;
415
        $bodyData['beneficiary_name'] = strtolower(str_replace(' ', '', $beneficiaryName));
416
        if (empty($beneficiaryEmail) || $beneficiaryEmail === '') {
417
            $bodyData['beneficiary_email'] = '';
418
        } else {
419
            $bodyData['beneficiary_email'] = strtolower(str_replace(' ', '', $beneficiaryEmail));
420
        }
421
        $bodyData['currency_code'] = $currencyCode;
422
        $bodyData['remark1'] = !empty($remark1) ? strtolower(str_replace(' ', '', $remark1)) : "";
423
        $bodyData['remark1'] = !empty($remark2) ? strtolower(str_replace(' ', '', $remark2)) : "";
424
        $bodyData['source_account_number'] = strtolower(str_replace(' ', '', $sourceAccountNumber));
425
        $bodyData['transaction_date'] = self::generateDateTransaction();
426
        $bodyData['transaction_id'] = strtolower(str_replace(' ', '', $transactionID));
427
        $bodyData['transfer_type'] = strtoupper(str_replace(' ', '', $transactionType));
428
429
        // Harus disort agar mudah kalkulasi HMAC
430
        ksort($bodyData);
431
432
        $authSignature = self::generateSign($uriSign, $oauth_token, $this->settings['secret_key'], $isoTime, $bodyData);
433
434
        $headers['X-BCA-Signature'] = $authSignature;
435
436
        // Supaya jgn strip "ReferenceID" "/" jadi "/\" karena HMAC akan menjadi tidak cocok
437
        $encoderData = json_encode($bodyData, JSON_UNESCAPED_SLASHES);
438
439
        $body = Body::form($encoderData);
440
        $response = Request::post($full_url, $headers, $body);
441
442
        return $response;
443
    }
444
445
    /**
446
     * Ambil KURS mata uang.
447
     *
448
     * @param string $oauth_token nilai token yang telah didapatkan setelah login
449
     * @param string $rateType type rate
450
     * @param string $currency Mata uang
451
     *
452
     * @throws BcaHttpException error
453
     * @return \Unirest\Response
454
     */
455
    public function getForexRate(
456
        $oauth_token,
457
        $rateType = 'eRate',
458
        $currency = 'USD'
459
    )
460
    {
461
        $params = array();
462
        $params['RateType'] = strtolower($rateType);
463
        $params['CurrencyCode'] = strtoupper($currency);
464
        ksort($params);
465
466
        $auth_query_string = self::arrayImplode('=', '&', $params);
467
468
        $uriSign = "GET:/general/rate/forex?$auth_query_string";
469
        $isoTime = self::generateIsoTime();
470
        $authSignature = self::generateSign($uriSign, $oauth_token, $this->settings['secret_key'], $isoTime, null);
471
472
        $headers = array();
473
        $headers['Accept'] = 'application/json';
474
        $headers['Content-Type'] = 'application/json';
475
        $headers['Authorization'] = "Bearer $oauth_token";
476
        $headers['X-BCA-Key'] = $this->settings['api_key'];
477
        $headers['X-BCA-Timestamp'] = $isoTime;
478
        $headers['X-BCA-Signature'] = $authSignature;
479
480
        $request_path = "general/rate/forex?$auth_query_string";
481
        $domain = $this->ddnDomain();
482
        $full_url = $domain . $request_path;
483
484
        $data = array('grant_type' => 'client_credentials');
485
        $body = Body::form($data);
486
        $response = Request::get($full_url, $headers, $body);
487
488
        return $response;
489
    }
490
491
    /**
492
     * Transfer dana kepada akun lain dengan jumlah nominal tertentu.
493
     *
494
     * @param string $oauth_token nilai token yang telah didapatkan setelah login
495
     * @param int $amount nilai dana dalam RUPIAH yang akan ditransfer, Format: 13.2
496
     * @param string $beneficiaryAccountNumber BCA Account number to be credited (Destination)
497
     * @param string $referenceID Sender's transaction reference ID
498
     * @param string $remark1 Transfer remark for receiver
499
     * @param string $remark2 ransfer remark for receiver
500
     * @param string $sourceAccountNumber Source of Fund Account Number
501
     * @param string $transactionID Transcation ID unique per day (using UTC+07 Time Zone). Format: Number
502
     * @param string $currencyCode nilai MATA Uang [Optional]
503
     *
504
     * @return \Unirest\Response
505
     */
506
    public function fundTransfers(
507
        $oauth_token,
508
        $amount,
509
        $sourceAccountNumber,
510
        $beneficiaryAccountNumber,
511
        $referenceID,
512
        $remark1,
513
        $remark2,
514
        $transactionID,
515
        $currencyCode = 'idr'
516
    )
517
    {
518
        $uriSign = "POST:/banking/corporates/transfers";
519
520
        $isoTime = self::generateIsoTime();
521
522
        $headers = array();
523
        $headers['Accept'] = 'application/json';
524
        $headers['Content-Type'] = 'application/json';
525
        $headers['Authorization'] = "Bearer $oauth_token";
526
        $headers['X-BCA-Key'] = $this->settings['api_key'];
527
        $headers['X-BCA-Timestamp'] = $isoTime;
528
529
        $request_path = "banking/corporates/transfers";
530
        $domain = $this->ddnDomain();
531
        $full_url = $domain . $request_path;
532
533
        $bodyData = array();
534
        $bodyData['Amount'] = $amount;
535
        $bodyData['BeneficiaryAccountNumber'] = strtolower(str_replace(' ', '', $beneficiaryAccountNumber));
536
        $bodyData['CorporateID'] = strtolower(str_replace(' ', '', $this->settings['corp_id']));
537
        $bodyData['CurrencyCode'] = $currencyCode;
538
        $bodyData['ReferenceID'] = strtolower(str_replace(' ', '', $referenceID));
539
        $bodyData['Remark1'] = strtolower(str_replace(' ', '', $remark1));
540
        $bodyData['Remark2'] = strtolower(str_replace(' ', '', $remark2));
541
        $bodyData['SourceAccountNumber'] = strtolower(str_replace(' ', '', $sourceAccountNumber));
542
        $bodyData['TransactionDate'] = $isoTime;
543
        $bodyData['TransactionID'] = strtolower(str_replace(' ', '', $transactionID));
544
545
        // Harus disort agar mudah kalkulasi HMAC
546
        ksort($bodyData);
547
548
        $authSignature = self::generateSign($uriSign, $oauth_token, $this->settings['secret_key'], $isoTime, $bodyData);
549
550
        $headers['X-BCA-Signature'] = $authSignature;
551
552
        // Supaya jgn strip "ReferenceID" "/" jadi "/\" karena HMAC akan menjadi tidak cocok
553
        $encoderData = json_encode($bodyData, JSON_UNESCAPED_SLASHES);
554
555
        $body = Body::form($encoderData);
556
        $response = Request::post($full_url, $headers, $body);
557
558
        return $response;
559
    }
560
561
    /**
562
     * Realtime deposit untuk produk BCA.
563
     *
564
     * @param string $oauth_token nilai token yang telah didapatkan setelah login
565
     *
566
     * @return \Unirest\Response
567
     */
568
    public function getDepositRate($oauth_token)
569
    {
570
        $uriSign = "GET:/general/rate/deposit";
571
        $isoTime = self::generateIsoTime();
572
        $authSignature = self::generateSign($uriSign, $oauth_token, $this->settings['secret_key'], $isoTime, null);
573
574
        $headers = array();
575
        $headers['Accept'] = 'application/json';
576
        $headers['Content-Type'] = 'application/json';
577
        $headers['Authorization'] = "Bearer $oauth_token";
578
        $headers['X-BCA-Key'] = $this->settings['api_key'];
579
        $headers['X-BCA-Timestamp'] = $isoTime;
580
        $headers['X-BCA-Signature'] = $authSignature;
581
582
        $request_path = "general/rate/deposit";
583
        $domain = $this->ddnDomain();
584
        $full_url = $domain . $request_path;
585
586
        $data = array('grant_type' => 'client_credentials');
587
588
        $body = Body::form($data);
589
        $response = Request::get($full_url, $headers, $body);
590
591
        return $response;
592
    }
593
594
    /**
595
     * Generate Signature.
596
     *
597
     * @param string $url Url yang akan disign.
598
     * @param string $auth_token string nilai token dari login.
599
     * @param string $secret_key string secretkey yang telah diberikan oleh BCA.
600
     * @param string $isoTime string Waktu ISO8601.
601
     * @param array|mixed $bodyToHash array Body yang akan dikirimkan ke Server BCA.
602
     *
603
     * @return string
604
     */
605
    public static function generateSign($url, $auth_token, $secret_key, $isoTime, $bodyToHash = [])
606
    {
607
        $hash = hash("sha256", "");
608
        if (is_array($bodyToHash)) {
609
            ksort($bodyToHash);
610
            $encoderData = json_encode($bodyToHash, JSON_UNESCAPED_SLASHES);
611
            $hash = hash("sha256", $encoderData);
612
        }
613
        $stringToSign = $url . ":" . $auth_token . ":" . $hash . ":" . $isoTime;
614
        $auth_signature = hash_hmac('sha256', $stringToSign, $secret_key, false);
615
616
        return $auth_signature;
617
    }
618
619
    /**
620
     * Set TimeZone.
621
     *
622
     * @param string $timeZone Time yang akan dipergunakan.
623
     *
624
     * @return string
625
     */
626
    public static function setTimeZone($timeZone)
627
    {
628
        self::$timezone = $timeZone;
629
        return self::$timezone;
630
    }
631
632
    /**
633
     * Get TimeZone.
634
     *
635
     * @return string
636
     */
637
    public static function getTimeZone()
638
    {
639
        return self::$timezone;
640
    }
641
642
    /**
643
     * Set nama domain BCA yang akan dipergunakan.
644
     *
645
     * @param string $hostName nama domain BCA yang akan dipergunakan.
646
     *
647
     * @return string
648
     */
649
    public static function setHostName($hostName)
650
    {
651
        self::$hostName = $hostName;
652
653
        return self::$hostName;
654
    }
655
656
    /**
657
     * Ambil nama domain BCA yang akan dipergunakan.
658
     *
659
     * @return string
660
     */
661
    public static function getHostName()
662
    {
663
        return self::$hostName;
664
    }
665
666
    /**
667
     * Ambil maximum execution time.
668
     *
669
     * @return string
670
     */
671
    public static function getTimeOut()
672
    {
673
        return self::$timeOut;
674
    }
675
676
    /**
677
     * Ambil nama domain BCA yang akan dipergunakan.
678
     *
679
     * @return string
680
     */
681
    public static function getCurlOptions()
682
    {
683
        return self::$curlOptions;
684
    }
685
686
    /**
687
     * Setup curl options.
688
     *
689
     * @param array $curlOpts
690
     * @return array
691
     */
692
    public static function setCurlOptions(array $curlOpts = [])
693
    {
694
        $data = self::mergeCurlOptions(self::$curlOptions, $curlOpts);
0 ignored issues
show
Bug introduced by
self::curlOptions of type integer is incompatible with the type array expected by parameter $existing_options of Bca\BcaHttp::mergeCurlOptions(). ( Ignorable by Annotation )

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

694
        $data = self::mergeCurlOptions(/** @scrutinizer ignore-type */ self::$curlOptions, $curlOpts);
Loading history...
695
        self::$curlOptions = $data;
0 ignored issues
show
Documentation Bug introduced by
It seems like $data of type array is incompatible with the declared type integer of property $curlOptions.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
696
697
        // return.
698
        return self::$curlOptions;
699
    }
700
701
    /**
702
     * Set Ambil maximum execution time.
703
     *
704
     * @param int $timeOut timeout in milisecond.
705
     *
706
     * @return string
707
     */
708
    public static function setTimeOut($timeOut)
709
    {
710
        self::$timeOut = $timeOut;
711
712
        // return.
713
        return self::$timeOut;
714
    }
715
716
    /**
717
     * Set BCA port
718
     *
719
     * @param int $port Port yang akan dipergunakan
720
     *
721
     * @return int
722
     */
723
    public static function setPort($port)
724
    {
725
        self::$port = $port;
726
727
        // return.
728
        return self::$port;
729
    }
730
731
    /**
732
     * Get BCA port
733
     *
734
     * @return int
735
     */
736
    public static function getPort()
737
    {
738
        return self::$port;
739
    }
740
741
    /**
742
     * Set BCA Schema
743
     *
744
     * @param int $scheme Scheme yang akan dipergunakan
745
     *
746
     * @return string
747
     */
748
    public static function setScheme($scheme)
749
    {
750
        self::$scheme = $scheme;
751
752
        // return.
753
        return self::$scheme;
754
    }
755
756
    /**
757
     * Get BCA Schema
758
     *
759
     * @return string
760
     */
761
    public static function getScheme()
762
    {
763
        return self::$scheme;
764
    }
765
766
    /**
767
     * Generate ISO8601 Time.
768
     *
769
     * @return string
770
     */
771
    public static function generateIsoTime()
772
    {
773
        $date = Carbon::now(self::getTimeZone());
774
        date_default_timezone_set(self::getTimeZone());
775
        $fmt = $date->format('Y-m-d\TH:i:s');
776
        $ISO8601 = sprintf("$fmt.%s%s", substr(microtime(), 2, 3), date('P'));
777
778
        return $ISO8601;
779
    }
780
781
    /**
782
     * Generate ISO8601 Time.
783
     *
784
     * @return string
785
     */
786
    public static function generateDateTransaction()
787
    {
788
        $date = Carbon::now(self::getTimeZone());
789
        date_default_timezone_set(self::getTimeZone());
790
        $fmt = $date->format('Y-m-d');
791
792
        return $fmt;
793
    }
794
795
    /**
796
     * Merge from existing array.
797
     *
798
     * @param array $existing_options
799
     * @param array $new_options
800
     * @return array
801
     */
802
    private static function mergeCurlOptions(&$existing_options, $new_options)
803
    {
804
        $existing_options = $new_options + $existing_options;
805
        return $existing_options;
806
    }
807
808
    /**
809
     * Validasi jika clientsecret telah di-definsikan.
810
     *
811
     * @param array $sourceAccountId
812
     *
813
     * @throws BcaHttpException Error jika array tidak memenuhi syarat
814
     * @return bool
815
     */
816
    private function validateArray($sourceAccountId = [])
817
    {
818
        if (!is_array($sourceAccountId)) {
0 ignored issues
show
introduced by
The condition is_array($sourceAccountId) is always true.
Loading history...
819
            throw new BcaHttpException('Data harus array.');
820
        }
821
        if (empty($sourceAccountId)) {
822
            throw new BcaHttpException('AccountNumber tidak boleh kosong.');
823
        } else {
824
            $max = sizeof($sourceAccountId);
825
            if ($max > 20) {
826
                throw new BcaHttpException('Maksimal Account Number ' . 20);
827
            }
828
        }
829
830
        return true;
831
    }
832
833
    /**
834
     * Implode an array with the key and value pair giving
835
     * a glue, a separator between pairs and the array
836
     * to implode.
837
     *
838
     * @param string $glue The glue between key and value
839
     * @param string $separator Separator between pairs
840
     * @param array $array The array to implode
841
     *
842
     * @throws BcaHttpException error
843
     * @return string The imploded array
844
     */
845
    public static function arrayImplode($glue, $separator, $array = [])
846
    {
847
        if (!is_array($array)) {
0 ignored issues
show
introduced by
The condition is_array($array) is always true.
Loading history...
848
            throw new BcaHttpException('Data harus array.');
849
        }
850
        if (empty($array)) {
851
            throw new BcaHttpException('parameter array tidak boleh kosong.');
852
        }
853
        foreach ($array as $key => $val) {
854
            if (is_array($val)) {
855
                $val = implode(',', $val);
856
            }
857
            $string[] = "{$key}{$glue}{$val}";
858
        }
859
860
        return implode($separator, $string);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $string seems to be defined by a foreach iteration on line 853. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
861
    }
862
}
863