1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
<?php
defined( 'ABSPATH' ) || exit();
class WC_Braintree_Controller_Client_Token extends WC_Braintree_Controller_Frontend {
protected $namespace = 'client-token/';
public function register_routes() {
register_rest_route(
$this->rest_uri(),
'create',
array(
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'get_client_token' ),
'permission_callback' => '__return_true',
'args' => array(
'currency' => array(
'required' => true
)
)
),
)
);
}
public function get_client_token( $request ) {
$client_token = $this->generate_client_token( $request['currency'] );
if ( is_wp_error( $client_token ) ) {
return $client_token;
}
return rest_ensure_response( $client_token );
}
private function generate_client_token( $currency ) {
try {
$args = array();
if ( ( $merchant_account = wc_braintree_get_merchant_account( $currency ) ) ) {
$args['merchantAccountId'] = $merchant_account;
}
$gateway = new \Braintree\Gateway( wc_braintree_connection_settings() );
return $gateway->clientToken()->generate( $args );
} catch ( \Braintree\Exception $e ) {
return new WP_Error( 'client-token-error', __( 'Error creating client token.', 'woo-payment-gateway' ), array( 'status' => 400 ) );
}
}
}