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

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.

Related

By usecases 1.create customer 2.update(kyc) 3.Deposit 4 Fund transfer using 3 microservices Api validation

USE case :
Create customer
create a table with name customers having following columns : Id(Numeric), customer_id(varchar), customer_name(varchar), customer_mobileNo(Numeric), EmailId(Varchar) Account_Id(varchar), Amount(Numeric), address(varchar), is_KYC_DONE(Boolean), active(Boolean)
Make a post rest end point to insert data into the customer table and register 2 customers with default amount like 0.
API Validation be like customer_id, customer_name, account_id should be mandatory, Mobile number should be numeric, Email should be in right format, is_KYC_DONE and active should have default value of 0 and 1
Update KYC to true
Make a patch rest point to update kyc in table to true on basis of customer id.
Deposit
Make a post rest end point to deposit amount in above created table based on account id
Deposit should happen when kyc is done i.e true otherwise tranaction will be declined
Fund transfer
Make a post rest point to do amount transfer from one account to another.
payload should be like this :
transfer {
“Amount” :
withdraw {
“Account_id” : “”
},
Deposit {
“Account_id” : “”
}
}
Validation be like
Sufficent funds should be dere
for both withdraw and deposit accountId and amount should be mandatory.
if deposit fails then amount withdrawn from account should be rollbacked.
NOTE : Mke sure atmost once and at least once the transaction should happen.
There will 3 microservices
customer : will have create customer and update kyc end points
Deposit : will have deposit end point
fundtransfer : will have fundtransfer endpoint, withdraw happens from this microservice and for deposit call should go to deposit miroservice.
I am in the process of learning about microservices and there's one thing that I can't seem to figure out and I can't find any resources that give me a direct answer to this. The question is: Do microservices involve only business logic and

Ruby Telegram Bot, passing value to CallbackQuery?

I have a Telegram Bot which updates scores for a set of teams.
Teams are dynamic in size.
def collection_keyboard(identity)
ip_addr = "127.0.0.1:27017"
client = Mongo::Client.new([ip_addr], :database => "camp")
kb = []
client[:inventory].find({"owner": identity}, projection: {"_id": 0, "name": 1}).each do |doc|
kb << Telegram::Bot::Types::InlineKeyboardButton.new(text: doc.to_s , callback_data: ??) //What do i put as the callback data?
end
markup = Telegram::Bot::Types::InlineKeyboardMarkup.new(inline_keyboard: kb)
return markup
end
The above method queries the db and creates an inline keyboard, allowing users to choose which teams score to increment.
Telegram::Bot::Client.run(token) do |bot|
bot.listen do |message|
case message
when Telegram::Bot::Types::CallbackQuery
if message.data == ?? //What do i check here?
end
end
A second inlinekeyboard will be created once the first CallbackQuery has been returned. This keyboard will allow a user to choose how many points to give e.g. 10, 20, 30.
However, since the group size vary, how do I pass the value of the Inline Keyboard which he user has clicked so that I can add points to that particular team? Since the group is dynamic, I cannot capture all possible callback return value with the regular switch statement?
For example, if a user clicks Yellow, how can I pass this value to the next InlineKeyboard such that the user can add 10 points to them?

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]);

Stripe Subscription Plans of Varying Amounts

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.)

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