Shopify Scripts API reference

Scripts are written with a Ruby API that gives you a great deal of control and flexibility.

There are different script types. A script is assigned a type when you create the script in the Script Editor app, based on which script template you choose to start with:

Line item scripts

Line item scripts affect line items in the cart and can change prices and grant discounts. These scripts are run when a change is made to the cart.

Line item scripts that discount a subscription apply only to the first payment of the subscription. Subsequent payments are not discounted by the script.

Some methodscan only be used in line item scripts.

Shipping scripts

Shipping scripts interact withshipping, and can change shipping methods and grant discounts on shipping rates. These scripts run when the checkout reaches the shipping options page.

Shipping scripts that discount the rate of shipping a subscription apply only to the first payment of the subscription. Subsequent payments are not discounted by the script.

Some methodscan only be used in shipping scripts.

Payment Scripts

Payment scripts interact withpayments, and can rename, hide and reorder payment gateways. Note that payment scripts do not interact with payment gateways shown before the checkout screen, such as Apple Pay. These scripts are run when the checkout reaches the payment page.

Some methodscan only be used in payment scripts.

General methods

The following methods are usable in any type of script:

Input

Script input methods
Method Return type Description
.cart Cart Returns a mutable cart object.
.locale string Returns the customer's locale. For example,en,fr, orpt-BR.

Cart

The cart object is only available on the online store. Some abandoned checkouts have access to the cart object. However, if a checkout has been closed and then a customer visits the abandoned checkout, it sends them to the pre-filled checkout and the cart object no longer exists. This is because the storefront has been bypassed by the abandoned checkout email.

Script methods using the Cart object
Method Return type Description
.customer 铜stomer Returns the owner of the cart (if any).
.shipping_address ShippingAddress Returns the shipping address of the owner of the cart (if any).
.discount_code varies Returns:

discount_codeis present if a discount has been applied to the cart. This does not necessarily mean that the price of the cart changes. For example, if a discount applies to carts above $50, and a script reduces the cart price below $50,discount_codeis still present but the price of the cart doesn't change.

See an example ofdiscount_code.

.line_items List Returns a list containing the line items in the cart.
.presentment_currency List Returns the customer's local (presentment) currency (inISO 4217format). For example, USD.
.subtotal_price Money Returns the subtotal price of the cart after line item discounts are applied but before discount codes are applied.
.total_weight grams Returns the total weight of all the line items in the cart.

CartDiscount::FixedAmount

Script methods using the CartDiscount::FixedAmount object
Method Return type Description
.code String Returns the discount code used to apply the discount.
.amount Money Returns the money amount of the discount.
.reject({ message: String }) nil Rejects the discount code applied to the cart. Amessageis required.
.rejected? Boolean Returns whether the discount code was rejected.

CartDiscount::Percentage

Script methods using the CartDiscount::Percentage object
Method Return type Description
.code String Returns the discount code used to apply the discount.
.percentage Decimal Returns the percentage amount of the discount.
.reject({ message: String }) nil Rejects the discount code applied to the cart. Amessageis required.
.rejected? Boolean Returns whether the discount code was rejected.

CartDiscount::Shipping

Script methods using the CartDiscount::Shipping object
Method Return type Description
.code String Returns the discount code used to apply the discount.
.reject({ message: String }) nil Rejects the discount code applied to the cart. Amessageis required.
.rejected? Boolean Returns whether the discount code was rejected.

铜stomer

Script methods using the Customer object
Method Return type Description
.id Integer Returns the customer's ID number.
.email String Returns the customer's email address.
.tags List Returns a list of strings representing any tags set for a customer.
.orders_count Integer Returns the total number of orders a customer has placed.
.total_spent Money Returns the total amount that the customer has spent on all orders.
.accepts_marketing? Boolean Returns whether the customer accepts marketing.

LineItem

Script methods using the LineItem object
Method Return type Description
.grams grams Returns the total weight of the line item.
.line_price Money The price of the line item.
.discounted? Boolean Returns whether the price of a line item has been discounted by a script or a manually applied discount. The use of discount codes doesn't affect the return value.
.properties hash Returns the properties that were specified for this line items.
.variant Variant Returns the specific product variant represented by the line item.
.quantity Integer Returns the quantity of this line item.
.selling_plan_id Integer Returns the ID of the selling plan for the line item. This method is useful when the store sells subscriptions and you want the script to detect when a product variant issold as a subscription.

