Skip to content

Instantly share code, notes, and snippets.

@ajayghaghretiya
Created December 28, 2017 12:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajayghaghretiya/172a6962567b0228889daed4a6b88fcb to your computer and use it in GitHub Desktop.
Save ajayghaghretiya/172a6962567b0228889daed4a6b88fcb to your computer and use it in GitHub Desktop.
Do Payment via WooCommerce REST API for Stripe
add_action( 'rest_api_init', 'custom_api_endpoints' );
function custom_api_endpoints() {
/**
* Handle Payment Method request.
*/
register_rest_route( 'wc/v2', 'payment', array(
'methods' => 'POST',
'callback' => 'custom_payment_endpoint_handler',
) );
}
function custom_payment_endpoint_handler() {
$response = array();
$payment_method = sanitize_text_field( $_POST['payment_method'] );
$order_id = sanitize_text_field( $_POST['order_id'] );
$payment_token = sanitize_text_field( $_POST['payment_token'] );
$error = new WP_Error();
if ( empty( $payment_method ) ) {
$error->add( 400, __( 'Payment Method is required.', 'woocommerce' ), array( 'status' => 400 ) );
return custom_error_code( $error );
}
if ( empty( $order_id ) ) {
$error->add( 400, __( 'Order ID is required.', 'woocommerce' ), array( 'status' => 400 ) );
return custom_error_code( $error );
}
if ( empty( $payment_token ) ) {
$error->add( 400, __( 'Payment Token is required.', 'woocommerce' ), array( 'status' => 400 ) );
return custom_error_code( $error );
}
if ( $payment_method === "stripe" ) {
$stripe_object = new WC_Gateway_Stripe();
$_POST['stripe_token'] = $payment_token;
$_POST['wc-stripe-payment-token'] = $payment_token;
$payment_result = $stripe_object->process_payment( $order_id );
if ( $payment_result['result'] === "success" ) {
$response['code'] = 200;
$response['message'] = __( "Your Payment Successfully", "payment-method" );
} else {
$response['code'] = 401;
$response['message'] = __( "Please enter valid card details", "payment-method" );
}
} else {
$response['code'] = 401;
$response['message'] = __( "Please select valid payment method", "payment-method" );
}
return $response;
}
@Kmadhvi
Copy link

Kmadhvi commented Feb 27, 2023

@ajayghaghretiya How to get payment token from orders if the order is generated from the api? Can you please help regarding that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment