Failed Conditions
Push — feature/json-api ( 16ac3f )
by Remco
07:50
created

Gateway::start()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 96
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 57
c 2
b 0
f 0
nc 1
nop 1
dl 0
loc 96
ccs 0
cts 76
cp 0
crap 2
rs 8.9381

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 Pronamic\WordPress\Pay\Gateways\Buckaroo;
4
5
use Pronamic\WordPress\Pay\Banks\BankAccountDetails;
6
use Pronamic\WordPress\Pay\Core\Gateway as Core_Gateway;
7
use Pronamic\WordPress\Pay\Core\PaymentMethods as Core_PaymentMethods;
8
use Pronamic\WordPress\Pay\Core\Server;
9
use Pronamic\WordPress\Pay\Payments\Payment;
10
11
/**
12
 * Title: Buckaroo gateway
13
 * Description:
14
 * Copyright: 2005-2021 Pronamic
15
 * Company: Pronamic
16
 *
17
 * @author Remco Tolsma
18
 * @version 2.0.4
19
 * @since 1.0.0
20
 */
21
class Gateway extends Core_Gateway {
22
	/**
23
	 * Client.
24
	 *
25
	 * @var Client
26
	 */
27
	protected $client;
28
29
	/**
30
	 * Constructs and initializes an Buckaroo gateway
31
	 *
32
	 * @param Config $config Config.
33
	 */
34
	public function __construct( Config $config ) {
35
		parent::__construct( $config );
36
37
		$this->set_method( self::METHOD_HTML_FORM );
38
39
		$this->client = new Client();
40
		$this->client->set_website_key( $config->get_website_key() );
41
		$this->client->set_secret_key( $config->get_secret_key() );
42
		$this->client->set_excluded_services( $config->get_excluded_services() );
43
		$this->client->set_invoice_number( $config->get_invoice_number() );
44
		$this->client->set_push_url( add_query_arg( 'buckaroo_push', '', home_url( '/' ) ) );
45
46
		if ( self::MODE_TEST === $config->mode ) {
47
			$this->client->set_payment_server_url( Client::GATEWAY_TEST_URL );
48
		}
49
	}
50
51
	/**
52
	 * Get issuers.
53
	 *
54
	 * @since 1.2.4
55
	 * @see Pronamic_WP_Pay_Gateway::get_issuers()
56
	 */
57
	public function get_issuers() {
58
		$groups = array();
59
60
		try {
61
			$result = $this->client->get_issuers();
62
63
			$groups[] = array(
64
				'options' => $result,
65
			);
66
		} catch ( \Exception $e ) {
67
			$this->error = new \WP_Error( 'buckaroo', $e->getMessage() );
68
		}
69
70
		return $groups;
71
	}
72
73
	/**
74
	 * Get supported payment methods
75
	 *
76
	 * @see Pronamic_WP_Pay_Gateway::get_supported_payment_methods()
77
	 */
78
	public function get_supported_payment_methods() {
79
		return array(
80
			Core_PaymentMethods::BANK_TRANSFER,
81
			Core_PaymentMethods::BANCONTACT,
82
			Core_PaymentMethods::CREDIT_CARD,
83
			Core_PaymentMethods::GIROPAY,
84
			Core_PaymentMethods::IDEAL,
85
			Core_PaymentMethods::PAYPAL,
86
			Core_PaymentMethods::SOFORT,
87
		);
88
	}
89
90
	/**
91
	 * Start
92
	 *
93
	 * @param Payment $payment Payment.
94
	 *
95
	 * @see Core_Gateway::start()
96
	 */
97
	public function start( Payment $payment ) {
98
		/**
99
		 * Authentication.
100
		 * 
101
		 * The HMAC SHA256 is calculated over a concatenated string (as raw data/binary/bytes) of the following values: WebsiteKey, requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String. See the next table for more information about these values. Please note: the Base64 hash should be a string of 44 characters. If yours is longer, it is probably in hexadecimal format.
102
		 *
103
		 * @link https://dev.buckaroo.nl/Apis/Description/json
104
		 */
105
		$website_key         = $this->config->website_key;
106
		$request_http_method = 'POST';
107
		$request_uri         = 'testcheckout.buckaroo.nl/json/datarequest/specifications';
108
		$request_timestamp   = \strval( \time() );
109
		$nonce               = \wp_generate_password( 32 );
110
		$request_content     = '{
111
  "Services": [
112
    {
113
      "Name": "idealqr",
114
	  "Version": 1
115
	}
116
  ]
117
}';
118
119
		$data = \implode(
120
			'',
121
			array(
122
				$website_key,
123
				$request_http_method,
124
				$request_uri,
125
				$request_timestamp,
126
				$nonce,
127
				\base64_encode( \md5( $request_content, true ) ),
128
			)
129
		);
130
131
		$authorization = 'hmac ' . $this->config->website_key . ':' . hash_hmac( 'sha256', $data, $this->config->secret_key ) . ':' . $nonce . ':' . $request_timestamp;
0 ignored issues
show
Unused Code introduced by
The assignment to $authorization is dead and can be removed.
Loading history...
132
133
$postArray = array(
134
    "Currency" => "EUR",
135
    "AmountDebit" => 10.00,
136
    "Invoice" => "testinvoice 123",
137
    "Services" => array(
138
        "ServiceList" => array(
139
            array(
140
                "Action" => "Pay",
141
                "Name" => "ideal",
142
                "Parameters" => array(
143
                    array(
144
                        "Name" => "issuer",
145
                        "Value" => "ABNANL2A"
146
                    )
147
                )
148
            )
149
        )
150
    )
151
);
152
153
154
$post = json_encode($postArray);
155
156
echo $post . '<br><br>';
157
158
$md5  = md5($post, true);
159
$post = base64_encode($md5);
160
161
echo '<b>MD5 from json</b> ' . $md5 . '<br><br>';
162
echo '<b>base64 from MD5</b> ' . $post . '<br><br>';
163
164
$websiteKey = $this->config->website_key;
165
$test = 'testcheckout.buckaroo.nl/json/Transaction';
166
$uri        = strtolower(urlencode($test));
167
$nonce      = 'nonce_' . rand(0000000, 9999999);
168
$time       = time();
169
170
$hmac       = $websiteKey . 'POST' . $uri . $time . $nonce . $post;
171
$s          = hash_hmac('sha256', $hmac, $this->config->secret_key, true);
172
$hmac       = base64_encode($s);
173
174
$authorization = ("hmac " . $this->config->website_key . ':' . $hmac . ':' . $nonce . ':' . $time);
175
var_dump($this->config );
0 ignored issues
show
Security Debugging Code introduced by
var_dump($this->config) looks like debug code. Are you sure you do not want to remove it?
Loading history...
176
var_dump($authorization );
177
		$test = \Pronamic\WordPress\Http\Facades\Http::request(
178
			'https://' . $test,
179
			array(
180
				'method'  => $request_http_method,
181
				'headers' => array(
182
					'Authorization' => $authorization,
183
					'Content-Type'  => 'application/json',
184
				),
185
				'body'    => \json_encode($postArray),
186
			)
187
		);
188
189
		var_dump( $test );
190
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
191
192
		$payment->set_action_url( $this->client->get_payment_server_url() );
0 ignored issues
show
Unused Code introduced by
$payment->set_action_url...t_payment_server_url()) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
193
	}
