lmsqueezy / laravel

A package to easily integrate your Laravel application with Lemon Squeezy.
https://lemonsqueezy.com
MIT License
520 stars 51 forks source link

Cast variant_id before saving #81

Closed matthiasweiss closed 8 months ago

matthiasweiss commented 8 months ago

Hi 😁

First of all I wanna thank you for this great package!

I ran into an issue where I had the following code in a listener of the OrderCreated event:

        $variantId = config("some.key");

        if (! $event->order->hasVariant($variantId)) {
            $message = sprintf('Invalid variant ID: %s', $event->order->variant_id);
            throw new Exception($message);
        }

This check always returned false, thus throwing the exception. I then double checked if I had messed up my environment variables or something else, but it turned out that the variant_id was of type integer, which I found out by logging gettype($event->order->variant_id).

This kind of makes sense, since the WebhookController receives the following data within the webhook (I replaced my actual variant ID with 123456):

{
  "data": {
    ...
    "attributes": {
      ...
      "first_order_item": {
        ...
        "variant_id": 123456,
       }
    }
  }
}

The important part here is that the variant_id is returned as an integer in the webhook payload.

Since the WebhookController simply creates an instance of the order model and dispatches it, the event listener receives the model with a variant_id that has an integer type. This results in the $event->order->hasVariant($variantId) check to always return false, since the method checks using strict equality, but $this->variant_id is of type number and the argument passed into the method is of type string. A quick solution for this would be to convert the variant_id to a string when creating the order.

Best, Matthias

driesvints commented 8 months ago

Thanks!