Stripe Subscription Plans of Varying Amounts - ruby

I am working on a donation form for a charity and they have requested a monthly donation plan where the user can choose whatever amount they would like to give.
I know I can make individual plans (i.e. if they said monthly donations of $5, $10, or $20 dollars) I could make three different plans and subscribe users to them. Is there a way to avoid making new plans for every varying subscription amount?

The Stripe documentation recommends using the quantity parameter on the subscription.
https://stripe.com/docs/guides/subscriptions
Varying billing amounts
Some users need full flexibility in computing billing amounts. For
example, you might have a conceptual subscription that has a base cost
of $10 per month, and a $5 per-seat cost each month. We recommend
representing these billing relationships by creating a base plan that
is only $1 per month, or even $0.01 per month. This lets you use
quantity parameter to bill each user very flexibly. In an example
with a $10 base cost and three $5 seats, you could use a $1 per month
base plan, and set quantity=25 to achieve the desired total cost of
$25 for the month.

I don't think you can do it with Stripe.
What you can do is keep using Stripe and dynamically build the subscription plans using Stripe API or move to PayPal and use their Preapproval operation.
https://developer.paypal.com/docs/classic/api/adaptive-payments/Preapproval_API_Operation/

Your question seems self-defeating -- you can't have subscriptions of varying amounts without creating the corresponding plans!
The simplest way to handle recurring donations of varying amounts would be to create one plan per donator. For instance, you could do something like this:
# Create the plan for this donator
plan = Stripe::Plan.create(
:amount => params[:amount],
:currency => 'usd',
:interval => 'month',
:name => 'Donation plan for #{params[:stripeEmail]}',
:id => 'plan_#{params[:stripeEmail]}'
)
# Create the customer object and immediately subscribe them to the plan
customer = Stripe::Customer.create(
:source => params[:stripeToken],
:email => params[:stripeEmail],
:plan => plan.id
)
If you wish to avoid creating unnecessary plans, you could simply check if an appropriate plan already exists. The simplest way to do so would be to use a naming convention that includes the amount. For instance:
plan_id = '#{params[:amount]}_monthly'
begin
# Try to retrieve the plan for this amount, if one already exists
plan = Stripe::Plan.retrieve(plan_id)
rescue Stripe:: InvalidRequestError => e
# No plan found for this amount: create the plan
plan = Stripe::Plan.create(
:amount => params[:amount],
:currency => 'usd',
:interval => 'month',
:name => "$#{'%.02f' % (params[:amount] / 100.0)} / month donation plan",
:id => plan_id
)
# Create the customer object as in the previous example
(Note that in both these examples, I assumed that params[:amount] would be the donation's amount, as an integer in cents.)

Related

How to add filter on item collection to get the Sales rep(total Quantity and Total no of Orders) of those Sale Managers which are logged in

$collection = $this->_itemCollectionFactory->create()->getCollection();
$collection->getSelect()->columns(array('total_orders' => new \Zend_Db_Expr('COUNT(order_id)')))
->columns(array('total_qty' => new \Zend_Db_Expr('ROUND(SUM(qty_ordered))')))
->group('sku');
$collection->getSelect()->limit(3);
$collection->addFieldToFilter('store_id', 2);
Through this code i can get the total quantity and total number of orders of all sales rep. But i need only those total quantity and total orders which were done by the Sales Rep og Logged in Sale Manager.
As you mentioned in your question you only want to get the order info based on a certain sales rep. To do that you need to somehow find a unique identify for the currently logged in sales rep and add a filter for that .
For example:
$collection = $this->_itemCollectionFactory->create()->getCollection();
$collection->getSelect()->columns(array('total_orders' => new \Zend_Db_Expr('COUNT(order_id)')))
->columns(array('total_qty' => new \Zend_Db_Expr('ROUND(SUM(qty_ordered))')))
->group('sku');
$collection->getSelect()->limit(3);
$collection->addFieldToFilter('store_id', 2);
$collection->addFieldToFilter('sales_rep_identifier', $loggedInSalesRepIdentifier);
The label sales_rep_identifier and the value $loggedInSalesRepIdentifier are just examples, you may have to adjust the format in which the data is stored if it doesn't currently have a field to check natively what sales rep did it, and adjust the values there accordingly
If you're using some kind of prebuilt system then maybe there are other labels for the identifier you could use, without more information on the specific database structure it's impossible to answer exactly, but essentially you need to filter by the unique sales rep identifier, and if that doesn't exist now in the database it should somehow but added

Laravel cashier + Stripe : creating a plan with quantity and decreasing prices

I'm whiling for one of my project to create a subscription system with Laravel Cashier and Stripe.
We will offer one plan to our users : 10€ / month for one location (they can add locations in the system) and for 75 followers.
What I want to do, is to make them pay more for locations : 2.5€ / locations / month for example, so this can be achieve with quantities ? But still, if the basic plan is at 10€ and I put 2 as a quantity, total price will be 20€ ?
Then price will be also based on their followers. 75 are included in the basic price. But then if they want more, they will also have to pay.
Example :
76-150 : + 4.95€ a month
151-250 : + 4.80€ a month etc ...
How can I handle that and make sure the customer will have to pay everything in one shot ?
Thanks in advance !
My advice would be to;
Calculate the total charge in your own logic,
Initiate a 'once-off' payment by first creating a customer object,
Then creating a charge!
Easy as 1,2,3 :D
Here's a tutorial from Stripes documentation on creating payments.
https://stripe.com/docs/charges
If you would like to add the user to a plan (subscription), see the below example (in PHP).
$customer = \Stripe\Customer::create(array(
"source" => $tokenID,
"plan" => $plan,
"email" => $email,
"coupon" => $coupon
));
I would use my front or back end to calculate:
price
discount rate
When the calculation is done, you can create your subscription with the right quantity and price, and discount rate (discount coupon).
$user->newSubscription('main', 'main')
->quantity($quantity)
->withCoupon($coupon)
->create($token, ['email' => $user->email]);

Save API response data daily without overwriting

UPDATED
I have setup a model Graph with a single attribute, :data
I request, for eg, Facebook page and store the likes in data.
How can I schedule that API call everyday, such that two things are achievable
1. Value stored in :data is a hash of key - updated_at and value :data. This hash being added with value everyday without risk of overwriting.
2. All the :data stored everyday can be recalled in a page and presented like a monthly graph, or a calculation is done, for eg, to show avg likes per day, etc.
Controller
def index
#fb = Graph.fb_page("facebook")
#data = Graph.new(:fb => [#fb])
#data.save
end

How do I charge an account in the Stripe Connected Accounts API?

How do I charge an account's external account in the Stripe Connected Accounts API?
I create invoices on my system then I want to let the users pay them.
On the first screen I list their payment accounts that are saved on the system. This will be bank accounts, credit cards, debit cards.
When they select the account to pay with this is where my trouble starts.
Here is my code
def pay_invoice invoice_id, source_id
invoice = Invoice.find(invoice_id)
account = Stripe::Account.retrieve(#account)
charge_source = account.external_accounts.retrieve(source_id)
c = Stripe::Charge.create(
:amount => invoice.cents,
:currency => "usd",
#:customer => #account,
:source => charge_source,
:description => "Charge for invoice ##{invoice_id}"
)
end
the source_id passed in to the method is the id of the external account I got earlier.
My first attempt was to pass that as the source and I got the error "No such token"
From what I can tell there is no good way to charge accounts through the connected accounts API.
I'm going to make a Stripe account for each user and also a Stripe contact for each user.
Then the code ends up looking like this:
def pay_invoice invoice_id, source_id
invoice = Invoice.find(invoice_id)
c = Stripe::Customer.retrieve(#customer_id)
paying_source = nil
c.sources.each do | source|
if source.id == source_id
paying_source = source
end
end
c = Stripe::Charge.create(
:amount => invoice.cents,
:currency => "usd",
:customer => c,
:source => paying_source,
:description => "Charge for invoice ##{invoice_id}"
)
invoice.status = "paid"
invoice.save
end
When you take Credit/debit card from user Stripe returns a Token and you can do two things
1. You can charge the customer for one time and the token will expire.
2. Create customer using that token and save for future payments So using this way you can make further charges
Here you are using that token for charge and it is getting expire so next same token is giving error.

Finding out when an order status has been set to completed

I'm selling virtual products in my store where my customers buy a subscription for sth. This subscription is valid for 31 days beginning with the day when the order has been completed.
How do I find out the day when the order status had been set to completed?
My Idea was to look for the "updated_at" field of an order but I'm unsure if this is the right way to determine when the order was completed.
$sales_model = Mage::getModel("sales/order");
$all_orders = $sales_model -> getCollection()
->addFieldToFilter('status', 'complete')
->addAttributeToFilter('updated_at', array(
'from' => $one_month_ago,
'to' => date('Y-m-d 24:00:00'),
'date' => true,
)
);
The way I would approach this, is by create a custom module the keep track of the order status using observer
See Magento order status change events
Then log (in a db) the order # and date when the order was complete and expire. This way you could easily run report on when subscription will expire
Customize Magento using Event/Observe

Resources