Using the WooCommerce REST API v2, I'm successfully creating an order in a pending, unpaid state.
I can see that I can set the order.payment_details.paid
field to true
which will create the order in a completed state and send out a completed order email, but it doesn't actually process the payment.
What is the proper way using the REST API v2 to create an order and have WooCommerce process the payment using the payment gateway?
Or do I need to add a plugin hook to the API on the server side? (I think so)
Here's what I've tried
curl -X POST https://example.com/wc-api/v2/orders \
-u consumer_key:consumer_secret \
-H "Content-Type: application/json" \
-d '{
"order": {
"customer_id": 2,
"payment_details": {
"method_id": "da_big_bank",
"method_title": "StackOverflow Money Laundering, Inc.",
"paid":true
},
"line_items": [
{
"product_id": 341,
"quantity": 1
}
]
}
}'
which, as I said, generates an order in completed state, but doesn't actually process any money with my gateway (which is not "StackOverflow Money Laundering, Inc." and is a legitimate gateway that does work when using our WooCommerce site)
As helgatheviking concurred, there currently isn't a way to process payment of an order with the WooCommerce REST API.
I ended up writing a hook into the
woocommerce_api_create_order
filter that immediately processes the order for payment when the order is created. If the processing fails, then the errors are added to theorder->post->post_excerpt
field which makes it appear asorder->note
in the JSON response.For this to work, I also had to extend the payment gateway so that its
process_payment()
method would accept a$user_id
as an input. This is because it's coded out of the box to operate on the currently logged in user, which, in my case, and probably most cases, is the system user that the REST client logs in as, not the actual user making a purchase.The other benefit of extending the gateway turned out to be that now errors can be returned rather than written to
wc_add_notice()
. Since this is a REST service, nothing ever sees the output ofwc_add_notice()