Controller Actions

You are viewing documentation for an unreleased version of Craft Commerce. Please be aware that some pages, screenshots, and technical reference may still reflect older versions.

Commerce exposes a number of common resources to your storefront via an HTTP API.

We recommend reviewing the main Craft documentation on working with controller actions before you dig in, here!

# Available Actions

Methods Action Description
POST cart/complete Completes an order without payment.
GET cart/get-cart Returns the current cart as JSON.
GET/POST cart/load-cart Loads a cookie for the given cart.
POST cart/forget-cart Removes a cookie for the current cart. 4.3.0+
POST cart/update-cart Manage a customer’s current cart.
POST payment-sources/add Creates a new payment source.
POST payment-sources/delete Deletes a payment source.
GET payments/complete-payment Processes customer’s return from an off-site payment.
POST payments/pay Makes a payment on an order.
GET downloads/pdf Returns an order PDF as a file.
POST subscriptions/subscribe Starts a new subscription.
POST subscriptions/cancel Cancels an active subscription.
POST subscriptions/switch Switch an active subscription’s plan.
POST subscriptions/reactivate Reactivates a canceled subscription.

Address management actions are part of the main Craft documentation. Commerce also allows address information to be set directly on a cart via POST cart/update-cart.

# POST cart/complete

You can let your customers complete an order without a payment transaction. The allowCheckoutWithoutPayment setting must be enabled or an HTTP exception will be thrown.

The cart must have an email address and honor the following settings:

See the Making Payments page for more on using this action.

# Supported Params

Param Description
forceSave Optionally set to true to force saving the cart.
number Optional order number for a specific, existing cart.
registerUserOnOrderComplete Whether to create a user account for the customer when the cart is completed and turned into an order.

# Response

The output of the action depends on whether the cart was completed successfully and the Accept header.

State text/html application/json
Standard behavior. Standard behavior; cart data is available under a key determined by the cartVariable config setting.
Standard behavior; cart is available in the template under a variable determined by the cartVariable. Standard behavior; cart data is available under a key determined by the cartVariable config setting.

# GET cart/get-cart

Returns the current cart as JSON. A new cart cookie will be generated if one doesn’t already exist.

The request must include Accept: application/json in its headers.

# Supported Params

Param Description
number Optional order number for a specific, existing cart.
forceSave Optionally set to true to force saving the cart.

# Response

State application/json
Standard behavior; cart data is available under a key determined by the cartVariable config setting.

# POST cart/update-cart

Updates the cart by adding or updating line items, and setting addresses and other cart attributes.

Read more about working with Addresses in Commerce.

# Supported Params

Param Description
billingAddress[] Billing address attributes. (See Addresses).
billingAddressId ID of an existing address to use as the billing address.
billingAddressSameAsShipping Set to true to use shipping address for billing address. (Will ignore billing address ID and fields.)
clearNotices When passed, clears all cart notices.
clearLineItems When passed, empties all line items from cart.
couponCode Coupon code for a discount that should be applied to the cart.
email Email address to be associated with the cart.
estimatedBillingAddress[] Estimated billing address attributes. (See Addresses).
estimatedBillingAddressSameAsShipping Set to true to use shipping address for estimated billing address.
estimatedShippingAddress[] Estimated shipping address attributes. (See Addresses).
fields[] Optional array of custom fields to be submitted to the cart.
forceSave Optionally set to true to force saving the cart.
gatewayId The payment gateway ID to be used when the cart is completed.
lineItems[] Array of one or more of the cart’s line items to update. Each must have an id key-value pair, and may include options, note, and qty key-value pairs. An item may include a remove key with a value of 1 or a qty of 0 to be removed from the cart.
number Optional order number for specific, existing cart.
paymentCurrency ISO code of a configured payment currency to be used for the cart.
paymentSourceId The ID for a payment source that should be used when the cart is completed.
purchasableId Single purchasable ID to be added to the cart. If provided, will also use optional note, options[], and qty parameters.
purchasables[] Array of one or more purchasables to be added to the cart. Each must include an id key-value pair, and may include options, note, and qty key-value pairs.
registerUserOnOrderComplete Whether to create a user account for the customer when the cart is completed and turned into an order.
saveBillingAddressOnOrderComplete Whether to save the billing address to the customer’s address book when the cart is completed and turned into an order. 4.3.0+
saveShippingAddressOnOrderComplete Whether to save the shipping address to the customer’s address book when the cart is completed and turned into an order. 4.3.0+
saveAddressesOnOrderComplete Whether to save both the shipping and billing address to the customer’s address book when the cart is completed and turned into an order. Unlike saveBillingAddressOnOrderComplete and saveShippingAddressOnOrderComplete, this is not stored on the order itself—it just allows customers to set both at the same time. 4.3.0+
shippingAddress[] Shipping address attributes. (See Addresses).
shippingAddressId ID of an existing address to use as the shipping address.
shippingAddressSameAsBilling Set to true to use billing address for shipping address and ignore shippingAddress and shippingAddressId.
shippingMethodHandle The handle of a shipping method to be set for the cart.