List

Script methods using the List object
Method Return type Description
.new List Creates a new object to represent a list.
.[] Element or nil

Returns the element at the specified index.

.& List

Returns a new list containing elements common to the two lists, with no duplicates.

.delete_if List Delete elements using an optional code block. See the documentation forRuby'sdelete_ifmethod.
.empty? Boolean

Returnstrueif the list contains no elements.

.first Element or nil

Returns the first element ornilif the list is empty.

.index(*args, &block) int or nil

Returns the index of the first element of the list. If a block is given instead of an argument, returns the index of the first element for which the block is true.

.rindex(*args, &block) int or nil

Returns the index of the last element of the list. If a block is given instead of an argument, returns the index of the first element for which the block is true.

.last Element or nil

Returns the last element ornilif the list is empty.

.length int

Returns the number of elements in the list.

.size int

Alias for length.

.each(*args, &block) List

Calls a block once for each element in the list, passing the element as a parameter to the block.

ShippingAddress

Script methods using the ShippingAddress object
Method Return type Description
.name string Returns the name of the of the person associated with the shipping address.
.address1 string Returns the street address portion of the shipping address.
.address2 string Returns the optional additional field of the street address portion of the shipping address.
.phone string Returns the phone number of the shipping address.
.city string Returns the city of the shipping address.
.zip string Returns the ZIP code of the shipping address.
.province string Returns the province/state of the shipping address.
.province_code string Returns the abbreviated value of the province/state of the shipping address.
.country_code string Returns the abbreviated value of the country of the shipping address.

Money

Script methods using the Money object
Method Return type Description
.derived_from_presentment(customer_cents:X) Money Converts an amount (in cents) from the customer's local (presentment) currency to your store's currency. This method accepts thecustomer_centsparameter, which accepts a number in cents. For example,Money.derived_from_presentment(customer_cents: 500).
.new Money Creates a new object to represent a price.
.zero Money

Creates a new object with a price of zero.

+ Money Adds twoMoneyobjects.
- Money Subtracts oneMoneyobject from another.
* Money Multiplies aMoneyobject by a number.

Money examples

Money.new(cents:1000)

Creates aMoneyobject representing 1000 cents, or $10.

Money.new(cents:100)*50

Creates aMoneyobject representing $1, then multiplies that amount by 50. Returns aMoneyobject representing $50.

Variant

Script methods using the Variant object
Method Return type Description
.id Integer Returns the ID number of the variant.
.price Money Returns the unit price of the variant.
.product Product Returns the associated product of the variant.
.skus List Returns the stock keeping units (SKUs) of the variant, which are often used for tracking inventory.
.title String Returns the title of the variant.

Product

Script methods using the Product object
Method Return type Description
.id Integer Returns the ID number of the product.
.gift_card? Boolean Returns whether the product is a gift card.
.tags List Returns a list of strings representing the tags that are set for this product.
.product_type String A categorization that a product can be tagged with, commonly used for filtering and searching.
.vendor String Returns the vendor of this product.

Kernel

Kernelis a Ruby module that is included in every class. As a result, its methods are available to every object. These methods act in the same way as global functions act in other languages.

脚本使用内核对象的方法
Method Return type Description
.exit none Ends execution of the current script without error. If this is run before anything is assigned toOutput.cart, the script has no effect. This is a useful way to exit scripts, for example, if the customer is ineligible to run the script.

Kernel example

customer=Input.cart.customerifcustomer&&customer.email.end_with?("@mycompany.com")# Employees are not eligible for this promotion.exitend

Line item methods

The following methods are only usable in行项目的脚本:

Cart

Script methods using the Cart object in line item scripts
Method Return type Description
.subtotal_price_was Money Returns the subtotal price of the cart before any discounts were applied.
.subtotal_price_changed? Boolean Returns whether the subtotal price has changed.

LineItem

