Time estimate for integration
August 7, 2025 · AI Conversations
They have an inhouse CRM called Insight.
Currently they have to raise every order in Insight manually.
What they require is an automation to push orders into Insight using the API info provided.
[https://api.4d.4u2c.app/openapi/swagger/index.html?urls.primaryName=Herbst%20Insight%20Customer%20Web%20API%20v2](https://api.4d.4u2c.app/openapi/swagger/index.html?urls.primaryName=Herbst%20Insight%20Customer%20Web%20API%20v2)
So I think what I would like to be able to do then is that when someone places an order on the website that It would check the email address against the customers in insight,
If we have that email address in the file, we could use that to post an order & payment to that account in insight.
If we don’t have that email address, then we can post an order to a guest account or web order account in Insight & we would need to send the delivery address in some notes or somewhere else.
There are lots of these endpoints that we can do other things with but the goal now would be to come up with a system for getting the web orders visible on Insight as soon as possible. I don’t know if this is something that post live or polls every so often.
—
## 🧠 **Scope Recap**
**Goal**: Automate the process of pushing WooCommerce orders into Herbst Insight CRM via their API.
### ✳️ Key Requirements:
1. On WooCommerce order placement:
– Look up customer in Insight via email.
– If found → create order + payment for that customer.
– If not found → post to “Guest” or “Web Order” account, and include delivery address.
2. Integration could be either **real-time (hooked into WooCommerce checkout)** or **scheduled polling** (e.g., every 5 minutes).
—
## 📋 Estimated Time Breakdown
| Task | Estimated Time |
|—————————————————————————————|—————-|
| **1. Review Herbst Insight API and authentication (e.g. token setup)** | 1.5 – 2 hrs |
| **2. WooCommerce hook for order placement (e.g., `woocommerce_thankyou` or webhook)** | 1 hr |
| **3. Fetch customer from Insight by email** | 1.5 hrs |
| **4. Conditional logic: customer match vs guest account fallback** | 1 hr |
| **5. Create order in Insight (API payload mapping)** | 2 – 3 hrs |
| **6. Post payment to Insight (linked to the order)** | 1.5 – 2 hrs |
| **7. Error handling and logging (for missing fields, API errors, etc.)** | 1.5 hrs |
| **8. Admin setting (for fallback account ID, API key, debug toggle, etc.)** | 2 hrs |
| **9. Test end-to-end (email match, guest, partial data, payment, etc.)** | 2 – 3 hrs |
| **10. Documentation (usage + config)** | 1 hr |
**🔁 Optional (if polling approach is preferred instead of real-time):**
| Task | Estimated Time |
|———————————————————————-|—————-|
| Build a CRON-based polling system to fetch new WooCommerce orders | +1.5 hrs |
| Avoid duplicate pushes via order meta/check flag | +1 hr |
—
## ⏳ **Total Estimate**
– **Real-time WooCommerce integration**: **14–17 hours**
– **With polling system (CRON)**: **+2.5 hours** → **~17–20 hours total**
—
## ⚙️ Technical Notes
– **Authentication**: Confirm whether the Insight API uses bearer tokens, basic auth, or other.
– **Fallback account**: You’ll need a hardcoded Insight account ID or email for guest orders.
– **WooCommerce versioning**: Ensure you're hooking into correct action depending on the version (e.g., order status changes or checkout complete).
—
## ✅ Recommendations
– Use real-time integration (`woocommerce_thankyou`) unless there's a business reason to poll.
– Store Insight sync status in `postmeta` to prevent duplicate pushes.
– Add admin options under a custom settings page or WooCommerce tab.
—
Let me know if you want this broken into **milestones** or if you'd like a **fixed quote document** prepared.
please gve me step and code
Below is a **step-by-step guide with CodeIgniter code snippets**, assuming you're using **CodeIgniter 3 or 4** (let me know which one if you need tailored code).
—
## ✅ OVERVIEW
When an order is placed in your CodeIgniter website:
1. Look up the customer's email in Insight via their API.
2. If the email is found → push the order and payment to that Insight customer.
3. If not found → push the order to a fallback “Guest” account and attach delivery address.
4. Log results/errors.
—
## 🔧 STEP 1: Setup Configuration (API URL, token)
Create a config file: `application/config/insight_api.php`
<?php
defined('BASEPATH') or exit('No direct script access allowed');
$config['insight_api_base_url'] = 'https://api.4d.4u2c.app/v2/';
$config['insight_api_key'] = 'YOUR_BEARER_TOKEN_HERE'; // from Herbst Insight API settings
$config['insight_guest_account_id'] = 'GUEST_ACCOUNT_ID'; // fallback account ID
—
## 📦 STEP 2: Create Insight API Library
Create: `application/libraries/Insight_api.php`
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Insight_api
{
protected $CI;
protected $base_url;
protected $token;
protected $guest_account_id;
public function __construct()
{
$this->CI =& get_instance();
$this->CI->config->load('insight_api');
$this->base_url = $this->CI->config->item('insight_api_base_url');
$this->token = $this->CI->config->item('insight_api_key');
$this->guest_account_id = $this->CI->config->item('insight_guest_account_id');
}
private function request($endpoint, $method = 'GET', $data = [])
{
$headers = [
'Authorization: Bearer ' . $this->token,
'Content-Type: application/json'
];
$url = $this->base_url . $endpoint;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($error) return ['error' => $error];
return json_decode($response, true);
}
public function getCustomerByEmail($email)
{
$result = $this->request("Customers/FindByEmail?email={$email}", 'GET');
return isset($result['id']) ? $result : null;
}
public function createOrder($customerId, $orderData)
{
return $this->request("Orders/Create?customerId={$customerId}", 'POST', $orderData);
}
public function postPayment($orderId, $paymentData)
{
return $this->request("Payments/Create?orderId={$orderId}", 'POST', $paymentData);
}
public function getGuestAccountId()
{
return $this->guest_account_id;
}
}
—
## 📦 STEP 3: Hook into Order Placement (Example Controller Logic)
In your `OrderController` or wherever the order is finalized:
public function place_order()
{
$this->load->library('Insight_api');
// Assume you have these from form or order object
$email = $this->input->post('email');
$order_items = $this->input->post('items'); // array of items
$total_amount = $this->input->post('total');
$address = $this->input->post('delivery_address');
// 1. Find customer in Insight
$insight_customer = $this->insight_api->getCustomerByEmail($email);
$customer_id = $insight_customer ? $insight_customer['id'] : $this->insight_api->getGuestAccountId();
// 2. Prepare order payload
$order_payload = [
'OrderLines' => array_map(function($item) {
return [
'ProductCode' => $item['sku'],
'Quantity' => $item['qty'],
'UnitPrice' => $item['price']
];
}, $order_items),
'Notes' => $insight_customer ? '' : 'Delivery Address: ' . $address,
'OrderDate' => date('Y-m-d'),
'DueDate' => date('Y-m-d', strtotime('+7 days'))
];
$order_response = $this->insight_api->createOrder($customer_id, $order_payload);
if (isset($order_response['id'])) {
$order_id = $order_response['id'];
// 3. Post payment
$payment_response = $this->insight_api->postPayment($order_id, [
'Amount' => $total_amount,
'PaymentDate' => date('Y-m-d'),
'Notes' => 'Online order'
]);
if (isset($payment_response['id'])) {
log_message('info', "Order and payment synced to Insight. Order ID: $order_id");
} else {
log_message('error', "Order pushed but payment failed: " . json_encode($payment_response));
}
} else {
log_message('error', "Order sync failed: " . json_encode($order_response));
}
}
—
## ✅ STEP 4: (Optional) CRON-Based Polling Alternative
Instead of real-time, you could create a CRON job that fetches pending orders and pushes them in bulk. You'd mark synced orders in DB using a flag like `synced_to_insight = 1`.
—
## 🧪 STEP 5: Test With:
– **Registered Customer**: Email found in Insight → normal sync.
– **Guest Checkout**: Not found → fallback logic, delivery address in notes.
– **Error scenarios**: API timeout, invalid SKU, missing price → log all.
—
## 🗃️ Logs
Use `log_message('info', …)` and `log_message('error', …)` throughout to store logs in `application/logs/`.
—
## 🧠 Final Notes
– Adjust endpoint paths depending on actual Insight API naming (check Swagger link).
– You may need to create a real product sync later (optional phase).
– Secure the API token in `.env` or use CI's encryption helpers.
—
Would you like me to create a full CodeIgniter 4-ready version or a database schema to go along with this as well?
—
## 🔑 How to Get Herbst Insight API Keys (Bearer Token)
### ✅ **Option 1: Herbst Insight Dashboard (Preferred)**
If you have admin access to the Herbst Insight backend:
1. **Login** to your Herbst Insight system (usually a local or cloud URL like `https://yourcompany.4d.4u2c.app`).
2. Go to **Settings** or **Developer / API Access** section.
3. Look for **API Tokens** or **Client Credentials** section.
4. Generate a new token:
– Give it a name like `Website Integration`.
– Set proper **scopes or permissions** (Orders, Payments, Customers).
– Save and copy the **Bearer Token** shown once.
> ⚠️ Note: Some systems may show it only **once**, so save it securely.
—
### ✅ **Option 2: Ask Herbst Support**
If you don’t have admin access:
– Email Herbst Insight support (or your internal team managing it) and ask:
> “Can you please provide an API access token (Bearer token) for the Herbst Insight Customer Web API v2, with access to the following endpoints: Customers, Orders, Payments? This will be used for automating web orders from our CodeIgniter website.”
—
### ✅ **Option 3: OAuth2 Authentication (if required)**
If the Swagger docs show an **OAuth2 flow**, then you may need:
– **Client ID**
– **Client Secret**
– **Token Endpoint** (e.g., `POST https://api.4d.4u2c.app/oauth/token`)
– Then use:
// Get token with client credentials
$data = [
'grant_type' => 'client_credentials',
'client_id' => 'YOUR_CLIENT_ID',
'client_secret' => 'YOUR_CLIENT_SECRET'
];
$response = $this->requestToken($data); // Use CURL or Guzzle to post this
$token = $response['access_token'];
Check in Swagger UI under the **Authorize** button — if it shows `client_credentials` or `password` type, it’s OAuth2.
—
## 🔐 Once You Have the Token
– Store it in your CodeIgniter config file:
$config['insight_api_key'] = 'your_actual_bearer_token_here';
Or in your `.env` file:
INSIGHT_API_KEY=your_actual_bearer_token_here
And retrieve in PHP:
$this->config->item('insight_api_key');
// OR
getenv('INSIGHT_API_KEY')
—
If you're unsure what the Swagger API uses for auth, send me a screenshot of the **Authorize popup** or the `securitySchemes` section in Swagger JSON and I can confirm the correct flow.