TransWikia.com

Using the WordPress and WooCommerce REST APIs in the same Node app

WordPress Development Asked by ken.dunnington on October 30, 2021

I am writing a small utility app that connects a 3rd party API to a WooCommerce store (actually, it’s multisite, but that’s not really relevant) in order to update customer records. The WooCommerce API docs state that the role property is read-only, but I need to update the roles in order to enable role-based pricing on the front-end. It looks like I can edit roles using the core WordPress API, but I’m writing this app using wc-api-node, which is a node wrapper for WooCommerce’s API. Should I use a separate wrapper and/or method to access the core WordPress API after creating/updating a customer record, or is this something I could handle with the woocommerce_rest_insert_customer action? (Note: I am primarily a node / JS developer, so don’t have a ton of experience with WordPress or WooCommerce.)

I’m also considering the possibility of making my own plugin and using the WordPress cron system to talk to the 3rd party API, but would prefer not to.

One Answer

I thought I'd share my solution for anyone working on a similar problem. I ended up switching to node-wpapi and using REST Autodiscovery to enable use of the WooCommerce & WordPress APIs from a single library. This can be done like so:

const wpapi = require('wpapi')

let wp = new wpapi({
  endpoint: 'http://your.wp.site/wp-json/',
  username: 'user',
  password: 'pass',
  auth: true,
  routes: routes
})
let woo = wp.namespace('wc/v2')

Where routes is a JSON representation of the REST API routes. See here for information on bootstrapping the API wrapper.

I'm then able to use both APIs side-by-side

wp.users()
  .search('foo') // Search by (for example) username
  .param('context', 'edit') // Get additional fields
  .then(result => {
    let user = result[0]
    woo.customers().id(user.id) // Get WooCommerce specific fields
    .then(customer => {
      console.log('woo.customer', customer)
    })
  })

Answered by ken.dunnington on October 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP