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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
<?php
defined( 'ABSPATH' ) || exit();
class WC_Stripe_Controller_Source extends WC_Stripe_Rest_Controller {
protected $namespace = 'source';
public function register_routes() {
register_rest_route( $this->rest_uri(), 'update', array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'update_source' ),
'permission_callback' => '__return_true',
'args' => array(
'source_id' => array( 'required' => true ),
'client_secret' => array( 'required' => true ),
'updates' => array( 'required' => true ),
'gateway_id' => array( 'required', true )
)
) );
register_rest_route(
$this->rest_uri(), 'order/source', array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => array( $this, 'delete_order_source' ),
'permission_callback' => '__return_true',
)
);
}
public function update_source( $request ) {
try {
$payment_method = WC()->payment_gateways()->payment_gateways()[ $request['payment_method'] ];
$source = $payment_method->payment_object->get_gateway()->sources->retrieve( $request['source_id'] );
if ( is_wp_error( $source ) ) {
throw new Exception( __( 'Error updating source.', 'woo-stripe-payment' ) );
}
if ( $source->status !== 'chargeable' ) {
if ( ! hash_equals( $source->client_secret, $request['client_secret'] ) ) {
throw new Exception( __( 'You do not have permission to update this source.', 'woo-stripe-payment' ) );
}
$updates = $request['updates'];
if ( WC()->cart ) {
$updates['amount'] = wc_stripe_add_number_precision( WC()->cart->total, strtoupper( $source->currency ) );
if ( 'stripe_klarna' === $payment_method->id ) {
unset( $updates['source_order']['items'] );
$payment_method->add_klarna_line_items_from_cart( $updates, WC()->cart, strtoupper( $source->currency ) );
}
}
$source = $payment_method->payment_object->get_gateway()->sources->update( $request['source_id'], $updates );
if ( is_wp_error( $source ) ) {
throw new Exception( __( 'Error updating source.', 'woo-stripe-payment' ) );
}
}
return rest_ensure_response( array( 'source' => $source->toArray() ) );
} catch ( Exception $e ) {
return new WP_Error( 'source-error', $e->getMessage(), array( 'status' => 400 ) );
}
}
public function delete_order_source( $request ) {
$order_id = WC()->session->get( 'order_awaiting_payment', null );
if ( $order_id ) {
$order = wc_get_order( $order_id );
$order->delete_meta_data( WC_Stripe_Constants::SOURCE_ID );
$order->save();
}
return rest_ensure_response( array( 'success' => true ) );
}
}