WP Webhooks / Blog / Integrations

Sending WooCommerce Orders to Salesforce as Real Order Records

WooCommerce to Salesforce Orders: price book entries, one Composite call for account, order and lines, and the HTTP 200 that hides a rollback.

9 min 2026-11-24
#salesforce#woocommerce#api

TL;DR: A WooCommerce order can land in Salesforce as a real Order with Order Products, written by one API call. Three details decide whether it works in production: price book entries, a single Composite request, and reading the response body instead of the status code.

  • Every Order Product needs a PricebookEntryId. Orders without price books exist only in orgs with a B2B Commerce licence.
  • An Order must be created in Draft. Activation is a separate update, and while activating, Status is the only field you can change.
  • One POST /composite upserts the Account, creates the Order and creates its lines. Up to 25 subrequests count as one API call.
  • With allOrNone: true a failure rolls everything back, and Salesforce still answers HTTP 200. Check every subresponse.
  • A unique external ID on the Order turns a repeated delivery into a harmless duplicate-value error.

/ Ready-made

Is there a ready-made WooCommerce Salesforce connector?

Yes, several. The most installed on WordPress.org is Integration for WooCommerce and Salesforce by CRM Perks: feeds that map order, product and user fields to any Salesforce object, a primary key for updates instead of duplicates, a log with resend, and email alerts on errors. Order items, custom fields, product sync and bulk export are in its premium version. Its free tier is a good fit for "every order becomes a Lead or a Contact", and it takes minutes to set up.

A direct API integration is worth it when you want Salesforce's own Order object with real Order Products, so revenue reports and the account's order history line up with the store. It also helps when the same order has to go to Salesforce and to other systems, such as an ERP or a warehouse, with one delivery log covering all of them. The rest of this article is that build.

/ Object

Should a WooCommerce order become an Opportunity or an Order?

An Order, in most stores. An Opportunity tracks a deal that might close. A paid web order already closed, so putting it in the pipeline inflates win rates and forecasts. The Order object records what was sold, to which Account, and at what price.

It also asks more of you than a Contact does. The required fields on create:

ObjectFieldRule from the object reference
OrderAccountIdRequired. Can only change while the order is Draft
OrderEffectiveDateThe order start date
OrderStatusMust map to the Draft status category when you create the order
OrderPricebook2IdRequired. The price book the order lines come from
OrderItemOrderIdRequired. The parent order
OrderItemPricebookEntryIdRequired on create. It can’t be changed in an update
OrderItemQuantity, UnitPriceUnits sold and the price per unit

The Orders feature also has to be switched on in the org's Order Settings before the API will accept any of this. Ask the Salesforce admin first, because it changes what sales users see too.

/ Price books

Where does the PricebookEntryId come from?

From a mapping you keep. The OrderItem reference is blunt about it: PricebookEntryId is "Required. ID of the associated PricebookEntry. Specify this field when creating OrderItem records. It can't be changed in an update." The one way around it is orders without price books, which the Order reference limits to orgs with the B2B Commerce, B2B Commerce Starter, Growth or Plus packages.

So each WooCommerce product needs to know the id of its entry in the price book your web orders use. For a catalogue of a few dozen products, store that id as product meta, for example _sf_pbe_id, filled once from a Salesforce report or a SOQL export. For a large or fast-changing catalogue, sync products first and write the id back. Either way, the order delivery should read an id that already exists, never look it up per order.

Send UnitPrice from WooCommerce, not the list price. The price book entry fixes which product it is. The price the customer paid, after coupons, is in the order: line total divided by quantity.

FIG 01 — One Composite call writes the account, the order and its lines, or nothing at all

/ One call

How do you write the account, order and lines in one request?

With the Composite resource. It runs a series of REST requests in one call, the output of one can feed the next, and "the entire series of requests counts as a single call toward your API limits." Each subrequest gets a referenceId, and later ones refer to its result as @{refAccount.id}, in the URL or the body.

JSON — POST /services/data/v64.0/composite

{
  "allOrNone": true,
  "compositeRequest": [
    {
      "method": "PATCH",
      "url": "/services/data/v64.0/sobjects/Account/WC_Customer_Key__c/WC-C-5f2b9c",
      "referenceId": "refAccount",
      "body": { "Name": "Ana Lee", "BillingCity": "Gdańsk" }
    },
    {
      "method": "POST",
      "url": "/services/data/v64.0/sobjects/Order",
      "referenceId": "refOrder",
      "body": {
        "AccountId": "@{refAccount.id}",
        "EffectiveDate": "2026-11-24",
        "Status": "Draft",
        "Pricebook2Id": "01s5g00000AbCdE",
        "WC_Order_Id__c": "1234"
      }
    },
    {
      "method": "POST",
      "url": "/services/data/v64.0/composite/sobjects",
      "referenceId": "refLines",
      "body": {
        "allOrNone": true,
        "records": [
          { "attributes": { "type": "OrderItem" }, "OrderId": "@{refOrder.id}",
            "PricebookEntryId": "01u5g00000XyZ12", "Quantity": 2, "UnitPrice": 25.00 }
        ]
      }
    }
  ]
}

