1

I have a digital product, with a landing page, and I want to know if the connected user has already bought the product so I can give him access to the content.

3 Answers 3

1

There is a direct way to find this out.

Here's an example. Note the id you supply must be the specific purchasableId, not the product id (so the defaultVariant.id or variant.id).

{# Has the customer explicitly bought the XXX product? Returns 0 (==false) or >= 1 (==true) #}

{% set purchasedXXX = craft.orders()
    .user(currentUser)
    .hasPurchasables(10637)
    .isCompleted()
    .count()
%}

You can then use that as just

{% if purchasedXXX %}
 ...
{% endif %}
1

Jeremy's answer is right, but for people using the Digital Products plugin, this command might be a better fit:

{# Has the customer explicitly bought the XXX product? Returns 0 (==false) or >= 1 (==true) #}
{% set licenses = craft.digitalProducts
    .licenses
    .owner(currentUser)
    .product(productID)
    .count()
%}
0

Try something like this:

  {% set found = false %}
  {% set orders = craft.orders()
    .customer(craft.commerce.customer)
    .all() %}
  {% for order in orders %}
    // here you could / should also check if the order was paid
    {% for lineItem in order.lineItems %}
      {% if lineItem.purchasableId == yourProductId %}
        {% set found = true %}
      {% endif %}
    {% endfor %}
  {% endfor %}
  {% if found %}
      // user has bought product before 
  {% endif %}

There might be more efficient query-wise.

1
  • There's a much more direct way available with recent Commerce versions, see my answer. Commented Sep 16, 2020 at 2:32

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.