I'm having trouble passing a Stripe Customer ID directly to a WC_Order object. I have tried passing it through the payment gateway metadata via the set_payment_method function however nothing I try seems to work.
I am trying to complete an entire order programmatically in order to migrate another system over to WordPress. We're trying to do this with WC Subscription objects which inherit from WC_Order.
Let me know if there is a good solution to this. Thank you!
Here's a bit of code to demonstrate what I'm basically trying to do:
$order = wc_create_order(['customer_id' => $user_id]);
$user = get_user_by( 'ID', $user_id );
$order->add_product( $product, 1 );
$payment_gateways = WC()->payment_gateways->payment_gateways();
$order->set_payment_method($payment_gateways['stripe'], [
'customer_id' => 'cus_XXXXXXXXXXXXXX' // this part right here, doesnt seem to work
]);
// $order->set_payment_method($payment_gateways['stripe'], [
// 'stripe_customer_id' => 'cus_XXXXXXXXXXXXXX' // also doesnt seem to work
// ]);
The ending result was that the order could not be completed and transactions do not come through to our Stripe account either.
Documentation on the set_payment_method function is very limited and provides no additional information on supported data that can be passed.
WC Subscriptions API Reference
My Answer:
> Unfortunately, passing a Stripe Customer ID directly to a WC_Order object is not supported out of the box in WooCommerce. However, you can achieve this by using custom metadata or custom fields.
One way to do this is to save the Stripe Customer ID as a custom field on the order object. You can do this by using the update_meta_data() method on the order object. Here's an example code snippet:
php
// Create a new order
$order = wc_create_order(['customer_id' => $customer_id]);
// Save the Stripe Customer ID as a custom field on the order
$order->update_meta_data('stripe_customer_id', $stripe_customer_id);
// Save the order
$order->save();
You can then retrieve the Stripe Customer ID from the order object using the get_meta() method:
php
// Get the Stripe Customer ID from the order
$stripe_customer_id = $order->get_meta('stripe_customer_id');
This way, you can store and retrieve the Stripe Customer ID associated with the order. Remember to adjust the code according to your specific requirements and implementation.
Rate this post
3 of 5 based on 1047 votesComments