=== Gold Standard Analytics for WooCommerce ===
Tags: woocommerce, coa, product testing, certificate of analysis, laboratory testing
Requires at least: 6.5
Tested up to: 7.1
Requires PHP: 7.4
Stable tag: 1.8.1
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Order laboratory tests from WooCommerce, track status, and automatically attach verified certificates of analysis (COAs) to the right products.

== Description ==

Gold Standard Analytics for WooCommerce connects product testing, laboratory order status, and verified certificate of analysis PDFs to the correct WooCommerce products and variations.

Order lab testing for your products from WordPress, pay on GSA's hosted page, print the shipping label and packing slip, and have each certificate attach to the product it covers when the lab publishes it.

= WooCommerce laboratory testing workflow =

* Synchronize available GSA categories, compounds, tests, bundles, and sample requirements.
* Map an exact product or variation to its testing configuration and optional lot or batch.
* Order testing from WooCommerce > Order Lab Testing: pick one or more products, choose tests or a package from the live GSA catalog, see the itemized quote, and place one order. Or start from a product's GSA Testing tab with "Order testing for this product".
* Pay by Mercury invoice (card, ACH or wire) or Stripe checkout on GSA's own page. No card details are entered or stored in WordPress.
* Follow each order's status, payment, inbound label and tracking in one list, and print a packing slip.
* Create separately quoted GSA testing orders from selected WooCommerce order lines.
* Receive signed status and COA events, with hourly polling of order statuses and new certificates as a fallback.
* Store authorized COA PDFs locally in the WordPress Media Library.
* Certificates from orders placed on goldstandardanalytics.com attach on their own when their compound and lot match exactly one product. Anything else waits in a short list on the settings screen, where you attach it with one click.
* Optionally display published COAs on the exact product or variation page.
* Link every displayed GSA certificate to its own page at goldstandardanalytics.com/coa/{accession}, with link text that names the compound and accession, so customers can check the document at the issuing laboratory. Private certificates are shown without a link, because they only open with the key printed on the PDF.
* Publish a store-wide COA library with the [gsa_coa_library] shortcode — one indexable Lab Results page listing every certificate with its product, PDF, and public-registry verification link.
* Describe each certificate as schema.org Certification, credited to the laboratory that issued it, and add it to WooCommerce's Product markup as hasCertification.
* Send customers verifiable lab results two ways: add public-COA verification links to your own store's order emails (no customer data leaves your store), and/or offer a checkout opt-in for customers to receive the certificate directly from Gold Standard Analytics (their email is shared with GSA only when they opt in, with the consent timestamp recorded).
* Full activity log of testing orders, shipping labels, and customer COA emails (including consent), viewable in the admin and exportable as CSV. Email addresses are stored only as a one-way hash.
* Attach certificates from ANY laboratory: upload a COA PDF on the product edit screen with the laboratory's name, accession, compound, and lot — no GSA account required. Manual certificates join the same product panel and [gsa_coa_library] page, clearly labeled with their laboratory.
* Automatically tag products that hold a published COA (configurable tag label, e.g. "Lab Tested"); the tag is removed if the last certificate is retracted.
* Choose where the COA panel renders (product summary, product tab, or manual placement with the new [gsa_coa_panel] shortcode) and customize its heading.
* Export the store's testing orders and full COA library as CSV from the settings screen. Exports download directly to your browser and are not sent anywhere.
* Optional, merchant-controlled attribution ("Independently tested by Gold Standard Analytics") and a site-wide verification footer badge. These link to goldstandardanalytics.com, render only after you enable them on the settings screen, can be set to rel="nofollow", and can be turned off at any time.

= Accurate COA matching =

Before publishing a COA, the plugin verifies the GSA order, expected compound, exact product or variation, and any configured lot or batch. A mismatch remains private for manual review instead of being attached to the wrong product.

A certificate from an order placed outside the store attaches automatically only when both the certificate and exactly one product carry the same compound and lot. A compound alone is never enough, because stores also test other brands' products.

= Safety and reliability =

* Activation makes no remote request. A manager must save a scoped GSA live API key and deliberately select **Connect and register webhook**.
* Credentials use dedicated non-autoloaded options and are never rendered back after saving; `GSA_WC_API_KEY` in `wp-config.php` is also supported.
* Quote-first order creation uses a deterministic line-item `clientReference` and API idempotency key.
* Order access is HPOS-compatible and uses WooCommerce APIs only.
* Signed, timestamped raw-body HMAC verification and durable event-ID deduplication protect webhook processing.
* Webhooks acknowledge quickly, then use a durable WP-Cron queue with bounded retries. Hourly polling supplies a recovery path.
* Optional WooCommerce operational logging is redacted and disabled by default.
* The plugin adds no telemetry, advertising, tracking pixels, or remote frontend assets.