# Response

The output of the action depends on whether the cart was updated successfully and the Accept header.

State text/html application/json
Standard behavior. Standard behavior; cart data is available under a key determined by the cartVariable config setting.
Standard behavior. Standard behavior; cart data is available under a key determined by the cartVariable config setting.

# GET/POST cart/load-cart

Loads a cookie for the specified cart.

# Supported Params

Param Description
number Required cart number to be loaded.

# Response

The action’s output depends on whether the cart was loaded successfully and the Accept header.

State text/html application/json
Standard behavior; GET requests are redirected to the loadCartRedirectUrl. Standard behavior.
Standard behavior; GET requests are redirected per the loadCartRedirectUrl. Standard behavior.

# POST cart/forget-cart 4.3.0+

Detaches a cart from the current customer’s session. Read more about managing carts.

This action has no arguments and responses are only sent as text/html.

# Response

State text/html
Standard behavior.

# GET cart/get-cart

Returns the current cart as JSON. A new cart cookie will be generated if one doesn’t already exist.

The request must include Accept: application/json in its headers.

# Supported Params

Param Description
number Optional order number for a specific, existing cart.
forceSave Optionally set to true to force saving the cart.

# Response

State application/json
Standard behavior; cart data is available under a key determined by the cartVariable config setting.

# POST payment-sources/add

Creates a new payment source for the current customer.

# Supported Params

Param Description
* All body parameters will be provided directly to the gateway’s payment form model.
description Description for the payment source.
gatewayId ID of the new payment source’s gateway, which must support payment sources.
isPrimaryPaymentSource Send a non-empty value to make this the customer’s primary payment source.

# Response

The action’s output depends on whether the payment source was saved and the Accept header.

State text/html application/json
Standard behavior. Standard behavior; PaymentSource (opens new window) data available under the paymentSource key.
Standard behavior; BasePaymentForm (opens new window) subclass available in the template as paymentForm, Standard behavior; payment form data available under the paymentForm key.

Note that the models available in success and failure states are different!

# POST payment-sources/delete

Deletes a payment source.

# Supported Params

Param Description
id ID of the saved payment source to delete. (Must belong to the customer, otherwise the user deleting must have commerce-manageOrders permission.)

# Response

The action’s output depends on whether the payment source was removed successfully and the Accept header.

# POST payments/pay

Makes a payment on an order. Read more about making payments.

# Supported Params

Param Description
* All body parameters will be provided directly to the gateway’s payment form model.
cancelUrl URL user should end up on if they choose to cancel payment.
email Email address of the person responsible for payment, which must match the email address on the order. Required if the order being paid is not the active cart.
gatewayId The payment gateway ID to be used for payment.
number The order number payment should be applied to. When ommitted, payment is applied to the current cart.
paymentAmount Hashed payment amount, expressed in the cart’s paymentCurrency. Available only if partial payments are allowed.
paymentCurrency ISO code of a configured payment currency to be used for the payment.
paymentSourceId The ID for a payment source that should be used for payment.
registerUserOnOrderComplete Whether the customer should have an account created on order completion.
savePaymentSource Whether to save card information as a payment source. (Gateway must support payment sources.)
saveBillingAddressOnOrderComplete Whether to save the billing address to the customer’s address book when the cart is completed and turned into an order. 4.3.0+
saveShippingAddressOnOrderComplete Whether to save the shipping address to the customer’s address book when the cart is completed and turned into an order. 4.3.0+
saveAddressesOnOrderComplete Whether to save both the shipping and billing address to the customer’s address book when the cart is completed and turned into an order. 4.3.0+

# Response

The action’s output depends on whether payment was applied successfully and Accept header.

State text/html application/json
Standard behavior; redirection defaults to the order’s returnUrl. Standard behavior; cart data is available under a key determined by the cartVariable, as well as special paymentForm, transactionId, and transactionHash properties.
Standard behavior; cart is available in the template under a variable determined by the cartVariable, as well as special paymentForm and paymentFormErrors variables. Standard behavior; cart data is available under a key determined by the cartVariable, as well as special paymentForm and paymentFormErrors properties.

Both the cart and payment form models may have errors. Be sure and check all returned variables when a payment fails—the top-level errors key in JSON responses will only include errors from the payment form.

# GET payments/complete-payment

Processes customer’s return from an off-site payment.

# Supported Params

Param Description
commerceTransactionHash Required transaction hash used to verify the off-site payment being completed.

# Response

The action’s output depends on whether the payment completed successfully and the Accept header.

State text/html application/json
Standard behavior; redirection defaults to the order’s returnUrl. Standard behavior; special url property set to the order’s returnUrl.
Standard behavior; redirection defaults to the order’s cancelUrl. Standard behavior; special url property set to the order’s cancelUrl.

# GET downloads/pdf

Generates and sends an order PDF as a file.

# Supported Params

Param Description
number Required order number.
option Optional string value that’s passed to the PDF template.
pdfHandle Handle of a configured PDF to be rendered.

# Response

State Output
File response with the rendered PDF and an application/pdf MIME type.
Exceptions will be rendered with the normal error template.

# POST subscriptions/subscribe

Starts a new subscription with the current customer’s default payment source. Learn more about supporting Subscriptions.

We recommend using normal HTML forms and a text/html content type for this action, as the gateway may require redirection to resolve billing issues when a subscription cannot be started. This workflow can be problematic when using application/json over Ajax.

# Supported Params

Param Description
planUid Required. UID of the Commerce plan the customer wants to subscribe to.
fields[...] Subscription custom field values, indexed by their handles.
fieldsLocation Allows relocation of the default fields key for custom field data (see above).
* Conditionally required. Each gateway that supports subscriptions may require additional properties on its craft\commerce\models\subscriptions\SubscriptionForm (opens new window) subclass.

planUid and all gateway-specific properties must be hashed to prevent tampering.

# Response

State text/html application/json
Standard behavior. Standard behavior; the Subscription model is available under the subscription key.
Standard behavior. Most subscription failures will be presented as a succinct error message. Specific issues are logged, but may not be disclosed to the customer. The user may be redirected to the updateBillingDetailsUrl setting to resolve billing issues. Standard behavior.

# POST subscriptions/cancel

Cancels an active subscription.

# Supported Params

Param Description
subscriptionUid Required. UID of the subscription to cancel. Must be hashed.
* Conditionally required. Each gateway that supports subscriptions may require additional properties on its craft\commerce\models\subscriptions\CancelSubscriptionForm (opens new window) subclass.

# Response

State text/html application/json
Standard behavior. Standard behavior; the Subscription model is available under the subscription key.
Standard behavior. Standard behavior.

# POST subscriptions/switch

Switch the plan on an active subscription.

# Supported Params

Param Description
subscriptionUid Required. UID of the subscription getting updated. Must be hashed.
planUid Required. UID of the plan to switch to. Must be hashed.
* Conditionally required. Each gateway that supports subscriptions may require additional properties on its craft\commerce\models\subscriptions\SwitchPlansForm (opens new window) subclass.

# Response

The request may fail if the new and old plans are not compatible. This is determined by the gateway, so be sure and consult its documentation and platform limitations.

You can check whether two plans are compatible in Twig, to narrow the options displayed to your customers:

{% set currentPlan = subscription.getPlan() %}
{% set gateway = currentPlan.getGateway() %}
{% set allPlans = craft.commerce.plans.getPlansByGatewayId(gateway.id) %}
{% set switchablePlans = allPlans|filter((p) => p.canSwitchFrom(currentPlan)) %}

<select name="planUid">
  {% for plan in switchablePlans %}
    <option value="{{ plan.uid|hash }}">{{ plan.name }}</option>
  {% endfor %}
</select>
State text/html application/json
Standard behavior. Standard behavior; the Subscription model is available under the subscription key.
Standard behavior. Standard behavior.

# POST subscriptions/reactivate

Reactivates a canceled subscription. Only subscriptions that haven’t expired yet can be reactivated—a subscription may be canceled

# Supported Params

Param Description
subscriptionUid Required. UID of the subscription to reactivate. Must be hashed.

# Response

State text/html application/json
Standard behavior. Standard behavior; the Subscription model is available under the subscription key.
Standard behavior. Standard behavior.