Referral Coupons¶
Barberklingen\BasePlugin\Modules\ReferralCoupons\ReferralCouponsModule
Generates and validates referral discount coupons. Each coupon is a standard WooCommerce coupon with a 100 % discount restricted to specific products, flagged with _referral meta for easy lookup.
Activating the module¶
Creating a coupon¶
use Barberklingen\BasePlugin\Modules\ReferralCoupons\Helpers\ReferralCoupon;
$coupon = ReferralCoupon::create(
product_ids: [123, 456], // restrict to these products
single_usage: true, // set usage_limit = 1
expiration_timestamp: strtotime('+30 days')
);
// $coupon->get_code() → random 8-char code
Codes are generated as 8-character random strings (VOUCHER_CODE_LENGTH = 8) with a uniqueness check against wc_get_coupon_id_by_code().
Listing all referral coupons¶
Returns every coupon with _referral meta set.
Starter kit products¶
The set of products a referral coupon applies to by default can be declared via a filter:
ReferralCoupon::get_starter_kit_product_ids() reads this filter.
Validation¶
ReferralCouponValidator is used both in the AJAX validation endpoint and at checkout:
use Barberklingen\BasePlugin\Modules\ReferralCoupons\Helpers\ReferralCouponValidator;
$validator = new ReferralCouponValidator($userId); // null = anonymous
$validator->is_coupon_valid(new WC_Coupon($code)); // throws on failure
An AJAX endpoint (ReferralCouponsValidationEndpoint) exposes the same check to JavaScript.
Checkout integration¶
The module hooks into the flow-checkout/subscription/before-create/context-referral-coupon action to validate the coupon before the subscription is created:
// Fired by the checkout flow when context = 'referral-coupon'
do_action('flow-checkout/subscription/before-create/context-referral-coupon', $validator);
If the coupon is empty or invalid, a RuntimeException is thrown to abort the checkout.
WP-CLI commands¶
wp referral-coupons generate --product-ids=123,456 --single-usage
wp referral-coupons list
wp referral-coupons delete <code>
Commands are registered by ReferralCoupons\CLI\CLIModule.