How to Create Coupon (Discount) code Programmatically Magento 2?

Create Coupon Programmatically in Magento 2 is the process of first create a Sales rule with basic details, next get rule id and apply rule id to the generate the new coupon.

Create Sales Rule using Magento\SalesRule\Api\Data\RuleInterfaceFactory and Coupon using Magento\SalesRule\Api\Data\CouponInterface.

We will create a coupon code with 20FIXED, When you applied this coupon from the cart page, It will be given a discount of $20 for the whole cart.

<?php
namespace Jesadiya\Coupon\Model;

use Exception;
use Psr\Log\LoggerInterface;
use Magento\SalesRule\Api\Data\RuleInterface;
use Magento\SalesRule\Api\Data\CouponInterface;
use Magento\Framework\Exception\InputException;
use Magento\SalesRule\Api\RuleRepositoryInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\SalesRule\Api\CouponRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\SalesRule\Api\Data\RuleInterfaceFactory;

class Coupon
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var CouponRepositoryInterface
     */
    protected $couponRepository;

    /**
     * @var RuleRepositoryInterface
     */
    protected $ruleRepository;

    /**
     * @var Rule
     */
    protected $rule;

    /**
     * @var CouponInterface
     */
    protected $coupon;

    public function __construct(
        CouponRepositoryInterface $couponRepository,
        RuleRepositoryInterface $ruleRepository,
        RuleInterfaceFactory $rule,
        CouponInterface $coupon,
        LoggerInterface $logger
    ) {
        $this->couponRepository = $couponRepository;
        $this->ruleRepository = $ruleRepository;
        $this->rule = $rule;
        $this->coupon = $coupon;
        $this->logger = $logger;
    }

    /**
     * Create Rule
     *
     * @return void
     */
    public function createRule()
    {
        $newRule = $this->rule->create();
        $newRule->setName('20$ discount')
            ->setDescription("20% Discount on applied rule")
            ->setIsAdvanced(true)
            ->setStopRulesProcessing(false)
            ->setDiscountQty(20)
            ->setCustomerGroupIds([0, 1, 2])
            ->setWebsiteIds([1])
            ->setIsRss(1)
            ->setUsesPerCoupon(0)
            ->setDiscountStep(0)
            ->setCouponType(RuleInterface::COUPON_TYPE_SPECIFIC_COUPON)
            ->setSimpleAction(RuleInterface::DISCOUNT_ACTION_FIXED_AMOUNT_FOR_CART)
            ->setDiscountAmount(20)
            ->setIsActive(true);

        try {
            $ruleCreate = $this->ruleRepository->save($newRule);
            //If rule generated, Create new Coupon by rule id
            if ($ruleCreate->getRuleId()) {
                $this->createCoupon($ruleCreate->getRuleId());
            }
        } catch (Exception $exception) {
            $this->logger->error($exception->getMessage());
        }
    }

    /**
     * Create Coupon by Rule id.
     *
     * @param int $ruleId
     *
     * @return int|null
     * @throws InputException
     * @throws LocalizedException
     * @throws NoSuchEntityException
     */
    public function createCoupon(int $ruleId) {
        /** @var CouponInterface $coupon */
        $coupon = $this->coupon;
        $coupon->setCode('20FIXED')
            ->setIsPrimary(1)
            ->setRuleId($ruleId);

        /** @var CouponRepositoryInterface $couponRepository */
        $coupon = $this->couponRepository->save($coupon);
        return $coupon->getCouponId();
    }
}

Coupon code

Now When you check the admin panel, Marketing -> Promotions -> Cart Price rules,

You have displayed a new Shopping cart rule with the sales rule grid.

You can set Coupon type as per your needs. In the above demo, We have used action type is Fixed amount discount for whole cart (cart_fixed).

You can see a list of all the actions apply conditions from the Magento\SalesRule\Api\Data\RuleInterface.

You can Create Coupon Dynamically using the above code approach with required changes on the code.

coupon action