1

I have a code that creates a woocommerce order after gravity form submission.

I am needing to set the payment method so that the customer receives the payment instructions. If anyone could see my code and make a suggestion I would appreciate it:

add_action( 'gform_after_submission_56', 'post_to_third_party', 10, 2 );
function post_to_third_party( $entry, $form ) {
    global $woocommerce;
    // use this to find out $entry output
    var_dump($entry);

    // Make sure to add hidden field somewhere in the form with product id and define it here, If you have some other way of defining products in the form you need to make sure product id is returned in the variable below somehow


    // set some variables
$user_id =rgar( $entry, '97' );
$product_id = rgar( $entry, '71' );
$quantity = rgar( $entry, '73' );
$note = rgar( $entry, '53' );

$product = wc_get_product($product_id);

  $address = array(   
         'first_name' => rgar( $entry, '98' ),
         'last_name'  => rgar( $entry, '99' ),
         'company'    => rgar( $entry, '' ),
         'email'      => rgar( $entry, '83' ),
         'phone'      => rgar( $entry, '84' ),
         'address_1'  => rgar( $entry, '88.1' ),
         'address_2'  => rgar( $entry, '88.2' ),
         'city'       => rgar( $entry, '88.3' ),
         'state'      => rgar( $entry, '88.4' ),
         'postcode'   => rgar( $entry, '88.5' ),
         'country'    => rgar( $entry, '88.6' ),
    );

$payment_gateways=rgar( $entry, '106' );
// Create the order object
$order = wc_create_order();
$order->set_customer_id( $user_id );

$order->add_product( wc_get_product($product_id), $quantity, $prices);

foreach ($order->get_items() as $item_key => $item ) {
    $item->add_meta_data( 'Booking Request', $note, true );
}

$order->set_address( $address, 'billing' );
$order->calculate_totals();
$order->update_status( 'on-hold', 'pending', TRUE); 

$order->add_order_note( $note );

    $coupon_code = rgar( $entry, '105' );
    $order->apply_coupon($coupon_code);
      // Set payment gateway
    $order->set_payment_method($payment_gateways);
}``` 

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Check it please - https://stackoverflow.com/questions/31787244/woocommerce-create-an-order-programmatically-and-redirect-to-payment – Dmitry Leiko Feb 24 '20 at 08:45

1 Answers1

4

Try this

$payment_gateways = WC()->payment_gateways->payment_gateways();
$order->set_payment_method($payment_gateways['stripe']);

This is my working code Thanks

rajat.gite
  • 450
  • 2
  • 10
  • I would like to be able to have a form field choose the payment method. Your solution sets it to Stripe. – Jessica Armstrong Feb 24 '20 at 08:03
  • @JessicaArmstrong **WC()->payment_gateways->payment_gateways();** this method will return array of available payment gateway in wordpress. so just make a function and choose your payment method and put into **$order->set_payment_method()** this method. – rajat.gite Feb 24 '20 at 08:31