### Installation
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Instructions for installing the Statamic Cargo addon using Composer and running the setup command.
```APIDOC
## Installation
Install Cargo via Composer and run the setup command to publish stubs and configure product collections.
```bash
# Install the package
composer require duncanmcclean/statamic-cargo
# Run the installation wizard
php please cargo:install
```
```
--------------------------------
### Install Cargo Addon
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Install the Cargo addon using Composer and run the installation wizard to publish stubs and configure product collections.
```bash
composer require duncanmcclean/statamic-cargo
php please cargo:install
```
--------------------------------
### Implement Buy One Get One Free Discount Type
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Extend the DiscountType class to create custom discount logic. This example calculates a 'Buy One Get One Free' discount for a specific product.
```php
// app/DiscountTypes/BuyOneGetOneFree.php
namespace App\DiscountTypes;
use DuncanMcClean\Cargo\Contracts\Cart\Cart;
use DuncanMcClean\Cargo\Discounts\Types\DiscountType;
use DuncanMcClean\Cargo\Orders\LineItem;
class BuyOneGetOneFree extends DiscountType
{
public function calculate(Cart $cart, LineItem $lineItem): int
{
$eligibleProductId = $this->discount->get('eligible_product');
// Only apply to eligible product
if ($lineItem->product()->id() !== $eligibleProductId) {
return 0;
}
// Calculate free items (every 2nd item is free)
$freeItems = floor($lineItem->quantity / 2);
$unitPrice = $lineItem->unitPrice();
return $freeItems * $unitPrice;
}
public function fieldItems(): array
{
return [
'eligible_product' => [
'display' => __('Eligible Product'),
'type' => 'entries',
'collections' => ['products'],
'max_items' => 1,
'validate' => ['required'],
],
];
}
}
```
--------------------------------
### Run Cargo Install Command
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/installation.md
After Composer finishes, execute this command to publish necessary files, set up the products collection, and complete the installation. This command is part of the Statamic CLI.
```bash
php please cargo:install
```
--------------------------------
### Install Cargo and Remove Simple Commerce
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/migrating-from-simple-commerce.md
Use Composer to remove the old Simple Commerce package and install the new Cargo package.
```bash
composer remove duncanmcclean/simple-commerce
composer require duncanmcclean/statamic-cargo
```
--------------------------------
### Configure Shipping Methods
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/migrating-from-simple-commerce.md
Define shipping methods in the `cargo.php` config file. This example shows how to set up free shipping.
```php
// config/statamic/cargo.php
'shipping' => [
'methods' => [
'free_shipping' => [],
],
],
```
--------------------------------
### Custom Payment Gateway Implementation
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/payment-gateways.md
Example implementation of a custom payment gateway class. This class extends Cargo's PaymentGateway and includes methods for setup, process, capture, cancel, webhook, and refund.
```php
set('amount_refunded', $amount)->save();
}
}
```
--------------------------------
### Install Statamic Cargo using Composer
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/installation.md
Run this command to add the Statamic Cargo addon to your project via Composer. Ensure you have Composer installed and configured.
```bash
composer require duncanmcclean/statamic-cargo
```
--------------------------------
### Get Available Payment Gateways API Endpoint
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/frontend/json-api/endpoints.md
Fetches the available payment gateways for the customer's cart. This includes any data returned by the payment gateway's `setup` method. Payment gateways are returned even for carts with a £0 total, though no `setup` data will be present in that case.
```blade
```
--------------------------------
### Install Tailwind CSS Forms Plugin
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/frontend/checkout/prebuilt.md
Install the @tailwindcss/forms plugin using npm. This is a prerequisite for customizing checkout styles.
```bash
npm install @tailwindcss/forms
```
--------------------------------
### JSON Translation Example
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/knowledge-base/translations.md
Use this format to create translation files. The key is the English text, and the value is your translated text.
```json
{
"Orders": "**Bestellungen**"
}
```
--------------------------------
### Get Available Payment Gateways via API
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Use this GET request to retrieve a list of available payment gateways for the current cart.
```bash
curl -X GET "https://your-store.com/!/cargo/cart/payment-gateways"
```
--------------------------------
### PHP Event Listeners for Cargo Events
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Implement custom logic by listening to various Statamic Cargo events. This example shows how to send emails, log status changes, and manage product stock. Ensure the necessary Mailables and event classes are imported.
```php
// app/Providers/AppServiceProvider.php
use DuncanMcClean\Cargo\Events\CartCreated;
use DuncanMcClean\Cargo\Events\CartSaved;
use DuncanMcClean\Cargo\Events\OrderCreated;
use DuncanMcClean\Cargo\Events\OrderPaymentReceived;
use DuncanMcClean\Cargo\Events\OrderShipped;
use DuncanMcClean\Cargo\Events\OrderStatusUpdated;
use DuncanMcClean\Cargo\Events\ProductNoStockRemaining;
use DuncanMcClean\Cargo\Events\ProductStockLow;
use DuncanMcClean\Cargo\Events\DiscountRedeemed;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Mail;
use App\Mail\OrderConfirmation;
use App\Mail\LowStockAlert;
public function boot(): void
{
// Send order confirmation email when payment is received
Event::listen(OrderPaymentReceived::class, function ($event) {
Mail::to($event->order->customer())
->locale($event->order->site()->shortLocale())
->send(new OrderConfirmation($event->order));
});
// Track order status changes
Event::listen(OrderStatusUpdated::class, function ($event) {
logger()->info('Order status changed', [
'order_id' => $event->order->id(),
'from' => $event->originalStatus->value,
'to' => $event->updatedStatus->value,
]);
});
// Alert when product stock is low
Event::listen(ProductStockLow::class, function ($event) {
Mail::to('inventory@example.com')
->send(new LowStockAlert($event->product));
});
// Handle out of stock products
Event::listen(ProductNoStockRemaining::class, function ($event) {
// $event->product could be Product or ProductVariant
$event->product->set('available', false)->save();
});
// Track discount usage
Event::listen(DiscountRedeemed::class, function ($event) {
logger()->info('Discount redeemed: ' . $event->discount->code());
});
}
```
--------------------------------
### Get Available Shipping Options via API
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Use this GET request to retrieve available shipping options for the cart. This requires a shipping address to be set.
```bash
curl -X GET "https://your-store.com/!/cargo/cart/shipping"
```
--------------------------------
### Retrieve First Product Variant
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/extending/php-apis/products.md
Get the first available product variant and access its properties. Ensure the product has variants defined.
```php
$variant = $product->variantOptions()->first();
$variant->key();
$variant->product();
$variant->name();
$variant->price();
$variant->stock();
$variant->isStockEnabled();
```
--------------------------------
### Create Custom Payment Gateway Integration
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Develop a custom payment gateway by extending the PaymentGateway class. This example shows a 'CustomPay' gateway with methods for setting up payments, processing customer returns, capturing authorized payments, canceling payments, handling webhooks, and processing refunds.
```php
// app/PaymentGateways/CustomPay.php
namespace App\PaymentGateways;
use DuncanMcClean\Cargo\Contracts\Cart\Cart;
use DuncanMcClean\Cargo\Contracts\Orders\Order;
use DuncanMcClean\Cargo\Payments\Gateways\PaymentGateway;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class CustomPay extends PaymentGateway
{
// Called by {{ payment_gateways }} tag - prepare payment
public function setup(Cart $cart): array
{
$payment = CustomPayAPI::createPayment([
'amount' => $cart->grandTotal(),
'currency' => $cart->site()->currency(),
'reference' => $cart->id(),
]);
return [
'payment_id' => $payment->id,
'checkout_url' => $payment->checkout_url,
];
}
// Called when customer returns from payment
public function process(Order $order): void
{
$paymentId = request('payment_id');
$payment = CustomPayAPI::getPayment($paymentId);
if ($payment->status === 'authorized') {
$order->set('payment_id', $paymentId);
}
}
// Capture authorized payment
public function capture(Order $order): void
{
$paymentId = $order->get('payment_id');
CustomPayAPI::capturePayment($paymentId);
}
// Cancel payment when checkout fails
public function cancel(Cart $cart): void
{
$paymentId = request('payment_id');
CustomPayAPI::cancelPayment($paymentId);
}
// Handle webhook notifications
public function webhook(Request $request): Response
{
$payload = $request->all();
// Verify webhook signature
if (!$this->verifySignature($request)) {
return response('Invalid signature', 403);
}
$cart = Cart::find($payload['reference']);
if ($payload['event'] === 'payment.captured') {
$this->createOrderFromCart($cart);
}
return response('OK');
}
// Process refunds from Control Panel
public function refund(Order $order, int $amount): void
{
$paymentId = $order->get('payment_id');
CustomPayAPI::refund($paymentId, $amount);
$order->set('amount_refunded', $amount)->save();
}
}
```
--------------------------------
### Order Total and Status Methods
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/extending/php-apis/orders.md
Methods for getting and setting order totals, and checking order status.
```APIDOC
## GET /api/orders/{order_id}/grandTotal
### Description
Allows you to get the grand total of the order, in pence.
### Method
GET
### Endpoint
/api/orders/{order_id}/grandTotal
### Parameters
#### Path Parameters
- **order_id** (integer) - Required - The ID of the order.
### Response
#### Success Response (200)
- **grand_total** (integer) - The grand total in pence.
#### Response Example
```json
{
"grand_total": 5000
}
```
```
```APIDOC
## POST /api/orders/{order_id}/grandTotal
### Description
Allows you to set the grand total of the order, in pence.
### Method
POST
### Endpoint
/api/orders/{order_id}/grandTotal
### Parameters
#### Path Parameters
- **order_id** (integer) - Required - The ID of the order.
#### Request Body
- **grand_total** (integer) - Required - The grand total in pence.
### Request Example
```json
{
"grand_total": 5500
}
```
### Response
#### Success Response (200)
- **message** (string) - Confirmation message.
#### Response Example
```json
{
"message": "Grand total updated successfully."
}
```
```
```APIDOC
## GET /api/orders/{order_id}/isFree
### Description
Returns `true` when the grand total of the order is £0.00.
### Method
GET
### Endpoint
/api/orders/{order_id}/isFree
### Parameters
#### Path Parameters
- **order_id** (integer) - Required - The ID of the order.
### Response
#### Success Response (200)
- **is_free** (boolean) - Indicates if the order is free.
#### Response Example
```json
{
"is_free": true
}
```
```
```APIDOC
## GET /api/orders/{order_id}/isPaid
### Description
Returns `true` when the grand total of the order is greater than £0.00.
### Method
GET
### Endpoint
/api/orders/{order_id}/isPaid
### Parameters
#### Path Parameters
- **order_id** (integer) - Required - The ID of the order.
### Response
#### Success Response (200)
- **is_paid** (boolean) - Indicates if the order has been paid.
#### Response Example
```json
{
"is_paid": true
}
```
```
```APIDOC
## GET /api/orders/{order_id}/subTotal
### Description
Allows you to get the sub total of the order, in pence.
### Method
GET
### Endpoint
/api/orders/{order_id}/subTotal
### Parameters
#### Path Parameters
- **order_id** (integer) - Required - The ID of the order.
### Response
#### Success Response (200)
- **sub_total** (integer) - The sub total in pence.
#### Response Example
```json
{
"sub_total": 4500
}
```
```
```APIDOC
## POST /api/orders/{order_id}/subTotal
### Description
Allows you to set the sub total of the order, in pence.
### Method
POST
### Endpoint
/api/orders/{order_id}/subTotal
### Parameters
#### Path Parameters
- **order_id** (integer) - Required - The ID of the order.
#### Request Body
- **sub_total** (integer) - Required - The sub total in pence.
### Request Example
```json
{
"sub_total": 4800
}
```
### Response
#### Success Response (200)
- **message** (string) - Confirmation message.
#### Response Example
```json
{
"message": "Sub total updated successfully."
}
```
```
```APIDOC
## GET /api/orders/{order_id}/discountTotal
### Description
Allows you to get the discount total of the order, in pence.
### Method
GET
### Endpoint
/api/orders/{order_id}/discountTotal
### Parameters
#### Path Parameters
- **order_id** (integer) - Required - The ID of the order.
### Response
#### Success Response (200)
- **discount_total** (integer) - The discount total in pence.
#### Response Example
```json
{
"discount_total": 500
}
```
```
```APIDOC
## POST /api/orders/{order_id}/discountTotal
### Description
Allows you to set the discount total of the order, in pence.
### Method
POST
### Endpoint
/api/orders/{order_id}/discountTotal
### Parameters
#### Path Parameters
- **order_id** (integer) - Required - The ID of the order.
#### Request Body
- **discount_total** (integer) - Required - The discount total in pence.
### Request Example
```json
{
"discount_total": 700
}
```
### Response
#### Success Response (200)
- **message** (string) - Confirmation message.
#### Response Example
```json
{
"message": "Discount total updated successfully."
}
```
```
--------------------------------
### Cart Facade - Get Current Cart
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Demonstrates how to retrieve and access data from the current shopping cart using the Cart facade.
```APIDOC
## Cart Facade - Get Current Cart
The Cart facade provides methods to query, create, and manage shopping carts. Use `current()` to get the active cart for web requests.
```php
use DuncanMcClean\Cargo\Facades\Cart;
// Get the current customer's cart
$cart = Cart::current();
// Access cart data
$grandTotal = $cart->grandTotal(); // Total in pence (e.g., 2999 = £29.99)
$subTotal = $cart->subTotal(); // Subtotal before discounts/shipping
$taxTotal = $cart->taxTotal(); // Total tax amount
$shippingTotal = $cart->shippingTotal();
$discountTotal = $cart->discountTotal();
// Check cart status
$isFree = $cart->isFree(); // True if grand total is £0.00
$customer = $cart->customer(); // Returns User or GuestCustomer object
// Get line items
$lineItems = $cart->lineItems(); // Returns LineItems collection
foreach ($lineItems as $item) {
echo $item->product()->title;
echo $item->quantity;
echo $item->total;
}
// Get addresses
$shippingAddress = $cart->shippingAddress(); // Returns Address object
$billingAddress = $cart->billingAddress();
$hasShipping = $cart->hasShippingAddress(); // Boolean check
```
```
--------------------------------
### Query all orders with criteria
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/extending/php-apis/orders.md
Utilize the `query()` method to build complex queries for orders. Chain `where` clauses to filter by attributes like `site` and `customer`, then use `get()` to execute the query.
```php
use DuncanMcClean\Cargo\Facades\Order;
Order::query()
->where('site', 'english')
->where('customer', $userId)
->get();
```
--------------------------------
### Get Shipping Total with Tax
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/migrating-from-simple-commerce.md
Calculates and outputs the shipping total including tax. This is achieved by summing the shipping total and shipping tax total.
```html
{{ sc:cart:shipping_total_with_tax }}
```
```html
{{ {cart:shipping_total} + {cart:shipping_tax_total} }}
```
--------------------------------
### Add Custom Checkout Step
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/frontend/checkout/prebuilt.md
Example of adding a new checkout step using the `step` partial. Ensure the step has a `title` parameter and its content is wrapped within the partial. The `slot:footer` can be used for navigation buttons.
```antlers
{{ partial:checkout/step title="Gift" }}
If this is a gift, let us know the name of the recipient and we can include a special gift note with the order.
{{ partial:checkout/input
name="gift_recipient"
label="Gift Recipient"
type="text"
placeholder="John"
}}
{{ slot:footer }}
{{ partial:checkout/button label="Continue to Payment" }}
{{ /slot:footer }}
{{ /partial:checkout/step }}
```
--------------------------------
### Get Current Cart
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/frontend/json-api/endpoints.md
Retrieves the customer's current cart. No specific setup is required beyond having a cart to retrieve.
```blade
```
--------------------------------
### Query and Create Orders - Order Facade
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Use the Order facade to find, query, and programmatically create orders. The `make()` method initializes a new order, which can then be configured and saved.
```php
use DuncanMcClean\Cargo\Facades\Order;
// Find an order
$order = Order::find(123);
$order = Order::findOrFail(123);
// Query orders
$orders = Order::query()
->where('site', 'english')
->where('customer', $userId)
->where('status', 'payment_received')
->get();
// Create an order programmatically
$order = Order::make()
->orderNumber(12345)
->status('payment_received')
->date('2025-04-07')
->site('english')
->customer($userId)
->lineItems([
['product' => 'abc', 'quantity' => 1],
['product' => 'efg', 'quantity' => 2],
]);
$order->save();
// Access order data
$orderNumber = $order->orderNumber();
$status = $order->status(); // Returns OrderStatus enum
$customer = $order->customer();
$shippingMethod = $order->shippingMethod();
$paymentGateway = $order->paymentGateway();
$taxBreakdown = $order->taxBreakdown(); // Collection of tax details
// Custom timeline events
$order->appendTimelineEvent(
type: \App\TimelineEventTypes\OrderDelivered::class,
metadata: ['carrier' => 'Royal Mail', 'tracking' => 'ABC123'],
);
```
--------------------------------
### Use Product Facade for Queries
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/extending/php-apis/products.md
Utilize the Cargo Product facade to scope entry queries specifically for products. Import the facade before use.
```php
use DuncanMcClean\Cargo\Facades\Product;
Product::all();
Product::find('product-id');
Product::findOrFail('product-id');
```
--------------------------------
### Product Facade and Variants
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
This section details how to query products using the Product facade and how to work with product variants, including defining them programmatically.
```APIDOC
## Product Facade and Variants
Products are Statamic entries with additional e-commerce fields. The Product facade scopes queries to product collections.
```php
use DuncanMcClean\Cargo\Facades\Product;
// Query products
$products = Product::all();
$product = Product::find('product-id');
$product = Product::findOrFail('product-id');
// Working with product variants
$variants = $product->variantOptions(); // Collection of ProductVariant instances
$variant = $product->variant('Small_Red');
// Variant properties
$variant->key(); // 'Small_Red'
$variant->name(); // 'Small, Red'
$variant->price(); // Price in pence
$variant->stock(); // Stock count
$variant->isStockEnabled(); // Boolean
// Define variants programmatically
$product->set('product_variants', [
'variants' => [
['name' => 'Size', 'values' => ['Small', 'Medium', 'Large']],
['name' => 'Colour', 'values' => ['Red', 'Yellow']],
],
'options' => [
['key' => 'Small_Red', 'variant' => 'Small, Red', 'price' => 2599],
['key' => 'Small_Yellow', 'variant' => 'Small, Yellow', 'price' => 2599],
['key' => 'Medium_Red', 'variant' => 'Medium, Red', 'price' => 2999],
['key' => 'Medium_Yellow', 'variant' => 'Medium, Yellow', 'price' => 2999],
['key' => 'Large_Red', 'variant' => 'Large, Red', 'price' => 3499, 'stock' => 10],
['key' => 'Large_Yellow', 'variant' => 'Large, Yellow', 'price' => 3499, 'stock' => 5],
],
]);
$product->save();
```
```
--------------------------------
### Create a new order instance
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/extending/php-apis/orders.md
Begin the order creation process by instantiating a new order object using the `make` method.
```php
use DuncanMcClean\Cargo\Facades\Order;
Order::make();
```
--------------------------------
### Get Shipping Total
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/migrating-from-simple-commerce.md
Outputs the total shipping cost. Use the `raw` filter to get the value without formatting.
```html
{{ sc:cart:shipping_total }}
```
```html
{{ cart:shipping_total }}
```
```html
{{ sc:cart:raw_shipping_total }}
```
```html
{{ cart:shipping_total | raw }}
```
--------------------------------
### Order Facade - Query and Create Orders
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Details on how to find, query, and programmatically create orders using the Order facade.
```APIDOC
## Order Facade - Query and Create Orders
The Order facade provides similar functionality to Cart for managing completed orders.
```php
use DuncanMcClean\Cargo\Facades\Order;
// Find an order
$order = Order::find(123);
$order = Order::findOrFail(123);
// Query orders
$orders = Order::query()
->where('site', 'english')
->where('customer', $userId)
->where('status', 'payment_received')
->get();
// Create an order programmatically
$order = Order::make()
->orderNumber(12345)
->status('payment_received')
->date('2025-04-07')
->site('english')
->customer($userId)
->lineItems([
['product' => 'abc', 'quantity' => 1],
['product' => 'efg', 'quantity' => 2],
]);
$order->save();
// Access order data
$orderNumber = $order->orderNumber();
$status = $order->status(); // Returns OrderStatus enum
$customer = $order->customer();
$shippingMethod = $order->shippingMethod();
$paymentGateway = $order->paymentGateway();
$taxBreakdown = $order->taxBreakdown(); // Collection of tax details
// Custom timeline events
$order->appendTimelineEvent(
type: \App\TimelineEventTypes\OrderDelivered::class,
metadata: ['carrier' => 'Royal Mail', 'tracking' => 'ABC123'],
);
```
```
--------------------------------
### Query Products and Manage Variants with Product Facade
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Use the Product facade to query products and access their variants. Variants can be retrieved by their key or defined programmatically.
```php
use DuncanMcClean\Cargo\Facades\Product;
// Query products
$products = Product::all();
$product = Product::find('product-id');
$product = Product::findOrFail('product-id');
// Working with product variants
$variants = $product->variantOptions(); // Collection of ProductVariant instances
$variant = $product->variant('Small_Red');
// Variant properties
$variant->key(); // 'Small_Red'
$variant->name(); // 'Small, Red'
$variant->price(); // Price in pence
$variant->stock(); // Stock count
$variant->isStockEnabled(); // Boolean
// Define variants programmatically
$product->set('product_variants', [
'variants' => [
['name' => 'Size', 'values' => ['Small', 'Medium', 'Large']],
['name' => 'Colour', 'values' => ['Red', 'Yellow']],
],
'options' => [
['key' => 'Small_Red', 'variant' => 'Small, Red', 'price' => 2599],
['key' => 'Small_Yellow', 'variant' => 'Small, Yellow', 'price' => 2599],
['key' => 'Medium_Red', 'variant' => 'Medium, Red', 'price' => 2999],
['key' => 'Medium_Yellow', 'variant' => 'Medium, Yellow', 'price' => 2999],
['key' => 'Large_Red', 'variant' => 'Large, Red', 'price' => 3499, 'stock' => 10],
['key' => 'Large_Yellow', 'variant' => 'Large, Yellow', 'price' => 3499, 'stock' => 5],
],
]);
$product->save();
```
--------------------------------
### Configure Payment Gateways in PHP
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/payment-gateways.md
Set up payment gateway configurations, including API keys and other options, in the `cargo.php` configuration file. Sensitive values should be stored in your `.env` file.
```php
// config/statamic/cargo.php
'payments' => [
'gateways' => [
'dummy' => [
//
],
// 'stripe' => [
// 'key' => env('STRIPE_KEY'),
// 'secret' => env('STRIPE_SECRET'),
// 'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
// ],
// 'mollie' => [
// 'api_key' => env('MOLLIE_KEY'),
// 'profile_id' => env('MOLLIE_PROFILE_ID'),
// ],
],
],
```
--------------------------------
### Create a New Cart using PHP
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/extending/php-apis/carts.md
Instantiate a new cart using the `make` method on the Cart facade. Further customization can be applied before saving.
```php
use DuncanMcClean\Cargo\Facades\Cart;
Cart::make();
```
--------------------------------
### Get States for a Country via API
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Use this GET request to retrieve a list of states for a given country. Specify the country code in the query parameters.
```bash
curl -X GET "https://your-store.com/!/cargo/states?country=USA"
```
--------------------------------
### Get Current Cart via JSON API
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Retrieve the current cart details using a GET request to the /!/cargo/cart endpoint. The response includes totals, line items, and customer information.
```bash
# Get current cart
curl -X GET "https://your-store.com/!/cargo/cart" \
-H "Accept: application/json"
```
--------------------------------
### Migrate sc:cart:* to cart:*
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/migrating-from-simple-commerce.md
General wildcard tags under `sc:cart` should be updated to `cart:*`.
```antlers
{{ sc:cart: }}
```
```antlers
{{ cart: }}
```
--------------------------------
### Initialize Alpine.js Data for Discount Code Forms
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/resources/views/checkout/components/_cart_summary.antlers.html
Sets up Alpine.js data components for applying and removing discount codes. Ensure Alpine.js is loaded before this script.
```javascript
document.addEventListener('alpine:init', () => {
Alpine.data('ApplyDiscountCodeForm', () => ({
discountCode: null,
busy: false,
error: null,
async applyDiscountCode(e) {
e.preventDefault();
this.busy = true;
this.error = null;
await this.submit(this.$root)
.then(data => this.discountCode = null)
.catch(error => {
if (error.status === 422) {
error.json().then(data => {
this.error = data.message;
});
return;
}
alert(`Something went wrong while redeeming the discount code. Please try again later.`);
})
.finally(() => this.busy = false);
},
}));
Alpine.data('RemoveDiscountCodeForm', () => ({
async removeDiscountCode(e) {
e.preventDefault();
await this.submit(this.$root)
.catch(error => {
alert(`Something went wrong while removing the discount code. Please try again later.`);
});
},
}));
});
```
--------------------------------
### GET /!/cargo/cart
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/frontend/json-api/endpoints.md
Retrieves the current customer's cart.
```APIDOC
## GET /!/cargo/cart
### Description
Returns the customer's cart.
### Method
GET
### Endpoint
/!/cargo/cart
### Response
#### Success Response (200)
- **cart** (object) - The customer's cart details.
```
--------------------------------
### Migrate Orders to Database
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/orders.md
Run this command to move existing orders to the database. It handles publishing migrations, updating configuration, and importing data. Ensure you have a backup strategy in place before execution.
```bash
php please cargo:database-orders
```
--------------------------------
### Shipping Total Management
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/extending/php-apis/orders.md
Methods for getting and setting the shipping total in pence.
```APIDOC
## GET/SET shippingTotal
### Description
Allows you to get or set the shipping total, in pence. The `$shippingTotal` parameter is optional.
### Method
GET/SET
### Endpoint
`/shippingTotal`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **shippingTotal** (integer) - Optional - The shipping total in pence.
### Request Example
```json
{
"shippingTotal": 500
}
```
### Response
#### Success Response (200)
- **shippingTotal** (integer) - The current shipping total in pence.
#### Response Example
```json
{
"shippingTotal": 500
}
```
```
--------------------------------
### Tax Total Management
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/extending/php-apis/orders.md
Methods for getting and setting the tax total in pence.
```APIDOC
## GET/SET taxTotal
### Description
Allows you to get or set the tax total, in pence. The `$taxTotal` parameter is optional.
### Method
GET/SET
### Endpoint
`/taxTotal`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **taxTotal** (integer) - Optional - The tax total in pence.
### Request Example
```json
{
"taxTotal": 1000
}
```
### Response
#### Success Response (200)
- **taxTotal** (integer) - The current tax total in pence.
#### Response Example
```json
{
"taxTotal": 1000
}
```
```
--------------------------------
### Shipping Total Management
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/extending/php-apis/carts.md
Allows for getting or setting the shipping total, specified in pence.
```APIDOC
## POST /shippingTotal
### Description
Allows you to get/set the shipping total, in pence. The `$shippingTotal` parameter is optional.
### Method
POST
### Endpoint
/shippingTotal
### Parameters
#### Query Parameters
- **shippingTotal** (integer) - Optional - The shipping total in pence.
### Request Example
```json
{
"shippingTotal": 500
}
```
### Response
#### Success Response (200)
- **shippingTotal** (integer) - The current shipping total in pence.
#### Response Example
```json
{
"shippingTotal": 500
}
```
```
--------------------------------
### Cart Facade - Create and Update Cart
Source: https://context7.com/duncanmcclean/statamic-cargo/llms.txt
Shows how to programmatically create new carts, add line items, and manage cart persistence.
```APIDOC
## Cart Facade - Create and Update Cart
Create new carts programmatically and configure customer, line items, and shipping details.
```php
use DuncanMcClean\Cargo\Facades\Cart;
// Create a new cart
$cart = Cart::make()
->site('english')
->customer($userId) // Or pass array for guest: ['name' => 'John', 'email' => 'john@example.com']
->lineItems([
['product' => 'product-entry-id', 'quantity' => 2],
['product' => 'another-product-id', 'variant' => 'Large_Red', 'quantity' => 1],
]);
// Save the cart (automatically recalculates totals)
$cart->save();
// Save without recalculating
$cart->saveWithoutRecalculating();
// Save without dispatching events
$cart->saveQuietly();
// Delete the cart
$cart->delete();
// Query carts
$carts = Cart::query()
->where('site', 'english')
->where('customer', $userId)
->get();
// Find a specific cart
$cart = Cart::find(123);
$cart = Cart::findOrFail(123); // Throws exception if not found
```
```
--------------------------------
### Cart Management Methods
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/extending/php-apis/carts.md
Methods for getting and setting cart properties and performing save/delete operations.
```APIDOC
## Cart Methods
### `id($id)`
Allows you to get/set the cart's ID. The `$id` parameter is optional.
### Method
`GET`/`POST` (Conceptual, as these are object methods)
### Endpoint
N/A (Object Method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```php
// Get ID
$cartId = $cart->id();
// Set ID
$cart->id('new-cart-id');
```
### Response
#### Success Response (200)
- **id** (string) - The cart's ID.
#### Response Example
```json
{
"id": "cart-123"
}
```
---
### `customer($customer)`
Allows you to get/set the customer. Returns a Statamic `User` object, or a `GuestCustomer` object. Accepts an optional `$customer` parameter, which should either be a Statamic `User` object, a user ID, or an array of guest customer data.
### Method
`GET`/`POST` (Conceptual, as these are object methods)
### Endpoint
N/A (Object Method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```php
// Get customer
$customer = $cart->customer();
// Set customer by User object
$user = User::find(1);
$cart->customer($user);
// Set customer by user ID
$cart->customer(1);
// Set customer by guest data
$cart->customer(['name' => 'John Doe', 'email' => 'john@example.com']);
```
### Response
#### Success Response (200)
- **customer** (User|GuestCustomer) - The customer object associated with the cart.
#### Response Example
```json
{
"customer": {
"id": 1,
"name": "Jane Doe",
"email": "jane@example.com"
}
}
```
---
### `coupon($coupon)`
Allows you to get/set the cart's coupon. The `$coupon` parameter is optional.
### Method
`GET`/`POST` (Conceptual, as these are object methods)
### Endpoint
N/A (Object Method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```php
// Get coupon
$coupon = $cart->coupon();
// Set coupon
$cart->coupon('DISCOUNT10');
```
### Response
#### Success Response (200)
- **coupon** (string|null) - The coupon code applied to the cart.
#### Response Example
```json
{
"coupon": "DISCOUNT10"
}
```
---
### `shippingMethod()`
Allows you to get the selected shipping method. Returns a `ShippingMethod` object.
### Method
`GET` (Conceptual, as this is an object method)
### Endpoint
N/A (Object Method)
### Parameters
None
### Request Example
```php
$shippingMethod = $cart->shippingMethod();
```
### Response
#### Success Response (200)
- **shippingMethod** (ShippingMethod) - The selected shipping method object.
#### Response Example
```json
{
"shippingMethod": {
"id": "flatrate",
"name": "Flat Rate Shipping"
}
}
```
---
### `shippingOption()`
Allows you to get the selected shipping option. Returns a `ShippingOption` object.
### Method
`GET` (Conceptual, as this is an object method)
### Endpoint
N/A (Object Method)
### Parameters
None
### Request Example
```php
$shippingOption = $cart->shippingOption();
```
### Response
#### Success Response (200)
- **shippingOption** (ShippingOption) - The selected shipping option object.
#### Response Example
```json
{
"shippingOption": {
"id": "option-a",
"name": "Standard Shipping"
}
}
```
---
### `paymentGateway()`
Allows you to get the selected payment gateway. Returns a `PaymentGateway` object.
### Method
`GET` (Conceptual, as this is an object method)
### Endpoint
N/A (Object Method)
### Parameters
None
### Request Example
```php
$paymentGateway = $cart->paymentGateway();
```
### Response
#### Success Response (200)
- **paymentGateway** (PaymentGateway) - The selected payment gateway object.
#### Response Example
```json
{
"paymentGateway": {
"id": "stripe",
"name": "Stripe"
}
}
```
---
### `lineItems($lineItems)`
Allows you to get/set line items. Returns a `LineItems` collection of `LineItem` objects (you can use Laravel collection methods on the `LineItems` class). Accepts an optional `$lineItems` parameter, which should be an array of line items to replace the current line items.
### Method
`GET`/`POST` (Conceptual, as these are object methods)
### Endpoint
N/A (Object Method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **lineItems** (array) - Optional. An array of line items to replace the current line items.
### Request Example
```php
// Get line items
$lineItems = $cart->lineItems();
// Set line items
$newLineItems = [
['product_id' => 1, 'quantity' => 2],
['product_id' => 3, 'quantity' => 1]
];
$cart->lineItems($newLineItems);
```
### Response
#### Success Response (200)
- **lineItems** (LineItems) - A collection of line item objects.
#### Response Example
```json
{
"lineItems": [
{
"product_id": 1,
"quantity": 2,
"price": 10.00
}
]
}
```
---
### `site($site)`
Allows you to get/set the cart's site. The `$site` parameter is optional.
### Method
`GET`/`POST` (Conceptual, as these are object methods)
### Endpoint
N/A (Object Method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```php
// Get site
$site = $cart->site();
// Set site
$cart->site('default'); // Assuming 'default' is a valid site handle
```
### Response
#### Success Response (200)
- **site** (string) - The handle of the cart's site.
#### Response Example
```json
{
"site": "default"
}
```
---
### `saveWithoutRecalculating()`
Saves the cart without recalculating totals.
### Method
`POST` (Conceptual, as this is an object method)
### Endpoint
N/A (Object Method)
### Parameters
None
### Request Example
```php
$cart->saveWithoutRecalculating();
```
### Response
#### Success Response (200)
Indicates successful save operation.
#### Response Example
```json
{
"status": "success"
}
```
---
### `saveQuietly()`
Saves the cart without dispatching events.
### Method
`POST` (Conceptual, as this is an object method)
### Endpoint
N/A (Object Method)
### Parameters
None
### Request Example
```php
$cart->saveQuietly();
```
### Response
#### Success Response (200)
Indicates successful save operation.
#### Response Example
```json
{
"status": "success"
}
```
---
### `save()`
Saves the cart.
### Method
`POST` (Conceptual, as this is an object method)
### Endpoint
N/A (Object Method)
### Parameters
None
### Request Example
```php
$cart->save();
```
### Response
#### Success Response (200)
Indicates successful save operation.
#### Response Example
```json
{
"status": "success"
}
```
---
### `deleteQuietly()`
Deletes the cart without dispatching events.
### Method
`DELETE` (Conceptual, as this is an object method)
### Endpoint
N/A (Object Method)
### Parameters
None
### Request Example
```php
$cart->deleteQuietly();
```
### Response
#### Success Response (200)
Indicates successful delete operation.
#### Response Example
```json
{
"status": "success"
}
```
```
--------------------------------
### Configure Shipping Methods in Config
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/shipping.md
Add your shipping methods to the `cargo.php` configuration file under the `shipping.methods` key to make them available during checkout. Use their handles as keys.
```php
// config/statamic/cargo.php
'shipping' => [
'methods' => [
'free_shipping' => [],
'royal_mail' => []
],
],
```
--------------------------------
### Publish Cargo Pre-built Checkout
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/frontend/checkout/prebuilt.md
Run this command to publish the pre-built checkout flow assets into your project. This allows for direct modification of the checkout views and logic.
```bash
php artisan vendor:publish --tag=cargo-prebuilt-checkout
```
--------------------------------
### Get Coupon/Discount Total
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/migrating-from-simple-commerce.md
Outputs the total discount applied to the cart. Use the `raw` filter for the unformatted value.
```html
{{ sc:cart:coupon_total }}
```
```html
{{ cart:discount_total }}
```
```html
{{ sc:cart:raw_coupon_total }}
```
```html
{{ cart:discount_total | raw }}
```
--------------------------------
### Configure Dummy Payment Gateway
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/migrating-from-simple-commerce.md
Add the 'dummy' gateway to the `payments.gateways` array in your `config/statamic/cargo.php` file. This is a basic configuration for testing purposes.
```php
// config/statamic/cargo.php
'payments' => [
'gateways' => [
'dummy' => [], // [tl! add]
],
],
```
--------------------------------
### Get Tax Total
Source: https://github.com/duncanmcclean/statamic-cargo/blob/1.x/docs/docs/migrating-from-simple-commerce.md
Outputs the total tax amount for the cart. Use the `raw` filter for the unformatted value.
```html
{{ sc:cart:tax_total }}
```
```html
{{ cart:tax_total }}
```
```html
{{ sc:cart:raw_tax_total }}
```
```html
{{ cart:tax_total | raw }}
```