I'm currently having some issue with a coupon creation in the payment_complete hook.
add_action('woocommerce_payment_complete', 'when_payment_complete');
function when_payment_complete( $order_id ) {
$referral_coupon = new WC_Coupon();
$bytes = random_bytes(8);
$encoded = base64_encode($bytes);
$stripped = str_replace(['=', '+', '/'], '', $encoded);
$stripped = strtoupper($stripped);
$prefix = strtoupper(substr(md5($user->user_email), 0, 3));
$referral_coupon->set_code( 'CHILO-REF-' . $prefix . $stripped );
$referral_coupon->set_description( 'TEST REFERRAL COUPON' );
$referral_coupon->set_discount_type( 'fixed_cart' );
$referral_coupon->set_amount( 50 );
$referral_coupon->set_status( "publish" );
$referral_coupon->set_individual_use(false);
$referral_coupon->set_usage_limit( 0 );
$referral_coupon->save();
}
The same block of code is used in a wordpress script and is working perfectly fine.
I don't know shy the coupon is never created
In your code,
$useris not defined and$user->user_emailcan be replaced with the billing email from the order. So maybe try:Code goes in functions.php file of your child theme (or in a plugin). It could work.
If it doesn't work, what you can do, is to use an alternative to
woocommerce_payment_completehook with the following, targeting instead paid order statuses and flagging the order when the coupon is created (avoiding multiple coupons creation):Code goes in functions.php file of your child theme (or in a plugin). It should work.