How To Execute Woocommerce Payment Programmatically

How to trigger Woocommerce payment process like checkout but it should process in the background

To trigger Woocommerce payment process, need to call “process_payment” method. Here is an example to process Woocommerce payment programmatically.

global $woocommerce;
$address = array(
      'first_name' => 'Test',
      'last_name'  => 'Test',
      'company'    => 'Test',
      'email'      => 'test@softwarehtec.com',
      'phone'      => '00-00-0000',
      'address_1'  => '0 test st',
      'address_2'  => '',
      'city'       => 'Test',
      'state'      => 'NY',
      'postcode'   => '10010',
      'country'    => 'US'
);


$order = wc_create_order();
$order->add_product( get_product('1'), 1); 
$order->set_address( $address, 'billing' );
$order->set_address( $address, 'shipping' );
$order->calculate_totals();

update_post_meta( $order->id, '_payment_method', 'paypal' );
update_post_meta( $order->id, '_payment_method_title', 'PayPal' );

WC()->session->order_awaiting_payment = $order->id;

$available_gateways = WC()->payment_gateways->get_available_payment_gateways();
$result = $available_gateways[ 'paypal' ]->process_payment( $order->id );

if ( $result['result'] == 'success' ) {
    $result = apply_filters( 'woocommerce_payment_successful_result', $result, $order->id );
    wp_redirect( $result['redirect'] );
    exit;
}


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments