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
<?php
defined( 'ABSPATH' ) || exit();
use \PaymentPlugins\WC_Braintree_Constants as Constants;
class WC_Braintree_Controller_Local_Payment extends WC_Braintree_Controller_Frontend {
protected $namespace = 'local-payment/';
public function register_routes() {
register_rest_route(
$this->rest_uri(), 'payment-data', array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'save_payment_data' ),
'permission_callback' => '__return_true',
)
);
register_rest_route( $this->rest_uri(), 'payment/complete', array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'complete_payment' ),
'permission_callback' => '__return_true'
) );
}
public function save_payment_data( $request ) {
try {
$order = wc_get_order( $request->get_param( 'order_id' ) );
if ( ! hash_equals( $order->get_order_key(), $request['order_key'] ) ) {
throw new Exception( __( 'Invalid order key', 'woo-payment-gateway' ) );
}
$order->update_meta_data( Constants::PAYMENT_ID, $request->get_param( 'payment_id' ) );
$order->save();
return rest_ensure_response( array( 'redirect_url' => $order->get_checkout_order_received_url() ) );
} catch ( Exception $e ) {
return new WP_Error( 'order-error', $e->getMessage(), array( 'status' => 200 ) );
}
}
public function complete_payment( $request ) {
try {
$order = wc_get_order( absint( WC()->session->get( 'order_awaiting_payment' ) ) );
$gateway = WC()->payment_gateways()->payment_gateways()[ $order->get_payment_method() ];
$result = $gateway->process_payment( $order->get_id() );
if ( isset( $result['result'] ) && $result['result'] === 'success' ) {
return rest_ensure_response( $result );
} else {
return rest_ensure_response( array( 'result' => 'failure', 'messages' => $this->get_error_messages() ) );
}
} catch ( Exception $e ) {
return new WP_Error( 'payment-error', $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
}