194
195
	/**
196
	 * Get output HTML
197
	 *
198
	 * @param Payment $payment Payment.
199
	 *
200
	 * @return array
201
	 *
202
	 * @see     Core_Gateway::get_output_html()
203
	 * @since   1.1.1
204
	 * @version 2.0.4
205
	 */
206
	public function get_output_fields( Payment $payment ) {
207
		$payment_method = $payment->get_method();
208
209
		switch ( $payment_method ) {
210
			case Core_PaymentMethods::IDEAL:
211
				$this->client->set_payment_method( PaymentMethods::IDEAL );
212
				$this->client->set_ideal_issuer( $payment->get_issuer() );
213
214
				break;
215
			case Core_PaymentMethods::CREDIT_CARD:
216
				$this->client->add_requested_service( PaymentMethods::AMERICAN_EXPRESS );
217
				$this->client->add_requested_service( PaymentMethods::MAESTRO );
218
				$this->client->add_requested_service( PaymentMethods::MASTERCARD );
219
				$this->client->add_requested_service( PaymentMethods::VISA );
220
221
				break;
222
			case Core_PaymentMethods::BANK_TRANSFER:
223
			case Core_PaymentMethods::BANCONTACT:
224
			case Core_PaymentMethods::MISTER_CASH:
0 ignored issues
show
Deprecated Code introduced by
The constant Pronamic\WordPress\Pay\C...entMethods::MISTER_CASH has been deprecated: "Bancontact/Mister Cash" was renamed to just "Bancontact". ( Ignorable by Annotation )

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

224
			case /** @scrutinizer ignore-deprecated */ Core_PaymentMethods::MISTER_CASH:

This class constant has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
225
			case Core_PaymentMethods::GIROPAY:
226
			case Core_PaymentMethods::PAYPAL:
227
			case Core_PaymentMethods::SOFORT:
228
				$this->client->set_payment_method( PaymentMethods::transform( (string) $payment_method ) );
229
230
				break;
231
			default:
232
				if ( '0' !== $payment_method ) {
233
					// Leap of faith if the WordPress payment method could not transform to a Buckaroo method?
234
					$this->client->set_payment_method( $payment_method );
235
				}
236
237
				break;
238
		}
239
240
		// Locale.
241
		$culture = null;
242
243
		$customer = $payment->get_customer();
244
245
		if ( null !== $customer ) {
246
			$locale = $customer->get_locale();
247
248
			// Buckaroo uses 'nl-NL' instead of 'nl_NL'.
249
			if ( ! empty( $locale ) ) {
250
				$culture = str_replace( '_', '-', $locale );
251
			}
252
		}
253
254
		$this->client->set_payment_id( (string) $payment->get_id() );
255
		$this->client->set_culture( $culture );
256
		$this->client->set_currency( $payment->get_total_amount()->get_currency()->get_alphabetic_code() );
257
		$this->client->set_description( $payment->get_description() );
258
		$this->client->set_amount( $payment->get_total_amount()->get_value() );
259
		$this->client->set_invoice_number( Util::get_invoice_number( (string) $this->client->get_invoice_number(), $payment ) );
260
		$this->client->set_return_url( $payment->get_return_url() );
261
		$this->client->set_return_cancel_url( $payment->get_return_url() );
262
		$this->client->set_return_error_url( $payment->get_return_url() );
263
		$this->client->set_return_reject_url( $payment->get_return_url() );
264
265
		return $this->client->get_fields();
266
	}
267
268
	/**
269
	 * Update status of the specified payment
270
	 *
271
	 * @param Payment $payment Payment.
272
	 */
273
	public function update_status( Payment $payment ) {
274
		$method = Server::get( 'REQUEST_METHOD', FILTER_SANITIZE_STRING );
275
276
		$data = array();
277
278
		switch ( $method ) {
279
			case 'GET':
280
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended
281
				$data = $_GET;
282
283
				break;
284
			case 'POST':
285
				// phpcs:ignore WordPress.Security.NonceVerification.Missing
286
				$data = $_POST;
287
288
				break;
289
		}
290
291
		$data = Util::urldecode( $data );
292
293
		$data = stripslashes_deep( $data );
294
295
		$data = $this->client->verify_request( $data );
296
297
		if ( false === $data ) {
0 ignored issues
show
introduced by
The condition false === $data is always true.
Loading history...
298
			return;
299
		}
300
301
		$payment->set_transaction_id( (string) $data[ Parameters::PAYMENT ] );
302
		$payment->set_status( Statuses::transform( (string) $data[ Parameters::STATUS_CODE ] ) );
303
304
		// Consumer bank details.
305
		$consumer_bank_details = $payment->get_consumer_bank_details();
306
307
		if ( null === $consumer_bank_details ) {
308
			$consumer_bank_details = new BankAccountDetails();
309
310
			$payment->set_consumer_bank_details( $consumer_bank_details );
311
		}
312
313
		if ( \array_key_exists( Parameters::SERVICE_IDEAL_CONSUMER_NAME, $data ) ) {
314
			$consumer_bank_details->set_name( (string) $data[ Parameters::SERVICE_IDEAL_CONSUMER_NAME ] );
315
		}
316
317
		if ( \array_key_exists( Parameters::SERVICE_IDEAL_CONSUMER_IBAN, $data ) ) {
318
			$consumer_bank_details->set_iban( (string) $data[ Parameters::SERVICE_IDEAL_CONSUMER_IBAN ] );
319
		}
320
321
		if ( \array_key_exists( Parameters::SERVICE_IDEAL_CONSUMER_BIC, $data ) ) {
322
			$consumer_bank_details->set_bic( (string) $data[ Parameters::SERVICE_IDEAL_CONSUMER_BIC ] );
323
		}
324
325
		$labels = array(
326
			Parameters::PAYMENT                       => __( 'Payment', 'pronamic_ideal' ),
327
			Parameters::PAYMENT_METHOD                => __( 'Payment Method', 'pronamic_ideal' ),
328
			Parameters::STATUS_CODE                   => __( 'Status Code', 'pronamic_ideal' ),
329
			Parameters::STATUS_CODE_DETAIL            => __( 'Status Code Detail', 'pronamic_ideal' ),
330
			Parameters::STATUS_MESSAGE                => __( 'Status Message', 'pronamic_ideal' ),
331
			Parameters::INVOICE_NUMBER                => __( 'Invoice Number', 'pronamic_ideal' ),
332
			Parameters::AMOUNT                        => __( 'Amount', 'pronamic_ideal' ),
333
			Parameters::CURRENCY                      => __( 'Currency', 'pronamic_ideal' ),
334
			Parameters::TIMESTAMP                     => __( 'Timestamp', 'pronamic_ideal' ),
335
			Parameters::SERVICE_IDEAL_CONSUMER_ISSUER => __( 'Service iDEAL Consumer Issuer', 'pronamic_ideal' ),
336
			Parameters::SERVICE_IDEAL_CONSUMER_NAME   => __( 'Service iDEAL Consumer Name', 'pronamic_ideal' ),
337
			Parameters::SERVICE_IDEAL_CONSUMER_IBAN   => __( 'Service iDEAL Consumer IBAN', 'pronamic_ideal' ),
338
			Parameters::SERVICE_IDEAL_CONSUMER_BIC    => __( 'Service iDEAL Consumer BIC', 'pronamic_ideal' ),
339
			Parameters::TRANSACTIONS                  => __( 'Transactions', 'pronamic_ideal' ),
340
		);
341
342
		$note = '';
343
344
		$note .= '<p>';
345
		$note .= __( 'Buckaroo data:', 'pronamic_ideal' );
346
		$note .= '</p>';
347
348
		$note .= '<dl>';
349
350
		foreach ( $labels as $key => $label ) {
351
			if ( ! isset( $data[ $key ] ) ) {
352
				continue;
353
			}
354
355
			$note .= sprintf(
356
				'<dt>%s</dt><dd>%s</dd>',
357
				esc_html( $label ),
358
				esc_html( (string) $data[ $key ] )
359
			);
360
		}
361
362
		$note .= '</dl>';
363
364
		$payment->add_note( $note );
365
	}
366
}
367