Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lukeholder/9fe5bbceeb37423291c6904f7ba8cd56 to your computer and use it in GitHub Desktop.
Save lukeholder/9fe5bbceeb37423291c6904f7ba8cd56 to your computer and use it in GitHub Desktop.
Creating test order in Craft Commerce
<?php
namespace Craft;
$craft = require '../craft/app/bootstrap.php';
$craft->plugins->loadPlugins();
$productIds = craft()->elements->getCriteria('Commerce_Product', ['limit' => null])->ids();
// Configuration
$customerId = 1; // real customer with email address set
$productId = $productIds[array_rand($productIds)];
$productQuantity = rand(1,5);
$paymentMethodId = 1;
$shippingMethodHandle = 'myHandle';
$order = new Commerce_OrderModel();
$order->number = md5(uniqid(mt_rand(), true));
$order->currency = craft()->commerce_paymentCurrencies->getPrimaryPaymentCurrencyIso();
$order->paymentCurrency = craft()->commerce_paymentCurrencies->getPrimaryPaymentCurrencyIso();
// Get products
$product = craft()->commerce_products->getProductById($productId);
$customer = craft()->commerce_customers->getCustomerById($customerId);
if ($customer)
{
if ($address = $customer->getAddresses()[0])
{
$order->setShippingAddress($address);
$order->setBillingAddress($address);
}
$order->customerId = $customerId;
}
$order->paymentMethodId = $paymentMethodId;
$order->shippingMethod = $shippingMethodHandle;
craft()->commerce_orders->saveOrder($order);
$success = craft()->commerce_cart->addToCart($order, $product->getDefaultVariant()->id, $productQuantity, '', $options = [ ], $error);
if (!$success)
{
echo $error;
$craft->end();
}
$success = craft()->commerce_orders->completeOrder($order);
if (!$success)
{
echo "Could’t complete order: <a href='".$order->getCpEditUrl()."'>".$order->number."</a>'";
}else{
echo "Created order: <a href='".$order->getCpEditUrl()."'>".$order->number."</a>'";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment