WooCommerce REST Client API – Programmatically get consumer key and secret

I am currently using the client-API to implement a simple user front-end to upload products. The function client->products->create() seems to work fine, how ever I can’t get around one issue.

Every time I upload a product, the vendor is set to the admin user instead of the user that is currently logged in. Is there a way to set the vendor through the API? Has anybody get done this?

Read More

This is the function I created that is called by AJaX when the form is submitted (I left key and website fields empty here on purpose):

function addProduct()
{

  $options = array(
    'debug'           => false,
    'return_as_array' => false,
    'validate_url'    => false,
    'timeout'         => 30,
    'ssl_verify'      => false,
  );

  try {

    $client = new WC_API_Client('', '', '', $options);

    $productName = $_POST["productname"];
    $price = $_POST["price"];
    $discountPrice = $_POST["discountPrice"];
    $description = $_POST["description"];
    $shortDescription = $_POST["shortDescription"];
    $authorId = 5;

    $client->products->create(array('title' => $productName, 'type' => 'simple', 'regular_price' => $price, 'description' => $description));
  } catch (WC_API_Client_Exception $e) {

    echo $e->getMessage() . PHP_EOL;
    echo $e->getCode() . PHP_EOL;

    if ($e instanceof WC_API_Client_HTTP_Exception) {

      print_r($e->get_request());
      print_r($e->get_response());
    }
  }

  echo ("Publicado" . $authorId);

  // Una función AJaX en WordPress debe siempre terminarse con die().
  die();
}

The problem seems to be the consumer key and consumer secret, so, is there a way to programmatically provide the clients with API keys and get these dynamically?

Related posts

3 comments

  1. UPDATE: The method to obtain the consumer key described below will not work; it is no longer possible to get hold of the consumer key from the database once it has been generated. The consumer key stored in this new table is not the same consumer key that is generated in the admin screens and passed out to the end user. It appears to be an SHA256 hashed a version of this key. This is more secure (previously the consumer key and secret stored in wp_usermeta was tantamount to storing clear-text passwords, as anyone with access to that data would be able to log into the API as any of those users), but is a little less convenient. Win some, lose some, but win on security.


    Your new WC_API_Client() will take three parameters before the options: $store_url, $consumer_key and $consumer_secret.

    Any user on the WC shop who is to be used to access the API will need a consumer key or consumer secret. The consumer key will identify which user the API will run as, and it is that user which will be linked to any entities created through the API.

    Until recently, you could get these two pieces of information for a user like this:

    $consumer_key = get_user_meta($user_id, 'woocommerce_api_consumer_key', true);
    $consumer_secret = get_user_meta($user_id, 'woocommerce_api_consumer_secret', true);
    

    Where $user_id is the ID for the user that will be creating items. If you want the current logged in user to be able to create items in their name then that user would need to be given a consumer key and secret, and would need to be in an appropriate WC/WP group to give them permission to do so.

    Note, that if you do this, then the user will also have access to the admin pages for WC to create these items, and not just through the API.

    In later versions of WC, the user meta items have been moved to a separate table: wp_woocommerce_api_keys so you need to look in there instead of in the user meta.

    This will get you the consumer key and secret for a given user ID:

    global $wpdb;
    $key = $wpdb->get_row( $wpdb->prepare("
        SELECT consumer_key, consumer_secret, permissions
        FROM {$wpdb->prefix}woocommerce_api_keys
        WHERE user_id = %d
    ", $user_id), ARRAY_A);
    

    the results being something like this:

    array(3) {
      ["consumer_key"]=>
      string(64) "58043812eee6aa75c80407f8eb9cec025825f138eb7d60118af66cf4b38060fa"
      ["consumer_secret"]=>
      string(43) "cs_1da716412bb9680d8b06b09160872b7e54416799"
      ["permissions"]=>
      string(10) "read_write"
    }
    

    I am, of course, assuming you are using the API to “loop back” to the current site and not accessing a remote site. Using the WC API to create products even on the current site can be very much more convenient than going through the PHP object API.

    I have not yet found any public WC methods to get these details; they are all private and assume only WC needs to know these details.

  2. Yes there is a fine customization that you need to do in your code that is as follows:

    Background information:

    Each users Consumer Key,Consumer Secret Key and read/write permissions (if WooCommerce API Keys are generated for that users) are stored in wordpress’s usermeta table with a meta_keys as ‘woocommerce_api_consumer_key‘, ‘woocommerce_api_consumer_secret‘ and ‘woocommerce_api_key_permissions‘ respectively.

    So you just need to get the current users id first then get that user’s meta value as mention above assign to some variables and send them as a parameter.

  3. I think the problem is generate programmatically the API keys for that customer for witch you want consume the woocommerce service, because the keys ar owned for each users and there aren’t be useful for other users.

    My advice is looking admin source code of woocommerce.

Comments are closed.