3

How can I pass in a quantity value while creating a subscription?


Plugin (version):

  • Craft CMS (3.1.21)

  • Craft Commerce (2.1.2)

  • Stripe for Craft Commerce (1.2.0)


Problem: My website allows users to subscribe to meal plans. For example, a user can subscribe to receive 5 vegetarian meals per week. Another user may also subscribe to recieve 10 meals per week. Currently, I must create two subscritpion plans on Stripe and on Craft (i.e Vegetarian-5 and Vegetarian-10). Stripe's API offers the ability to create a single plan that charges per quantity (i.e I want to create one Vegetarian Plan and charge $10 per meal).

I wrote a plugin that uses createSubscription() from craft\commerce\services. However, ideally I want to send a quantity value but after reviewing Craft's logic for this function, I am unable to figure out a way to pass in a quantity value. However, I could easily bypass Craft and use the Stripe's API to do this (setting subscription quantity through stripe API) but that feels like the wrong solution.

5

I realize that this is an older question, but I have found the answer for it after much searching, and want to leave this answer for others who might be coming from a search engine.

The way I have found that you would do this is with the Stripe Payments plugin. The documentation for it can be found at https://github.com/craftcms/commerce-stripe.

From there, you will find that there is a beforeSubscribe event. You can use that to set parameters for quantity. From the documentation:

use craft\commerce\stripe\events\SubscriptionRequestEvent;
use craft\commerce\stripe\base\SubscriptionGateway as StripeGateway;
use yii\base\Event;

Event::on(StripeGateway::class, StripeGateway::EVENT_BEFORE_SUBSCRIBE, function(SubscriptionRequestEvent $e) {
    $e->parameters['someKey'] = 'some value';
    unset($e->parameters['unneededKey']);
});

For my subscription, I have found that $e->parameters['items'][0]['quantity'] = 3; works for my setup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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