WooCommerce must be installed and active. Use of the laboratory integration requires a Gold Standard Analytics customer account and scoped live API key.

== External service ==

This plugin connects to the Gold Standard Analytics Agent API at `https://www.goldstandardanalytics.com/api/v1/agent` only after an administrator explicitly connects it.

Depending on the action, it sends the API key, selected laboratory category/compound/tests, turnaround and raw-data preference, optional administrator-entered lot/batch, a site-derived client reference, WooCommerce order/line/product/variation identifiers and product names in sample notes, the store's host name, and quantity. GSA uses this data to quote and create laboratory submissions, return statuses, payment links, shipping labels, tracking and authorized results, and deliver signed webhooks.

Reads the plugin makes with the key: the testing catalog, the account's order readiness (terms accepted, addresses on file, key permissions), order status, the shipping label, and the newest published results (hourly, to catch a missed webhook).

When an administrator selects **Connect and register webhook**, the plugin also sends the complete public webhook URL generated for the current site, normally `https://YOUR-WORDPRESS-SITE.example/wp-json/gold-standard-analytics/v1/webhook`, and requests subscriptions to `order.created`, `order.status_changed`, `order.cancelled`, `coa.published`, and `coa.retracted`. This lets GSA deliver those signed events to the store. The URL contains the store's public scheme, host, any WordPress subdirectory, and the `/wp-json/gold-standard-analytics/v1/webhook` REST path.

For a matched published result, the plugin directly follows the short-lived HTTPS COA URL returned by the authorized API; that file URL may be hosted on GSA-controlled Supabase Storage. The PDF is then stored on the WordPress site.

Use requires an active GSA customer account, accepted service terms, configured addresses, and a scoped live API key.

Optional features send data only after you turn them on:

* Merchant directory: your store name, store URL and chosen categories, when you tick "List my store".
* Customer COA emails from GSA: a customer's email address, order number, certificate accession numbers and consent time, only for customers who tick the checkout box.
* Product sync (WooCommerce > GSA Product Sync, separate product-only key): published products enabled for testing, with product and variation IDs, names, SKUs, product URLs, variation attributes, selected GSA category/compound/tests and entered lot numbers. It sends no customer order, address or payment data, and creates no order or charge.

* Service: https://www.goldstandardanalytics.com/
* Privacy Policy: https://www.goldstandardanalytics.com/privacy
* Terms: https://www.goldstandardanalytics.com/terms

The fixed production base URL can be changed by a site developer with the `gsa_wc_api_base_url` filter. Doing so changes the external service destination and should be reviewed by the store owner.

== Installation ==

1. Install and activate WooCommerce.
2. Upload the plugin directory to `/wp-content/plugins/` or install the release ZIP in Plugins > Add New.
3. Activate **Gold Standard Analytics for WooCommerce**.
4. Open WooCommerce > Gold Standard Analytics.
5. Save a `gsa_live_` API key with the permissions listed under the key field. Saving settings makes no network request unless you ask to be listed in the merchant directory.
6. Select **Connect and register webhook**. A public HTTPS WordPress REST URL is required.
7. Synchronize the catalog, then configure the **GSA Testing** panel on products or exact variations.
8. Order testing from WooCommerce > Order Lab Testing, or from selected line items on a WooCommerce order.

WP-Cron must be able to run. On low-traffic or production sites, configure a real scheduler to request `wp-cron.php` regularly.

== Frequently Asked Questions ==

= Does activation contact GSA? =

No. Activation creates local non-autoloaded options and schedules local cron hooks. Only the explicit Connect action registers or rotates a webhook and synchronizes the catalog.

= Can I order testing from WordPress? =

Yes. WooCommerce > Order Lab Testing lets you pick products, tests or a package, see the quote, and place the order. You pay on GSA's hosted page by invoice or card, then print the label and packing slip. The key needs the permissions listed on the settings screen, and your GSA account needs accepted terms and an address on file; the ordering screen tells you if anything is missing.

= I ordered on goldstandardanalytics.com. Will the certificate still show up? =

