1

I am trying to apply a coupon code to a users session so that when they add a product to the cart and go to check the coupon is automatically applied to the cart.

This thing is that the user comes from a 3rd party system to a specific hidden url and based on some url parameters we will apply different coupon codes. The problem is that at this point the user does not have any products in their cart.

I found this and it works but only if you already have products in the cart. If a user go to this url and then adds a product to the cart the coupon code is not applied. Any ideas how this can be accomplished?

http://www.example.com/checkout/cart/couponPost/coupon_code/somecode/?return_url=http://www.example.com/products

1 Answer 1

0

One possible solution to this problem is to use events and observers in Magento 2. Events and observers are a way to execute custom code when a specific action occurs in the system, such as adding a product to the cart, placing an order, or creating a customer. You can use events and observers to apply the coupon code to the user session when the user adds a product to the cart, regardless of whether they have visited the hidden URL or not.

To use events and observers in Magento 2, you need to do the following steps:

• Identify the event that you want to observe. For example, if you want to apply the coupon code when the user adds a product to the cart, you can use the checkout_cart_product_add_after event

• Create an observer class that implements the Magento\Framework\Event\ObserverInterface interface and defines the execute method. This is where you write your custom code that will apply the coupon code to the user session. For example, you can create a class called ApplyCouponCode in your custom module's Model folder

• Declare your observer in the events.xml file in your custom module's etc folder. You need to specify the event name, the observer name, and the observer class. For example, you can create a file called events.xml in your custom module's etc/frontend folder and add the following code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
  <event name="checkout_cart_product_add_after">
      <observer name="apply_coupon_code"
                instance="Vendor\Module\Model\ApplyCouponCode" />
  </event>
</config>

• Clear the cache and test your observer.

But if you want to use hidden URL like this 1 https://{{your_website_url}}/applydiscount/?code={{Coupon_code}}&redirect_url={{Url of any page on your website}} then I would recommend to use Automatically apply coupon code extension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.