Three things make that body work:

  • The Account is an upsert. PATCH on an external ID field creates the account the first time and updates it after that. Since API version 46.0 an update answers 200 with the record id (201 on create), so @{refAccount.id} resolves on both paths. Versions 45.0 and older answered 204 with no body, which would break the reference.
  • The lines go in one sObject Collections request. Up to 200 records per request, and a Composite call allows up to 5 Collections or query subrequests among its 25.
  • The key is yours. WC_Customer_Key__c is a hash of the billing email, so guest orders from the same person land on one Account.

The arithmetic is why this matters. Separate calls cost 3 per order: at 2,000 orders a day that is 2,000 × 3 = 6,000 calls from the org's shared daily allowance. One Composite call per order costs 2,000. The WordPress Salesforce integration article covers how that allowance is shared and how the client credentials token is obtained.

/ The 200

Why can a failed Salesforce composite request return HTTP 200?

Because that is the documented contract. The Composite request body reference says that with allOrNone true, "the entire composite request is rolled back. The top-level request returns HTTP 200 and includes responses for each subrequest." With it false, the requests that do not depend on the failure still run, and the answer is 200 again.

That breaks any sender that equates 2xx with delivered. A product with no price book entry, a closed price book, or a required field the admin added last week all produce an order that is not in Salesforce, a log line that says success, and no retry. The fix is to read compositeResponse: every item carries its own httpStatusCode and body, and anything at 300 or above means the order did not land.

A rolled-back Composite request still answers HTTP 200. If your sender only reads the status code, failed orders are logged as delivered. — the line most WooCommerce to Salesforce code gets wrong

/ Retries

How do you stop a retry from creating a second Salesforce order?

Create the Order with a field Salesforce will refuse to duplicate. Make WC_Order_Id__c a custom text field marked External ID and Unique. Now replay the bad case: Salesforce commits the order, the response is lost to a timeout, and the sender retries. The retry's order insert fails on the unique value (a DUPLICATE_VALUE error), allOrNone rolls the retry back, and the order written the first time stays the only one.

Why not upsert the Order as well? Because of its lines. PricebookEntryId cannot change in an update, and lines created by a repeated request would add to the order rather than replace it. A plain insert that the unique field turns away is simpler and safe.

Keep activation out of the same request. Per the Order reference, an order is created in Draft, and while you activate it, "the Status field is the only field you can update". AccountId can only change while the order is Draft. Activate in a separate step, a Salesforce flow on new web orders or a second call after the first succeeded, so a retry never sends a full order body to an activated record.

ConcernCRM Perks (free tier)Webhook Actions + Composite body
SetupFeeds and field mapping in wp-admin, no codeOne webhook, a pre-dispatch snippet that builds the body, a token filter
Order ProductsPremium versionBuilt by the snippet, one PricebookEntryId per product
Which orders are sentFilters and rules in the feedAny condition on the order payload
Salesforce answers 5xx or 429Logged, resend from the logRetried with backoff, 5 attempts by default
Rolled-back composite (HTTP 200)Not applicable, it sends single-object requestsLogged as success. A post-dispatch snippet has to read compositeResponse and flag it
Same order to other systemsSalesforce onlyOther webhooks on the same trigger, each with its own log
try_it

Seeing it run beats reading about it. The live preview boots a throwaway WordPress with Webhook Actions already installed and demo deliveries sitting in the log — no signup, nothing left on your machine afterwards.

/ Code

What does the code look like?

Two small pieces. First, a snippet that turns the order into the Composite body. It runs before each delivery on a webhook triggered by woocommerce_order_status_processing, which passes the order id and the order, and it must return the array to send:

PHP — pre-dispatch snippet: WooCommerce order to Composite body

$order = $payload['args'][1];                         // the order's data
$v     = '/services/data/v64.0';

$lines = [];
foreach ( $order['line_items'] as $item ) {
    $lines[] = [
        'attributes'       => [ 'type' => 'OrderItem' ],
        'OrderId'          => '@{refOrder.id}',
        'PricebookEntryId' => get_post_meta( $item['product_id'], '_sf_pbe_id', true ),
        'Quantity'         => $item['quantity'],
        'UnitPrice'        => round( $item['total'] / $item['quantity'], 2 ),  // after coupons
    ];
}

$b   = $order['billing'];
$key = 'WC-C-' . substr( md5( strtolower( trim( $b['email'] ) ) ), 0, 16 );