Yes, if the product in WordPress has the same compound and lot as the sample you sent, and no other product does. Otherwise it appears under "Certificates waiting for a product" on the settings screen, with the matching products suggested, and attaches when you choose one. Setting the lot on the product later also works: the hourly check picks it up.

= Is a product saved as a GSA order? =

No. The product screen only saves testing configuration. Orders are created only when a manager places one from the ordering screen or from selected WooCommerce order lines.

= Is the product SKU used as a laboratory lot? =

No. Lot/batch is an optional dedicated field. If configured, it is sent and must match the published result exactly before the COA is attached.

= Where is the API key stored? =

By default it is held in a dedicated non-autoloaded WordPress option, masked in the UI, and never rendered back. For stronger operational control, define `GSA_WC_API_KEY` in `wp-config.php`; WordPress core does not provide a general-purpose secret vault.

= What happens if webhook delivery is delayed? =

Signed events are queued locally and retried by WP-Cron. An hourly authenticated status poll provides a fallback for mapped orders. Event IDs are retained for 30 days to deduplicate at-least-once delivery.

= Can the plugin automatically attach a Certificate of Analysis to a WooCommerce product? =

Yes, after GSA publishes an authorized result. The plugin verifies the originating GSA order, compound, and any configured lot or batch before copying the COA PDF into the WordPress Media Library and displaying it on the exact product or variation. A mismatch stays private for manual review.

= Does the plugin support product variations and WooCommerce HPOS? =

Yes. Each product or exact variation can have its own testing mapping, and order access uses WooCommerce APIs compatible with High-Performance Order Storage (HPOS).

= Is the WooCommerce plugin free? =

The plugin download is free and GPL-licensed. An active Gold Standard Analytics customer account is required, and laboratory testing is quoted and billed separately.

= What happens on uninstall? =

Uninstall removes plugin options (including product sync and directory state), credentials, caches, mappings, product/order/item metadata, queued webhook records, scheduled hooks, and only those Media Library PDFs the plugin downloaded from GSA. It does not contact GSA or delete remote laboratory orders. Deactivation alone preserves data.

== Privacy ==

The plugin proposes privacy-policy text under Settings > Privacy. Store owners are responsible for reviewing that text, their legal basis, retention obligations, and disclosures. Local order mappings and COAs may contain identifiers related to commercial laboratory submissions. Optional logs exclude bodies, credentials, and customer PII.

== Screenshots ==

1. Connect a scoped GSA API key, register signed webhooks, control storefront COA visibility, and synchronize the testing catalog.
2. Map an exact WooCommerce product or variation to its GSA category, compound, tests, turnaround, and optional lot or batch.
3. Create laboratory testing orders from selected WooCommerce order lines and see each line's GSA order and current status.
4. Display only matched, authorized COA PDFs on the correct product or variation page.

== Changelog ==

= 1.8.1 =
* Lot matching never publishes a certificate the customer kept private; it waits for you instead.
* Stores that saved their settings before 1.8.0 keep lot matching off until they turn it on, so nothing attaches to a product they did not choose.
* Certificates from console orders placed under 1.7.x attach as soon as their order is mapped, even when a webhook or a manual check reaches them first.

= 1.8.0 =
* Fixed: ordering from WordPress. The quote showed no price, the Pay button never appeared, peptide quotes were rejected, an order without a lot was rejected, the crypto option could never succeed, and the shipping label was never found. The console now sends and reads what the GSA API actually uses.
* New: order several products in one GSA order, with tests or a package chosen from the catalog, an itemized quote, payment by invoice or card, and status, tracking, label, packing slip and certificates in one list. "Order testing for this product" on the product's GSA Testing tab.
* New: certificates from orders placed on goldstandardanalytics.com attach when compound and lot match exactly one product; others wait in a list with one-click attach.
* New: hourly check for certificates a webhook missed, and console orders now update their status and attach their certificates.
* Certificate links name the compound and accession, private certificates are no longer linked to a page they cannot open, and WooCommerce's Product markup now lists each certificate as hasCertification.
* Fixed: uploading another lab's COA on the product screen silently did nothing; creating orders from a WooCommerce order showed an error after succeeding.
* Packing slip ship-to address corrected to 5151 Mitchelldale St A10, Houston, TX 77092.
* Product sync screen is now translatable; uninstall also removes product sync, directory and waiting-certificate data.

