Skip to content

Instantly share code, notes, and snippets.

@skyred
Last active November 24, 2016 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skyred/102288a4f1487fa4dd7851109e051d3b to your computer and use it in GitHub Desktop.
Save skyred/102288a4f1487fa4dd7851109e051d3b to your computer and use it in GitHub Desktop.
Programmatically creates CommerceOrder on D8
// {
// "mail": "testrest@test.com",
// "uid": 1,
// "store_id": 1,
// "order_items": [
// {"title": "restTitle1", "quantity": 2, "unit_price": {"number": "23.45", "currency_code": "CNY"}, "total_price": {"number": "46.9", "currency_code": "CNY"}},
// {"title": "restTitle2", "quantity": 3, "unit_price": {"number": "10.01", "currency_code": "CNY"}, "total_price": {"number": "30.03", "currency_code": "CNY"}},
// {"title": "restTitle3", "quantity": 4, "unit_price": {"number": "0.2", "currency_code": "CNY"}, "total_price": {"number": "0.8", "currency_code": "CNY"}}
// ]
// }
/** Command to test
* curl -X POST -H "Authorization: Basic dGVzdDp0ZXN0" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
* "mail": "testrest@test.com",
* "uid": 1,
* "store_id": 1,
* "field_de_business_id": 43,
* "field_de_store_id": 75,
* "placed": 1420070400,
* "order_items": [
* {"title": "restTitle1", "quantity": 2, "unit_price": {"number": "23.45", "currency_code": "CNY"}, "total_price": {"number": "46.9", "currency_code": "CNY"}},
* {"title": "restTitle2", "quantity": 3, "unit_price": {"number": "10.01", "currency_code": "CNY"}, "total_price": {"number": "30.03", "currency_code": "CNY"}},
* {"title": "restTitle3", "quantity": 4, "unit_price": {"number": "0.2", "currency_code": "CNY"}, "total_price": {"number": "0.8", "currency_code": "CNY"}}
* ]
* }' "http://insready.com:8080/custom/entity/commerce_order"
*/
public function post($body, $request) {
$order_data = [
'type' => 'default',
'mail' => $body['mail'],
'uid' => [$body['uid']],
'store_id' => [$body['store_id']],
];
if (!empty($body['custom_placed_date']) && !empty($body['placed'])) {
$order_data['placed'] = $body['placed']->getTimestamp();
}
$order = Order::create($order_data);
$order->save();
foreach ($body['order_items'] as $item) {
$item['order_id'] = intval($order->id());
$item['type'] = 'default';
$order_item = OrderItem::create($item);
$order_item->save();
$order->addItem($order_item);
}
$order->save();
return new ResourceResponse("{'order_id': " . $order->id() ."}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment