Doing this for a particular order is pretty straightforward. All you need to have is the coupon code ID:
// This is the ID of the coupon code you want to add to the order. $coupon_id = 1; /** @var \Drupal\commerce_order\Entity\OrderInterface $order */ $order = \Drupal\commerce_order\Entity\Order::load(1); $order->get('coupons')->appendItem($coupon_id); $order->save();
Doing this for the shopping cart involves a bit more boilerplate code to set things up:
// This is the ID of the coupon code you want to add to the order. $coupon_id = 1; /** @var \Drupal\commerce_cart\CartManager $cart_manager */ $cart_manager = \Drupal::service('commerce_cart.cart_manager'); /** @var \Drupal\commerce_cart\CartProvider $cart_provider */ $cart_provider = \Drupal::service('commerce_cart.cart_provider'); /** @var \Drupal\commerce_store\Entity\Store $store */ $store = \Drupal::service('commerce_store.current_store')->getStore(); /** @var \Drupal\commerce_order\Entity\OrderInterface $cart */ $cart = $cart_provider->getCart('default', $store); // Finally, add the coupon and save changes in the order. $cart->get('coupons')->appendItem($coupon_id); $cart->save();