blob: 3dabb689c658f8536460699bf1ecfa1f9f5b9878 [file] [log] [blame]
swissChilif0cbdc32023-01-05 17:21:38 -05001<?php
2/***
3 * Class WC_REST_Stripe_Tokens_Controller
4 */
5
6defined( 'ABSPATH' ) || exit;
7
8/**
9 * REST controller for tokens.
10 */
11class WC_REST_Stripe_Tokens_Controller extends WC_Stripe_REST_Base_Controller {
12
13 /**
14 * Endpoint path.
15 */
16 protected $rest_base = 'wc_stripe/tokens';
17
18 /**
19 * Register REST API routes for Stripe tokens.
20 */
21 public function register_routes() {
22 register_rest_route(
23 $this->namespace,
24 // For more info on Stripe tokens, see the following:
25 // https://stripe.com/docs/api/tokens/object
26 '/' . $this->rest_base . '/(?P<token_id>[a-z]{3}_[a-zA-Z0-9]{24})',
27 [
28 'methods' => WP_REST_Server::READABLE,
29 'callback' => [ $this, 'get_token' ],
30 'permission_callback' => [ $this, 'check_permission' ],
31 ]
32 );
33 }
34
35 /**
36 * Retrieve a Stripe token, given a secret-key and token_id.
37 *
38 * @param WP_REST_Request $request Request object.
39 *
40 * @return WP_REST_Response Response object.
41 */
42 public function get_token( $request ) {
43 $token_id = $request->get_param( 'token_id' );
44 $secret_key = $request->get_header( 'X-WCStripe-Secret-Key' );
45
46 try {
47 WC_Stripe_API::set_secret_key( $secret_key );
48 $response = WC_Stripe_API::request( [], "tokens/$token_id", 'GET' );
49
50 if ( ! empty( $response->error ) ) {
51 return new WP_REST_Response( [ 'result' => 'bad_request' ], 400 );
52 }
53 } catch ( Exception $exception ) {
54 return new WP_REST_Response( [ 'result' => 'bad_request' ], 400 );
55 }
56
57 return new WP_REST_Response( $response, 200 );
58 }
59}