Forked from sjelfull/create-test-order-in-craft-commerce.php
Last active
July 14, 2018 01:27
-
-
Save lukeholder/9fe5bbceeb37423291c6904f7ba8cd56 to your computer and use it in GitHub Desktop.
Creating test order in Craft Commerce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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