= 1.7.0 =
* Fixed: saving the settings screen could silently switch off the ordering console, the COA links in your order emails, and the checkout opt-in. All settings now save together, with a test that keeps the form and the saver in step.
* New: ask to be listed in the public Gold Standard merchant directory. Sends only your store name, address and chosen testing categories; reviewed before it appears; untick to withdraw immediately.

= 1.6.0 =
* Certificates from any laboratory now emit schema.org Certification markup, credited to the issuing laboratory — your other-lab COAs become machine-readable too. Only GSA-issued certificates link to the GSA registry.
* Each certificate gets its own anchor on the product panel and the library page, so you can link a customer to one certificate.
* Attribution links are strictly opt-in and never pre-selected, and the optional site-wide footer badge is marked sponsored.

= 1.5.0 =
* The customer COA opt-in now works on stores using the WooCommerce Checkout block, registered as an additional checkout field (WooCommerce 8.9 or newer). Stores on the classic checkout are unchanged, and the opt-in never renders twice.
* Declares compatibility with cart and checkout blocks, so WooCommerce no longer reports the plugin as incompatible.
* Fixed: "Verify" links now open the certificate on goldstandardanalytics.com instead of an empty lookup form.

= 1.4.0 =
* Add opt-in, product-only synchronization to the GSA account and sample picker. Separate scoped key, resumable batches, safe removal reconciliation, and connection status.
* Align the runtime version with the plugin release.

= 1.3.1 =
* Security hardening from a full audit: order console now uses a deterministic idempotency key (a double-submit can no longer create two billable orders); testing-order and shipping-label flows no longer rely on wp_safe_redirect to external hosts; the shipping-label action verifies the order belongs to this store.
* CSV exports (COA library, testing orders, activity log) neutralize spreadsheet formula-injection prefixes.
* API-key hint now reveals only the last 4 characters; clearing the activity log now requires full admin (manage_options); uninstall removes the activity log and console-order options; the audit log no longer floods with per-email events and holds more history.


= 1.3.0 =
* In-WordPress testing-order console (WooCommerce → Order Lab Testing): product picker, live quote, order, and hosted-checkout payment (Mercury / Stripe / crypto) — no card data handled by WordPress — plus shipping-label retrieval and a locally generated packing slip.
* Customer COA emails: store-sent verification links added to your own order emails, and an opt-in for GSA to email the certificate from its own domain (consent captured and logged; customer email shared with GSA only on opt-in).
* Audit log of orders, labels, and customer emails, viewable in admin and exportable as CSV; email addresses stored only as a one-way hash.
* PHP 8.4 compatibility: explicit fputcsv arguments.


= 1.2.0 =
* Manual certificates from any laboratory: upload COA PDFs per product with lab name, accession, compound, and lot. Clearly labeled; only GSA-issued certificates carry public-registry verification links and Certification JSON-LD.
* Auto-tagging: optionally tag products holding a published COA (custom label), removed on retraction of the last certificate.
* Panel placement (summary / tab / manual) with the new [gsa_coa_panel] shortcode, and a customizable panel heading.
* Merchant-side CSV exports of testing orders and the COA library (capability- and nonce-protected, downloads only to the store admin).


= 1.1.0 =
* Every displayed COA now links to its permanent page in the Gold Standard Analytics public registry and to a pre-filled verification lookup.
* New [gsa_coa_library] shortcode: a store-wide, indexable Lab Results page of every published certificate.
* New schema.org Certification JSON-LD on COA surfaces citing the issuing laboratory and public certificate URL.
* New optional test-panel explainer links per COA (merchant-controlled).
* New merchant-controlled attribution line and site-wide verification footer badge, with an optional rel="nofollow"; both are consent-gated on the settings screen and disabled until saved.


= 1.0.1 =
* Improves the WooCommerce product-testing field layout for current admin styles.
* Adds merchant-focused directory copy, search terms, FAQs, and screenshot captions.

= 1.0.0 =
* Initial WordPress.org-compatible release.
* Adds intentional connection, catalog sync, exact product/variation configuration, idempotent quote/order creation, signed webhook processing, status polling, and fail-closed local COA publishing.

== Upgrade Notice ==

= 1.8.1 =
Private certificates are never attached by lot match, and lot matching stays off for existing stores until you turn it on.

= 1.8.0 =
Ordering from WordPress works end to end, and certificates from orders placed on goldstandardanalytics.com can attach automatically. Check the key permissions listed on the settings screen.
