Process checkout using WC REST API

To process payment for an WooCommerce Order, the workflow goes like the following:

  1. Create an WooCommerce Order
  2. Process Payment for this order, using one of WC_Payment_Gateways
  3. Change order status (default is pending->processing, or to complete if empty order)

IMHO, Step two can be implemented as the following:

  1. Use a front-end lib to tokenize payment info, using frameworks like Stripe or PayPal.
  2. Pass the payment token to your WordPress backend using WP REST API
  3. Let WordPress and WooCommerce process the payment as usual.

You can create a custom REST API endpoint to process payment for your WooCommerce website, add the following code to your code.

add_action( 'rest_api_init', 'wc_rest_payment_endpoints' );
function wc_rest_payment_endpoints() {
    /**
     * Handle Payment Method request.
     */
    register_rest_route( 'wc/v2', 'payment', array(
        'methods'  => 'POST',
        'callback' => 'wc_rest_payment_endpoint_handler',
    ) );
}
function wc_rest_payment_endpoint_handler( $request = null ) {
    $response       = array();
    $parameters     = $request->get_json_params();
    $payment_method = sanitize_text_field( $parameters['payment_method'] );
    $order_id       = sanitize_text_field( $parameters['order_id'] );
    $payment_token  = sanitize_text_field( $parameters['payment_token'] );
    $error          = new WP_Error();

    if ( $payment_method === "stripe" ) {
        $wc_gateway_stripe                = new WC_Gateway_Stripe();
        $_POST['stripe_token']            = $payment_token;
        $payment_result               = $wc_gateway_stripe->process_payment( $order_id );
        if ( $payment_result['result'] === "success" ) {
            $response['code']    = 200;
            $response['message'] = __( "Your Payment was Successful", "wc-rest-payment" );
        } else {
            return new WP_REST_Response( array("c"), 123 );
            $response['code']    = 401;
            $response['message'] = __( "Please enter valid card details", "wc-rest-payment" );
        }
    }  else {
        $response['code'] = 405;
        $response['message'] = __( "Please select an available payment method. Supported payment method can be found at https://wordpress.org/plugins/wc-rest-payment/#description", "wc-rest-payment" );
    }

    return new WP_REST_Response( $response, 123 );
}

If you’re looking for a hassle-free way to do this, you checkout our plugin WC REST Payment.

It supports WooCommerce Gateways including Stripe, PayPal Express, PayPal Standard, Direct Bank Transfer, Cheque, Cash on Delivery.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)