return [
    'allOrNone'        => true,
    'compositeRequest' => [
        [ 'method' => 'PATCH', 'url' => "$v/sobjects/Account/WC_Customer_Key__c/$key",
          'referenceId' => 'refAccount',
          'body' => [ 'Name' => $b['company'] ?: trim( $b['first_name'] . ' ' . $b['last_name'] ) ] ],
        [ 'method' => 'POST', 'url' => "$v/sobjects/Order", 'referenceId' => 'refOrder',
          'body' => [
              'AccountId'      => '@{refAccount.id}',
              'EffectiveDate'  => gmdate( 'Y-m-d' ),
              'Status'         => 'Draft',
              'Pricebook2Id'   => '01s5g00000AbCdE',  // your web price book id
              'WC_Order_Id__c' => (string) $order['id'],
          ] ],
        [ 'method' => 'POST', 'url' => "$v/composite/sobjects", 'referenceId' => 'refLines',
          'body' => [ 'allOrNone' => true, 'records' => $lines ] ],
    ],
];

Second, a snippet that runs after each delivery and catches the rolled-back 200. It cannot change the delivery's status, so it writes what happened where the shop manager will see it, on the order itself:

PHP — post-dispatch snippet: flag a rolled-back composite on the order

$res    = json_decode( $responseBody, true );
$errors = [];
foreach ( $res['compositeResponse'] ?? [] as $sub ) {
    if ( $sub['httpStatusCode'] >= 300 ) {
        $errors[] = $sub['referenceId'] . ': ' . wp_json_encode( $sub['body'] );
    }
}
$already = $errors && str_contains( implode( ' ', $errors ), 'DUPLICATE_VALUE' );
if ( $errors && ! $already ) {
    $wc = wc_get_order( $originalPayload['args'][0] );
    $wc && $wc->add_order_note( 'Salesforce rejected this order: ' . implode( ' | ', $errors ) );
}

The access token comes from the client credentials flow, cached in a transient and added in the fswa_headers filter for this one webhook. Cache it for less than the session timeout set for the integration user, because a 401 is not one of the responses that gets retried.

/ Exposure

What does Salesforce not protect you from?

Silent rollbacks. Covered above, and worth repeating: a 200 from /composite says nothing about your order.

A price book that drifts. A product added in WooCommerce without a _sf_pbe_id, or a price book entry an admin deactivates, rolls back every order that contains it. Add a check to your product publish routine, and look at the order notes weekly.

An integration user with too much access. The client credentials flow runs as a named user and inherits every permission it has. Give it create and edit on Account, Order and Order Product, and nothing else.

Your share of the org's allowance. The daily API limit belongs to the whole org. A retry loop on a broken body does not fail alone. That is why 4xx answers should never be retried, and why the retry policy article separates the two. For the same pattern with an ERP on the other end, see WooCommerce to NetSuite. Gravity Forms to Salesforce covers form entries and Leads.

/Footnotes
¹ Order and OrderItem fields from the Salesforce Object Reference; Composite limits and the allOrNone behaviour from the REST API Developer Guide; upsert status codes from Insert or Update (Upsert) a Record Using an External ID. All read 2026-11-24.
² CRM Perks feature split from the plugin's WordPress.org page, version 1.8.2.
FAQ

Things engineers always ask.

Don't see yours? Open an issue on GitHub or check the full reference in the API docs.

Should WooCommerce orders become Salesforce Opportunities or Orders? +
Orders, when the record should say what was sold. An Order needs an Account, a start date, a Draft status and a price book, and each Order Product needs a price book entry, a quantity and a unit price. Opportunities suit a sales pipeline; a paid web order has already closed, so most stores that report revenue in Salesforce want Orders.
Why does every Salesforce Order Product need a PricebookEntryId? +
Salesforce prices order products through price books. OrderItem.PricebookEntryId is required on create and cannot be changed later. Orders without price books exist, but only in orgs with a B2B Commerce licence. Everyone else maps each WooCommerce product to the id of its entry in the order price book.
How many Salesforce API calls does one WooCommerce order cost? +
One, if you use the Composite resource. Up to 25 subrequests run in a single call, and the whole series counts as one call toward the org API limits. Upserting the account, creating the order and creating its lines separately would cost three calls per order.
Why does a failed Salesforce composite request return HTTP 200? +
With allOrNone set to true, Salesforce rolls back every subrequest when one fails, but the top-level response is still HTTP 200, with a result for each subrequest. A sender that only checks the status code records the order as delivered. Read each httpStatusCode in compositeResponse instead.
How do you stop a retry from creating a second Salesforce order? +
Store the WooCommerce order number in a custom field marked External ID and Unique, and create the Order with it. If a retry repeats a request that already succeeded, the order insert fails on the duplicate value, allOrNone rolls the whole request back, and nothing is written twice.
Ready

Your next automation is
one sentence away.

$ wp plugin install flowsystems-webhook-actions --activate