I'm trying to send this string to my Stripe account to process a transaction, and I want to send both an ID of the item being bought and the amount paid for as a JSON string. How do I include the pieces of the model in the string?
customer = Stripe::Customer.create(email: email, description: {"amount:" amount, "id:" idea_id}')
One part of the model is amount and the other is idea_id
Assuming your model is called Product
#product = Product.find(params[:id])
customer = Stripe::Customer.create(email: email, description: {amount: #product.amount, id: #product.idea_id}.to_json)
or you can also use
customer = Stripe::Customer.create(email: email, description: #product.as_json(only: [:amount, :idea_id]))
However this may not work if you absolutely require the key for idea_id to be 'id'. in which case use the first option.
Hope this helps
Related
I've got some issues, i'm trying to implement subscription with stripe > it works when there is for exemple 3 items in my order > it create a subscription for the 3 items.
The problem is that if the customer wants to stop sub only for ONE element, i dont know how to handle this ...
So i was wondering to create a subscription for each element, this is my code
customer = Stripe::Customer.create
#order.line_items.each do |line_item|
product = Stripe::Product.create(
{
name: line_item.product.name,
metadata: {
product_id: line_item.product.id,
line_item_id: line_item.id
}
}
)
price = Stripe::Price.create(
{
product: product.id,
unit_amount: line_item.product.price_cents,
currency: 'eur',
recurring: {
interval: 'month'
}
}
)
Stripe::Subscription.create({
customer: customer.id,
items: [
{price: price.id, quantity: line_item.quantity}
]
})
but i got this error This customer has no attached payment source or default payment method.
and i dont know how to attach it, even with documentation..
any help please ? thank you
As said in comments; To fix the error in the title:
You need to first have the "payment method", if you haven't already, create one:
Maybe using Stripe.js and it's elements API.
Which nowadays has "payment" element, allowing users to choose their payment-method.
And supports Setup-Intent's "client_secret" (beside Payment-Intent's), submittable using confirmSetup(...) method.
Then (using Stripe API):
Attach said "payment method" to the Customer:
(Optionally) set it as their default for invoices (with invoice_settings.default_payment_method).
And, while creating the subscription, pass the customer (that which you atteched said "payment method" to).
I've been trying to implement a payment method for a shopping cart using card information attached to the user via a subscription model. And while the latter works fine, whenever I attempt to create a charge for the cart, I get the "Must provide source or error."
Here's some code to get started. Let me know if you need more.
checkouts_controller.rb
def create
customer = Stripe::Customer.create(
source: params[:stripeToken],
email: 'paying.user#example.com',
)
charge = Stripe::Charge.create(
amount: current_cart.total,
currency: 'usd',
description: "Order ##{current_cart.id}"
)
end
Error logs from Stripe Post Body
{
"amount": "9500",
"currency": "usd",
"description": "Order #1"
}
And from the response body
{
"error": {
"code": "parameter_missing",
"doc_url": "https://stripe.com/docs/error-codes/parameter- missing",
"message": "Must provide source or customer.",
"type": "invalid_request_error"
}
}
I’m using the standard 4242 4242 4242 4242 card that is actually recorded and attached to my user via my subscription model. Card info like the brand, last four digits, expiration month and year all appear in my view when I go to add a different card. The stripe_id is also present when I check in the console.
I have checked stripe documentation and copied the snippet from their create action from https://stripe.com/docs/checkout/rails but this only trigged the error “Cannot charge a customer with no active card” despite the fact that this card is currently being used for a subscription.
So where did I goof at?
You need to make sure that the customer you create is passed in on the charge create call:
charge = Stripe::Charge.create(
customer: customer,
amount: current_cart.total,
currency: 'usd',
description: "Order ##{current_cart.id}"
)
Or you can use the source directly as:
charge = Stripe::Charge.create(
source: params[:stripeToken],
amount: current_cart.total,
currency: 'usd',
description: "Order ##{current_cart.id}"
)
Both options and examples can be found here
moving from comment to an answer
Hi #Grasshopper27, looks like the customer you created is not being created with the source. You should look into Dashboard -> Logs to look at the request body for the /customer creation request and see if the token is being passed in.
I would also like to note that this Rails doc is a bit outdated, you should try out updated Checkout to really simplify your integration: stripe.com/docs/payments/checkout
I use Ruby on Rails 4.2.5 with the Restforce gem for Salesforce API. I create a Contact in my controller :
class CandidateFormController < ApplicationController
def index
client = Restforce.new(
:username => ENV['SALESFORCE_USERNAME'],
:password => ENV['SALESFORCE_MDP'],
:security_token => ENV['SALESFORCE_TOKEN'],
:client_id => ENV['SALESFORCE_APIKEY'],
:client_secret => ENV['SALESFORCE_SECRET'],
)
new_client = client.create('Contact', FirstName: #first_name,
LastName: #last_name,
Email: #email,
MobilePhone: #telephone,
Description: #champ_libre,
Profil_LinkedIN__c: #linkedin
)
end
end
I have a relationship between two of my tables.
Candidate is associated to Opportunity (a job offer if you prefer), and the restforce documentation doesn't explain how to create a new entry with a relation between two elements, or if it does I am not enough experimented to have understand how am I supposed to do so.
I have not enough credit to post screenshots, but if this is necesseray I can use imgur or something like that.
P.S : I already see this post on the subject, but that didn't help me at all.
Well, after another hour of research I finally find how to create relationship in salesforce.
My code looks like this now :
class CandidateFormController < ApplicationController
def index
client = Restforce.new(
:username => ENV['SALESFORCE_USERNAME'],
:password => ENV['SALESFORCE_MDP'],
:security_token => ENV['SALESFORCE_TOKEN'],
:client_id => ENV['SALESFORCE_APIKEY'],
:client_secret => ENV['SALESFORCE_SECRET'],
)
new_client = client.create('Contact', FirstName: #first_name,
LastName: #last_name,
Email: #email,
MobilePhone: #telephone,
Description: #champ_libre,
Profil_LinkedIN__c: #linkedin
)
new_candidature = client.create(
'Candidatures__c',
Candidats__c: "someId",
Offredemploi__c: new_client
)
end
end
In my case, I wanted to create a relationship between an Opportunity and a Contact (A job offer and a Candidate).
I look more into fields that already was created and filled for Opportunity and Contact in my salesforce account, and find out that there were no field that was corresponding to the relationship I was looking for.
I discover than in salesforce, there are objects that exist just for the junction between two objects, and they are called "Junction Object" (pretty obvious, but not easy to find).
You just have to create a new salesforce object with create() after the creation of your first element (a Contact for me) and create the junction object with the good type (for me it was Candidatures__c), and specify the two relationships.
In my own code I create an new Candidature__c, I specify the Id of the job offer (the Candidats__c id) and the Id of the candidate in Offredemploi__c with the Id I create some lines above.
Hope it will helps.
I am trying to create a customer and charge that customer using Rails and Stripe. The customer is getting created in Stripe, but I keep getting the error Cannot charge a customer that has no active card when trying to do the charge.
I am following a stripe tutorial as a Rails beginner, so I'm not sure where to go from here. Any help would be greatly appreciated.
Rails code:
def process_payment
customer = Stripe::Customer.create email: email,
card: card_token
Stripe::Charge.create customer: customer.id,
amount: level.price*100,
description: level.name,
card: card_token,
currency: 'usd'
end
def create
#registration = Registration.new registration_params.merge(email: stripe_params["stripeEmail"],
card_token: stripe_params["stripeToken"])
raise "Please, check registration errors" unless #registration.valid?
#registration.process_payment
#registration.save
redirect_to #registration, notice: 'Registration was successfully created.'
end
Try creating the charge without the card_token. You shouldn't need to specify the card a second time, since the card is attached to the customer, which you're specifying though the customer parameter.
customer = Stripe::Customer.create email: email,
source: card_token
Stripe::Charge.create customer: customer.id,
amount: level.price*100,
description: level.name,
currency: 'usd'
Also, pass the card_token through the source param, rather than the deprecated card param. Here is a blog post that talks about this change: https://stripe.com/blog/unifying-payment-types-in-the-api
More info: https://stripe.com/docs/api/ruby#create_customer
and: https://stripe.com/docs/api#create_charge
What you are trying to do is charge a customer once you have created a payment method for her. However, you cannot use the Charge endpoint to do that if you have not set any subscriptions because this method is made for recurring payments linked to subscriptions.
In order to be able to charge your client, set a subscription. This will activate the card. You'll then be able to debit the card.
You're trying to access the parameters, so you must use the params keyword.
Instead of card_token, use params["card_token"]
I'm struggling to understand the relationship that owner = create(:user, device_token: device_token) has to owner: {device_token: device_token}, I usually use user_id for this association.
2. What is the device_token method in the controller is doing.
describe 'POST /v1/events' do
it 'saves the address, lat, lon, name, and started_at date' do
date = Time.zone.now
device_token = '123abcd456xyz'
owner = create(:user, device_token: device_token)
post '/v1/events', {
address: '123 Example St.',
ended_at: date,
lat: 1.0,
lon: 1.0,
name: 'Fun Place!!',
started_at: date,
owner: {
device_token: device_token
}
}.to_json, { 'Content-Type' => 'application/json' }
event = Event.last
expect(response_json).to eq({ 'id' => event.id })
expect(event.address).to eq '123 Example St.'
expect(event.ended_at.to_i).to eq date.to_i
expect(event.lat).to eq 1.0
expect(event.lon).to eq 1.0
expect(event.name).to eq 'Fun Place!!'
expect(event.started_at.to_i).to eq date.to_i
expect(event.owner).to eq owner
end
end
Controller Code:
def create
#event = Event.new(event_params)
if #event.save
render
end
end
private
def event_params
{
address: params[:address],
ended_at: params[:ended_at],
lat: params[:lat],
lon: params[:lon],
name: params[:name],
started_at: params[:started_at],
owner: user
}
end
def user
User.find_or_create_by(device_token: device_token)
end
def device_token
params[:owner].try(:[], :device_token)
end
end
There's a number of ways you can identify uniquely identify a record in a database. Using the id field is the most common - but if you've got another way to uniquely identify a user, then you can use that, too. Normally, you don't show a user what their ID number is in the database. But, if you want to give them a way to uniquely identify themselves, you could create another field which is unique for each user - such as a membership_number or similar. It seems like in your case, device_token is a field that uniquely identifies a user.
So, your database cares about the user_id field - that's what it uses to tie an Event to a specific User (aka, the owner). If your users knew their id, then they could pass in that, rather than their device_token, and everything would be fine. But they don't know it.
So, they pass in their devise_token. You use that to fetch the user from the database, and then you know that user's id. Then, you can store that user's id in the user_id field of your Event model.
def user
User.find_or_create_by(device_token: device_token)
end
This method is the one that gets a user based on a devise_token. And then this method:
def event_params
{
address: params[:address],
ended_at: params[:ended_at],
lat: params[:lat],
lon: params[:lon],
name: params[:name],
started_at: params[:started_at],
owner: user
}
end
In particular, the line: owner: user calls that method above. From that point, Rails handles it under the hood and makes sure your user_id is set correctly.
UPDATE AFTER YOUR COMMENT:
device_token is being passed in as a parameter. It is also the name of a field in the User model. So, a single row in the user table might look like this:
id: 24, first_name: fred, last_name: flintstone, device_token: 123abc, address: bedrock, etc.
the method:
def user
User.find_or_create_by(device_token: device_token)
end
is saying: go to the User's table in the database, try to find a User which has a device_token that has the value that was passed in as a parameter, and if we can't find one, then create one.
So in this line: User.find_or_create_by(device_token: device_token), the first reference to device_token is the key of a hash, and it refers to the field called device_token in your User model.
The second reference to device_token is a call to this method:
def device_token
params[:owner].try(:[], :device_token)
end
which fetches the device_token from the parameters passed in. This method basically says: Look in the params hash at the value inside the owner key. See if the owner key contains a device_token. If it does, return that device_token, and if it doesn't return nil. It does this using the try method, which you can read more about here: http://apidock.com/rails/Object/try