WC_REST_Paypal_Buttons_Controller::cancel_payment
Cancel a PayPal payment. This is used to move the woocommerce order back to a draft status.
Method of the class: WC_REST_Paypal_Buttons_Controller{}
No Hooks.
Returns
WP_REST_Response. The response object.
Usage
$WC_REST_Paypal_Buttons_Controller = new WC_REST_Paypal_Buttons_Controller(); $WC_REST_Paypal_Buttons_Controller->cancel_payment( $request );
- $request(WP_REST_Request) (required)
- The request object.
WC_REST_Paypal_Buttons_Controller::cancel_payment() WC REST Paypal Buttons Controller::cancel payment code WC 10.3.6
public function cancel_payment( WP_REST_Request $request ) {
$data = $request->get_json_params();
$order_id = isset( $data['order_id'] ) ? absint( $data['order_id'] ) : 0;
$paypal_order_id = isset( $data['paypal_order_id'] ) ? wc_clean( $data['paypal_order_id'] ) : '';
if ( ! $order_id || '' === $paypal_order_id ) {
return new WP_REST_Response( array( 'error' => 'Invalid request' ), 400 );
}
$order = wc_get_order( $order_id );
if ( ! $order ) {
return new WP_REST_Response( array( 'error' => 'Order not found' ), 404 );
}
// Verify order by checking the PayPal order ID.
$paypal_order_id_from_meta = $order->get_meta( '_paypal_order_id' );
if ( $paypal_order_id_from_meta !== $paypal_order_id ) {
return new WP_REST_Response( array( 'error' => 'Invalid PayPal order' ), 404 );
}
// If order is already in draft status, do nothing and return success.
if ( $order->has_status( OrderStatus::CHECKOUT_DRAFT ) ) {
return new WP_REST_Response( array( 'success' => true ), 200 );
}
// If order is not pending, return an error.
if ( ! $order->has_status( OrderStatus::PENDING ) ) {
return new WP_REST_Response( array( 'error' => 'Order is not pending' ), 409 );
}
$order->update_status( OrderStatus::CHECKOUT_DRAFT );
$order->save();
return new WP_REST_Response( array( 'success' => true ), 200 );
}