Unable to update Stripe accounts with URI error - ruby-on-rails

I receive the following error when attempting to update Stripe Connect accounts:
bad URI(is not URI?): /v1/accounts/{ "id": "acct_xxxxxxxxxxxxxxxxxx", "object": "account", "business_profile": { "mcc": null, "name": null, "product_description":
....
....
I am able to create accounts but updating them doesn't seem to work. I am using the same form and similar code in the controller. This is my update method in controller:
def update
unless (current_user || current_affiliate).stripe_account
redirect_to new_user_stripe_account_path and return
end
begin
#stripe_account_retrieve = Stripe::Account.retrieve((current_user || current_affiliate).stripe_account.acct_id)
stripe_account_params.each do |key, value|
if value.empty?
flash.now[:alert] = "Please complete all fields."
render 'edit' and return
end
end
if #stripe_account.account_type == "individual"
Stripe::Account.update(
#stripe_account_retrieve,
{
:country => stripe_account_params[:country],
:type => "custom",
:business_type => stripe_account_params[:account_type],
requested_capabilities: ['platform_payments'],
individual: {
address: stripe_account_params[:address_line1],
first_name: stripe_account_params[:first_name],
last_name: stripe_account_params[:last_name],
ssn_last_4: stripe_account_params[:ssn_last_4],
# phone: stripe_account_params[:business_tax_id],
dob: {
day: stripe_account_params[:dob_day],
month: stripe_account_params[:dob_month],
year: stripe_account_params[:dob_year]
},
address: {
line1: stripe_account_params[:address_line1],
city: stripe_account_params[:address_city],
state: stripe_account_params[:address_state],
postal_code: stripe_account_params[:address_postal]
},
},
tos_acceptance: {
date: Time.now.to_i,
ip: request.remote_ip
}
})
....
....
respond_to do |format|
#stripe_account = StripeAccount.find(params[:id])
if #stripe_account.update(stripe_account_params)
format.html { redirect_to #stripe_account, notice: 'Stripe account was successfully updated.' }
format.json { render :show, status: :ok, location: #stripe_account }
else
format.html { render :edit }
format.json { render json: #stripe_account.errors, status: :unprocessable_entity }
end
end
end
end
According to the docs, I don't see anything I am doing wrong...
https://stripe.com/docs/api/accounts/update
My edit in controller:
def edit
#stripe_account_retrieve = Stripe::Account.retrieve((current_user || current_affiliate).stripe_account.acct_id)
#stripe_account = StripeAccount.find(params[:id])
end
When i submit the update form (this is ahead of the error:)
Started PATCH "/stripe_accounts/27" for 127.0.0.1 at 2019-04-03 20:16:38 -0400
Processing by StripeAccountsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"3//b+Exxxf9xxxtagFbsdzMxxxW+wxxxx899FDLfMb/RxxxxQA==", "stripe_account"=>{"first_name"=>"seller21114", "last_name"=>"last2124", "ssn_last_4"=>"2222", "dob_month"=>"1", "dob_day"=>"10", "dob_year"=>"1912", "address_line1"=>"111 st", "address_city"=>"san fran", "country"=>"US", "address_state"=>"IL", "address_postal"=>"90210", "tos"=>"1"}, "2"=>"", "button"=>"", "id"=>"27"}
IS there anything I am doing wrong here with my code?

Stripe::Account.update(
#stripe_account_retrieve,... )
this should be
Stripe::Account.update(
#stripe_account_retrieve[:id], ...)
i.e., pass the ID of the Account object you retrieved, not the full object itself.
Or just pass the value of (current_user || current_affiliate).stripe_account.acct_id directly to Stripe::Account.update, since you don't seem to currently use the retrieved account for anything else so you may as well save youself a GET request :)

Related

Rails is returning an instance of User instead of a user Object

I recently deployed my site on Heroku and Netlify and was having issues with Auth. My current issue (and hopefully last) is that upon login, rails is sending back a user instance instead of the object with information (i.e #User:0x000056205efbbad8). I get a token from my rails response and upon refresh am logged in but am not automatically logged in because of the user instance being returned instead of an object with user information.
This is my auth controller
class AuthController < ApplicationController
def login
user = User.find_by(username: params[:username])
if user && user.authenticate(params[:password])
secret = ENV["SECRET_KEY_BASE"]
token = JWT.encode({ user_id: user.id }, secret, 'HS256')
render json: { user: UserSerializer.new(user), token: token }
else
render json: { failure: "Invalid Username or Password" }
end
end
def signup
auth_params = params.permit(:username, :password, :email, :avatar)
if params[:avatar].instance_of?(String) || params[:avatar].nil?
user = User.create(auth_params)
render json: user
else
imageUploaded = Cloudinary::Uploader.upload(params[:avatar])
user_params_new = auth_params
user_params_new[:avatar] = imageUploaded["url"]
user = User.create(user_params_new)
if user.valid?
secret = ENV["SECRET_KEY_BASE"]
token = JWT.encode({ user_id: user.id }, secret, 'HS256')
render json: {user: user, token: token }, status: :created
else
render json: { error: user.errors.full_messages }, status: :unprocessable_entity
end
end
end
end
Here is my login function on my React frontend
function handleLogin(e) {
e.preventDefault()
fetch(`${process.env.REACT_APP_API_BASE_URL}/login`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(loginData)
})
.then(r => r.json())
.then(data => {
if (data.failure) {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Incorrect Username or Password!'
})
} else {
setCurrentUser(data.user)
setUserReviews(data.user.reviews)
setFavorites(data.user.favorites)
localStorage.setItem("token", data.token)
history.push("/festivals")
}
})
}
I so appreciate any help on this, thanks so much!
Link to github repo: https://github.com/connormul/festie-backend
https://github.com/connormul/festie-frontend
render json: { user: UserSerializer.new(user), token: token }
This doesn't look a correct use of serializer
try to change it to
render json: { user: UserSerializer.new(user).as_json, token: token }

Rails 6.0.0 TypeError - no implicit conversion of nil into String:

people so I have this problem when trying to do a post API call.
the situation is this:
I have a large application where students sign up so I can manage them and contact them through that student management app.
Now I have created a smaller app where students can do their assignments, lets call that homework app;
I am doing a post API call to the bigger app in the login section so students don't have to sign up again and they can use the same information in both applications.
I am getting an internal server error 500; in the terminal the error is:
TypeError - no implicit conversion of nil into String:
app/controllers/api/sessions_controller.rb:12:in `create'
this is the create action in sessions controller in the student management app:
def create
unless request.format == :json
sign_out
render status: 406, json: { message: "JSON requests only." } and return
end
resource = warden.authenticate!(auth_options)
if resource.blank?
render status: 401, json: { response: "Access denied." } and return
end
sign_in(resource_name, resource)
respond_with resource, location:
after_sign_in_path_for(resource) do |format|
format.json { render json:
{
success: true, jwt: current_token, response: "Authentication successful"
}
}
end
end
and most importantly the api call with a very simple html form:
ps: I am running the projects locally, thats why the url's are defined as localhost
<form class="login-form">
<input type="email" class="mail mail-input" placeholder=" Email"><br>
<input type="password" class="password pw-input" placeholder=" Password"><br>
<button class="login" type="button" name="button">Login</button>
</form>
<script>
var login = document.querySelector(".login")
login.addEventListener("click", function(){
var email = document.querySelector(".mail")
var password = document.querySelector(".password")
let loginValues = {
email: email.value,
password: password.value
}
$.post (
"http://localhost:4000/api/login.json",
{
api_user: {
email: email.value,
password: password.value
}
},
function (response){
console.log(response)
console.log('in');
window.location.replace("http://localhost:3000/")
}
)
})
</script>
Can you try replacing this:
api_user: {
email: email.value,
password: password.value
}
With this:
user: {
email: email.value,
password: password.value
}
Tell me if it works?
Update, based on comments:
I really have no idea what you are doing in the code above, the code is really messy... Try replacing this:
respond_with resource, location:
after_sign_in_path_for(resource) do |format|
format.json { render json:
{
success: true, jwt: current_token, response: "Authentication successful"
}
}
end
with this:
respond_with resource do |format|
format.json { render json:
{
success: true, jwt: current_token, response: "Authentication successful"
}
}
end

Params for json array in Rails

I'm new to rails,
Please check my code and tell me whats wrong with my use params, because this is how it made sense to me.
Controller:
def create
user = User.find(user_params)
order = user.purchases.new
render json: order.errors if !order.save
basket = params.require(:basket)
basket.each do |b|
i = Item.find(b[:item_id])
render json: i.errors, status: 422 if !i
order.purchases_items.create(item_id: i, quantity: b[:quantity])
end
render nothing: true, status: 201 # location: show action
end
and my test file is sending
test "making order" do
post "/api/users/#{#tuser.id}/orders",
{ basket: [ { item_id: '2', quantity: '5' },
{ item_id: '1', quantity: '4'} ] }.to_json,
{ 'Accept' => Mime::JSON, 'Content-Type' => Mime::JSON.to_s }
assert_response 201
assert_equal Mime::JSON, response.content_type
end
Thanks,
What I basically want to do is store each array element in the array basket from params[:basket], and iterate over it.
Sometime params keys are not get converted into symbols automatically. Can u try passing string "basket" instead of symbol :basket?

Parsing JSON Array Object in ROR

I am trying to parse a JSON Object to insert values in table(MySQL). JSON is recived at server but it is unable to read the values to be inserted. Its inserting NULL values.
Below is snapshot from my rails console.
Started POST "/lists.json" for 192.168.1.9 at 2013-08-13 11:38:46 +0530
Processing by ListsController#create as JSON
Parameters: {"list"=>[{"amount"=>"120", "status"=>"done", "itemno"=>"w01", "na
me"=>"t01"}]}
WARNING: Can't verify CSRF token authenticity
(1.0ms) BEGIN
SQL (1.0ms) INSERT INTO `lists` (`amount`, `itemno`, `name`, `status`) VALUES
(NULL, NULL, NULL, NULL)
(103.0ms) COMMIT
The Create method in my lists_controller.rb is as below
def create
lists = params[:list].collect{|key,list_attributes| List.new(list_attributes)}
all_list_valid = true
lists.each_with_index do |list,index|
unless list.valid?
all_list_valid = false
invalid_list = lists[index]
end
end
if all_list_valid
#lists = []
lists.each do |list|
list.save
#lists << list
end
format.html { redirect_to #list, notice: 'List was successfully created.' }
format.json { render json: #list, status: :created, location: #list }
else
format.html { render action: "new" }
format.json { render json: #list.errors, status: :unprocessable_entity }
end
end
I am not sure why it is taking NULL values even though "Parameters" seems to have correct values. Please advise . Thanks.
See documentation for the collect method.
irb(main):008:0> parameters = {"list"=>[{"amount"=>"120", "status"=>"done", "itemno"=>"w01", "name"=>"t01"}]}
=> {"list"=>[{"status"=>"done", "amount"=>"120", "itemno"=>"w01", "name"=>"t01"}]}
irb(main):009:0> parameters["list"]
=> [{"status"=>"done", "amount"=>"120", "itemno"=>"w01", "name"=>"t01"}]
irb(main):010:0> parameters["list"].collect{|list| p list}
{"status"=>"done", "amount"=>"120", "itemno"=>"w01", "name"=>"t01"}
=> [nil]

How do i get the before_save value in the controller in Rails 3?

def update
#product_category = #business_category.product_categories.find(params[:id])
product_category_was = #business_category.product_categories.find(params[:id])
respond_to do |format|
if #product_category.update_attributes(params[:product_category])
share_associations(#product_category, product_category_was) if in_params('_maps_attributes', 'product_category')
format.js
format.html { redirect_to(admin_product_categories_path, :notice => 'Product category was successfully updated.') }
format.xml { head :ok }
else
format.js
format.html { render :action => "edit" }
format.xml { render :xml => #product_category.errors, :status => :unprocessable_entity }
end
end
end
The function share_associations has the parameters #product_category and product_category_was. The problem is, when i call product_category_was.send('images') for example (which i have to call using send since the call is dynamic) it obviously pulls the newest associated images and not the images that were associated. Is there anyway i can get the object to get the images that were associated at the point in time it was made?
I think you need a deep copy of your object, because normal association (=) will only create a reference:
product_category_was = Marshal::load(Marshal::dump(#product_category))
This might not work for all kinds of objects, but for normal Rails objects this should work.
I have no idea what arnep is talking about, nor what problem you're getting. What you're doing works for me on two different finds through an association, and so it should.
irb(main):016:0> s = School.first
=> #<School id: 2, name: "Bar", created_at: "2011-04-09 17:48:57", updated_at: "2011-05-13 09:13:38", confirmed: nil, zipcode: nil>
irb(main):017:0> g1 = s.grades.find 4
=> #<Grade id: 4, name: "4th", type: nil, school_id: 2, created_at: "2011-04-19 03:17:49", updated_at: "2011-05-13 09:15:17">
irb(main):018:0> g2 = s.grades.find 4
=> #<Grade id: 4, name: "4th", type: nil, school_id: 2, created_at: "2011-04-19 03:17:49", updated_at: "2011-05-13 09:15:17">
irb(main):019:0> g1.update_attributes :name => '5th'
=> true
irb(main):020:0> g2
=> #<Grade id: 4, name: "4th", type: nil, school_id: 2, created_at: "2011-04-19 03:17:49", updated_at: "2011-05-13 09:15:17">
irb(main):021:0> g1
=> #<Grade id: 4, name: "5th", type: nil, school_id: 2, created_at: "2011-04-19 03:17:49", updated_at: "2011-05-13 09:16:02">
irb(main):022:0>
In fact, usually people are asking the inverse question - how to get an already instantiated object to reload from the DB. The problem is probably in your share_associations method, or something else you're not showing yet.
I found a way to do something that works for now. It's not the greatest way, but it works for now. I basically created an empty array and pushed the product_categories array into it. This made it so the value was no longer a call so the value does not change. Hopefully this will help someone else eventually.
def update
#product_category = #business_category.product_categories.find(params[:id])
if in_params('_maps_attributes', 'product_category')
media_was = Array.new
media_was = media_was | #business_category.product_categories.find(params[:id]).send(map_type('product_category').pluralize)
end
respond_to do |format|
if #product_category.update_attributes(params[:product_category])
share_associations(#product_category, media_was) if in_params('_maps_attributes', 'product_category')
format.js
format.html { redirect_to(admin_product_categories_path, :notice => 'Product category was successfully updated.') }
format.xml { head :ok }
else
format.js
format.html { render :action => "edit" }
format.xml { render :xml => #product_category.errors, :status => :unprocessable_entity }
end
end
end

Resources