脚本使用LineItem对象行我的方法tem scripts
Method Return type Description
.change_line_price(Moneynew_price, { message:String}) Money Change the price of the line item to the amount specified. Amessageis required.new_pricemust be lower than the current price.
.original_line_price Money Returns the original price of the line item before scripts and discounts were applied.
.line_price_was Money Returns the price of the line item before changes were applied by the current script.
.line_price_changed? Boolean Returns whether the price of the line item has changed.
.change_properties(hashnew_properties, { message:String}) hash Sets new properties for a line item. The original properties hash is stored inproperties_wasand the properties hash that is passed to the method becomes the new properties for the line item.
.properties_was hash Returns the original properties hash of the line item before any changes were applied.
.properties_changed? Boolean Returns whether the properties for the line item have been changed.
.split({ take:Integer}) LineItem Splits a line item into two line items.takespecifies what quantity to remove from the original line item to create the new line item.

.split穰mple

This example script splits a line item calledoriginal_line_iteminto two line items. The new line item has a quantity of 1 (specified bytake: 1). The script then applies a discounted price to the new line item with the message "Third hat for 5 dollars".

iforiginal_line_item.quantity>=3new_line_item=original_line_item.split(take:1)new_line_item.change_line_price(Money.new(cents:500),message:"Third hat for 5 dollars")cart.line_items<<new_line_itemend

Variant

Script methods using the Variant object in line item scripts
Method Return type Description
.compare_at_price Money Returns the compare-at price of the variant. Returnsnilif the variant doesn't have a compare-at price.

Shipping methods

The following methods are usable inshipping scripts:

Input

Script methods using the Input object in shipping scripts
Method Return type Description
.shipping_rates ShippingRateList Returns a list of all the shipping rates.

ShippingRateList

Script methods using the ShippingRateList object in shipping scripts
Method Return type Description
.delete_if ShippingRateList Delete shipping rates using an optional code block. See the documentation forRuby'sdelete_ifmethod.
.sort! ShippingRateList Sort the shipping rates using the comparison operator or using an optional code block. See the documentation forRuby'ssort!method.
.sort_by! ShippingRateList 车辆使用一个可选的运费代码ck. See the documentation forRuby'ssort_by!method.

ShippingRate

Script methods using the ShippingRate object in shipping scripts
Method Return type Description
.code String Returns the code of the shipping rate.
.markup Money Returns the markup for a shipping rate, if applicable.
.name String Returns the name of the shipping rate. It can be modified by using thechange_namemethod.
.price Money Returns the price of the shipping rate.
.source String Returns the source (the carrier) associated with the shipping rate, if relevant. It can't be modified.
.change_name(Stringnew_name) String Changes the name (maximum of 255 characters) of the shipping rate. It's not possible to change, delete or hide the source.
.apply_discount(Moneydiscount, { message: String }) Money Applies a discount of the specified fixed amount. The price cannot be reduced below 0. A message is required.
.phone_required? Boolean Returnstrueif a phone number is required to get the shipping rate, orfalseif a phone number is not required.

Payment methods

The following methods are usable inpayment scripts:

Input

Script methods using the Input object in payment scripts
Method Return type Description
.payment_gateways PaymentGatewaysList Returns a list of all the payment gateways in the store.

PaymentGatewayList

Script methods using the PaymentGatewayList object in payment scripts
Method Return type Description
.delete_if PaymentGatewayList Delete payment gateways using an optional code block. See the documentation forRuby'sdelete_ifmethod.
.sort! PaymentGatewayList Sort the payment gateways using the comparison operator or using an optional code block. See the documentation forRuby'ssort!method.
.sort_by! PaymentGatewayList Sort the payment gateways using an optional code block. See the documentation forRuby'ssort_by!method.

PaymentGateway

Method Return type Description
.name String Returns the name of the payment gateway.
.enabled_card_brands List

If the payment gateway supports credit cards, returns a list of the credit card types that the store accepts. If the gateway doesn't support credit cards, returns an empty list.

.change_name(Stringnew_name) String Changes the name of the payment gateway. Payment gateways with logos can't be renamed.

Examples

In the following line item script example, when a customer orders a product that is not a gift card, then the price of the product is reduced by $9. Also, the total amount that the customer has spent throughout all visits to your store is shown:

customer = Input.cart.customer Input.cart.line_items.each do |line_item| product = line_item.variant.product next if product.gift_card? line_item.change_line_price(line_item.line_price - Money.new(cents: 900), message: customer.total_spent) end Output.cart = Input.cart

Learn more

Learn more about:

Ready to start selling with Shopify?

Try it free