|
2 | 2 | description: Learn how to create an order via code in Umbraco Commerce. |
3 | 3 | --- |
4 | 4 |
|
5 | | -# Create an Order via Code |
| 5 | +# Create an Order via Code |
| 6 | + |
| 7 | +It is sometimes necessary, such as when importing orders from another system, to create a fully finalized order via code. |
| 8 | + |
| 9 | +An example of the code to do this is shown below. Here the `api` variable is an instance of the `IUmbracoCommerceApi` interface, which is an injectable service you access via [dependency injection](../key-concepts/dependency-injection.md). |
| 10 | + |
| 11 | +```csharp |
| 12 | +await api.Uow.ExecuteAsync(async (uow) => |
| 13 | +{ |
| 14 | + // Fetch the store |
| 15 | + var store = await api.GetStoreAsync("blendid"); |
| 16 | + |
| 17 | + // Create or get the current order |
| 18 | + var order = await api.GetOrCreateCurrentOrderAsync(store.Id).AsWritableAsync(uow); |
| 19 | + |
| 20 | + // Add product |
| 21 | + var productId = "2fa949e4-2acb-4aef-bb7c-4d3a5f7bbe52"; // The product node Key |
| 22 | + await order.AddProductAsync(productId, null, 1); |
| 23 | + |
| 24 | + // Set customer details |
| 25 | + var country = await api.GetCountryAsync(store.Id, "GB"); |
| 26 | + await order.SetPropertiesAsync(new Dictionary<string, string> |
| 27 | + { |
| 28 | + { Constants. Properties. Customer. EmailPropertyAlias, $"[email protected]" }, |
| 29 | + { "marketingOptIn", "0" }, |
| 30 | + { Constants.Properties.Customer.FirstNamePropertyAlias, "Example" }, |
| 31 | + { Constants.Properties.Customer.LastNamePropertyAlias, $"Customer" }, |
| 32 | + { "billingAddressLine1", "10 Example Road" }, |
| 33 | + { "billingCity", "Example City" }, |
| 34 | + { "billingZipCode", "EX3 3PL" }, |
| 35 | + { "billingTelephone", "0123456789" }, |
| 36 | + { "shippingSameAsBilling", "1" } |
| 37 | + }) |
| 38 | + .SetPaymentCountryRegionAsync(country, null) |
| 39 | + .SetShippingCountryRegionAsync(country, null); |
| 40 | + |
| 41 | + // Set shipping method |
| 42 | + var shippingMethod = await api.GetShippingMethodAsync(store.Id, "pickup"); |
| 43 | + await order.SetShippingMethodAsync(shippingMethod); |
| 44 | + |
| 45 | + // Set payment method |
| 46 | + var paymentMethod = await api.GetPaymentMethodAsync(store.Id, "invoicing"); |
| 47 | + await order.SetPaymentMethodAsync(paymentMethod); |
| 48 | + |
| 49 | + // Recalculate order |
| 50 | + await order.RecalculateAsync(); |
| 51 | + |
| 52 | + // Finalize order |
| 53 | + await order.InitializeTransactionAsync(); |
| 54 | + await order.FinalizeAsync(order.TransactionAmount.Value, Guid.NewGuid().ToString("N"), PaymentStatus.Authorized); |
| 55 | + |
| 56 | + // Save order |
| 57 | + await api.SaveOrderAsync(order); |
| 58 | + |
| 59 | + // Commit the unit of work |
| 60 | + uow.Complete(); |
| 61 | +}); |
| 62 | +``` |
0 commit comments