woocommerce-paypal-payments/modules/ppcp-button/src/Endpoint/class-dataclientidendpoint.php

93 lines
2 KiB
PHP
Raw Normal View History

<?php
2020-08-31 11:12:46 +03:00
/**
* The Data Client ID endpoint.
*
* @package Inpsyde\PayPalCommerce\Button\Endpoint
*/
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\Button\Endpoint;
use Inpsyde\PayPalCommerce\ApiClient\Endpoint\IdentityToken;
2020-08-26 08:06:14 +03:00
use Inpsyde\PayPalCommerce\ApiClient\Exception\PayPalApiException;
use Inpsyde\PayPalCommerce\ApiClient\Exception\RuntimeException;
2020-08-31 11:12:46 +03:00
/**
* Class DataClientIdEndpoint
*/
2020-08-27 11:08:36 +03:00
class DataClientIdEndpoint implements EndpointInterface {
2020-09-11 13:38:02 +03:00
const ENDPOINT = 'ppc-data-client-id';
2020-08-27 11:08:36 +03:00
2020-08-31 11:12:46 +03:00
/**
* The Request Data Helper.
*
* @var RequestData
*/
private $request_data;
/**
* The Identity Token.
*
* @var IdentityToken
*/
private $identity_token;
/**
* DataClientIdEndpoint constructor.
*
* @param RequestData $request_data The Request Data Helper.
* @param IdentityToken $identity_token The Identity Token.
*/
2020-08-27 11:08:36 +03:00
public function __construct(
2020-08-31 11:12:46 +03:00
RequestData $request_data,
IdentityToken $identity_token
2020-08-27 11:08:36 +03:00
) {
2020-08-31 11:12:46 +03:00
$this->request_data = $request_data;
$this->identity_token = $identity_token;
2020-08-27 11:08:36 +03:00
}
2020-08-31 11:12:46 +03:00
/**
* Returns the nonce.
*
* @return string
*/
2020-08-27 11:08:36 +03:00
public static function nonce(): string {
return self::ENDPOINT;
}
2020-08-31 11:12:46 +03:00
/**
* Handles the request.
*
* @return bool
*/
public function handle_request(): bool {
2020-08-27 11:08:36 +03:00
try {
2020-08-31 11:12:46 +03:00
$this->request_data->read_request( $this->nonce() );
$user_id = get_current_user_id();
2020-09-01 09:00:45 +03:00
$token = $this->identity_token->generate_for_customer( $user_id );
2020-08-27 11:08:36 +03:00
wp_send_json(
array(
'token' => $token->token(),
2020-09-01 09:00:45 +03:00
'expiration' => $token->expiration_timestamp(),
2020-08-27 11:08:36 +03:00
'user' => get_current_user_id(),
)
);
return true;
} catch ( RuntimeException $error ) {
wp_send_json_error(
array(
'name' => is_a( $error, PayPalApiException::class ) ? $error->name() : '',
'message' => $error->getMessage(),
'code' => $error->getCode(),
'details' => is_a( $error, PayPalApiException::class ) ? $error->details() : array(),
)
);
return false;
}
}
}