This article describes how you can create new voucher codes also known as promo codes for the Ucommerce Promotion Engine from code. 


Instruction


Step-by-step guide

  • Step 1: Setting up the Promotion for the Vouchers
  • Step 2: Generating the voucher code or codes
  • Step 3: Save the voucher codes


Step 1: Setting up the Promotion for the Vouchers

Vouchers codes in what we call a Criteria in the Ucommerce Promotion Engine, which is something the customer needs to fulfill in order to receive a discount. You can find more information about this here.


This means that we need to ensure that we have a Promotion in place. Which we then can associate with the voucher codes. 


Read more about the configuration of Promotion here.


Step 2: Generating the voucher code or codes

Now it is time to create the actaully vourche code that can be shared with the customer. 


The requirements for during this, is to have a unique string contianing the voucher code. 

var voucherCode = "summer-is-coming";

or you can generate mulitiple voucher codes 

var generatedCodes = ObjectFactory.Instance.Resolve<IVoucherCodeGenerator>()
.GenerateCodes(numberToGenerate, codeLength, prefix, suffix);


Step 3: Save the voucher codes

When the codes has been generated it is time establish the assiociation to the Promotion and save them in the database. 


This don't prevent you for creating duplicated voucher codes. In order to ensure this doesn't happens you can delete any voucher code already present with the code or avoid creating it if the code already has been used. See below how you can delete duplicates.


We need to specify which Promotion the voucher codes should be relate to by creating a VoucherTarget. 

var voucherTargetRepo = ObjectFactory.Instance.Resolve<IRepository<VoucherTarget>>();

var voucherTarget = new VoucherTarget
{
    CampaignItem = promotion,
    EnabledForApply = true
};

voucherTargetRepo.Save(voucherTarget);

Then you need to specify the max number of usages per voucher code:

var voucherCodeRequest = new CreatePromoCodeRequest();
voucherCodeRequest.Code = voucherCode;
voucherCodeRequest.MaxUses = 2;

Now you are ready to save it to the database:

var args = new InsertPromoCodesQueryArgs
{
    PromoCodesWithMaxUses = new List<CreatePromoCodeRequest>(){ voucherCodeRequest },
    VoucherTargetId = voucherTarget.TargetId
};
var insertPromoCodesQuery = ObjectFactory.Instance.Resolve<IQuery<InsertPromoCodesQueryArgs, InsertPromoCodesQueryResult>>();
var result = insertPromoCodesQuery.Execute(args);


To ensure you don't have any duplicated voucher code, you can execute the following query:

var deleteAllDuplicateVoucherCodesQuery = ObjectFactory.Instance.Resolve<IQuery<DeleteAllDuplicateVoucherCodesQueryArgs, DeleteAllDuplicateVoucherCodesQueryResult>>();
deleteAllDuplicateVoucherCodesQuery.Execute(new DeleteAllDuplicateVoucherCodesQueryArgs());