Creating Destination Charges with Stripe - ArgumentError - Unsupported argument type: 1 (Integer) - ruby-on-rails-6

I'm implementing destination charges with fee collection with stripe. Below is the code implementation as based on this:
def create
#session = Stripe::Checkout::Session.create({
payment_method_types: ["card"],
line_items: [{
price_data: {
currency: "usd",
product_data: {
name: "Provider Payment",
},
unit_amount: 500,
},
quantity: 1,
}],
payment_intent_data: {
application_fee_amount: 123,
transfer_data: {
destination: PetProvider.find(PetOwnerPetProvider.find_by(current_pet_owner.id).pet_provider_id).uid, #pick the current_pet_provider's stripe account id by way of from POPP Table
},
},
mode: "payment",
success_url: payments_success_url + "?session_id={CHECKOUT_SESSION_ID}",
cancel_url: payments_cancel_url,
})
respond_to do |format|
format.js #render create.js.erb
end
rescue Stripe::CardError => e
flash[:error] = e.message
end
Essentially, I have a controller, PaymentsController that has this create method.
I'm getting ArgumentError - Unsupported argument type: 1 (Integer): when I click the Pay button that I implemented to call this create controller action.
Below is how I implemented the button;
<%= button_to 'Pay', payments_create_path, method: :post, remote: true %>
I'm passing the uid which I'm picking from the database and passing it in destination:
I can't seem to get it working though.
This is create.js.erb:
const stripe = Stripe('<%= Rails.configuration.stripe[:publishable_key]%>');
stripe.redirectToCheckout({
sessionId: '<%= #session.id %>'
})
This is the full stack trace;
Started POST "/payments/create" for 127.0.0.1 at 2020-08-07 18:03:03 +0300
Processing by PaymentsController#create as JS
Parameters: {"authenticity_token"=>"GBNOhDSTNritpjJYcFwwq98GfTRDKegW9RZTq1cTTQr1YHU3pquLi9iIMFPxHHE5IHGyuzJ8xLC116gB1bKb9g=="}
PetOwner Load (0.3ms) SELECT "pet_owners".* FROM "pet_owners" WHERE "pet_owners"."id" = $1 ORDER BY "pet_owners"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
Completed 500 Internal Server Error in 5ms (ActiveRecord: 1.0ms | Allocations: 2999)
ArgumentError - Unsupported argument type: 1 (Integer):
app/controllers/payments_controller.rb:27:in `create'

Related

'Note' property not being added in clockify

How do I set the note field?
When I try to add a new Client with the following data (taken from logged request):
method: 'post',
data: '{"name":"Inger Lise Suprice AS","note":"10017"}',
I get the following response:
data: {
id: '***',
name: 'Inger Lise Suprice AS',
workspaceId: '***',
archived: false,
address: null,
note: null <-----
}
Notice the 'note' field is null, even though I set the field in the request.
I followed the example in the documentation. Assuming this is a bug.

Ionic and Firebase .update(): Nested Arrays are not supported

I'm having this issue while I'm trying to perform a crud update function. To put into context, this is an Ionic app with Firebase. This is an app in which the user will be able to create events and update them at a later stage if they want. However, I'm not being able to perform the update with the following error:
ERROR FirebaseError: Function DocumentReference.update() called with invalid data. Nested arrays are not supported (found in document Events/XWtRgH04iEG9IUIqMrgX)
Below are highlighted the function that will save an event after being updated and the service that contains the update function. Any help is greatly appreciated!
saveEvent(event) {
let id = event.id;
let evtSave = {
id: id,
createdAt: event['createdAt'],
createdBy: event['createdBy'],
updatedAt: Date.now(),
part: event['part'] || ['No participants'],
comments: event['comments'] || ['No comments'],
type: event['type'],
title: event['title'],
date: event['date'],
time: event['time'],
map: event['map'],
players: event['players'],
location: event['location'],
description: event['description'],
image: event['image']
};
console.log('saveEvent: ', evtSave);
this.eventServ.updateEvents(id, evtSave)
.then(res => {
this.searchEvents();
console.log('Event: ', res);
this.myAlert('Event successfully updated');
this.mode = 'listMode';
});
Below is the code contained in the service:
updateEvents(eventID, event){
return this.firestore.collection('Events').doc(eventID).update(({
id: event.id,
createdAt: event.date,
createdBy: event.createdBy,
updatedAt: Date.now(),
part: [event.part],
comments: [],
type: event.type,
title: event.title,
date: event.dateMilis,
time: event.time,
map: event.map,
players: event.players,
location: event.location,
description: event.description || 'No description...',
image: event.image || 'No image...',
})).catch((error)=>{
console.log('Error: ', error);
})
and finally a screenshot of how an event looks like in firebase:
At one place in your code you have part: event['part'] || ['No participants'], which will set part to an array of stringy, containing exactly one participant.
Later, when you save, you do: part: [event.part], which I assume can lead to the case where you will get part: [['No participants']].
This is a nested array and as firebase tells you in the error message, this is not supported in firestore.

Trouble Accessing Set Context in Collection2 to Display Invalid Keys on CLIENT

I am using Collection2 for form insert and validation. It works great.
My only issue using the context to access the keys for presenting errors back to the user on the client.
I have the following code:
Common.coffee
Schemas = {}
Schemas.Journal = new SimpleSchema
goal:
type: String
label: "Related Goal"
max: 200
description:
type: String
label: "Comment"
max: 200
likes:
type: Number
label: "Likes"
min: 0
createdBy:
type: String
max: 50
createdAt:
type: Date
label: "Created At"
Journal.attachSchema(Schemas.Journal)
journalContext = Schemas.Journal.namedContext("insertForm")
On Client:
Template.journalForm.events
'submit #newEntryForm': (event) ->
text = event.target.text.value
Meteor.call("newJournalEntry", Session.get("activeGoal"), text)
On Server as a Method:
'newJournalEntry': (goalId, text) ->
Journal.insert
goal: goalId
description: text
createdAt: new Date()
createdBy: Meteor.userId()
likes: 0
{validationContext: "insertForm"}, (error, result) ->
if error
console.log error.invalidKeys
else
console.log "#{result} added to Journal collection."
The validation works correctly on the server and when insert is denied I see the correct messages via terminal, but calling the validation context ON THE CLIENT always gives back an empty array. []
Either of the following work on the server, but if I try these on the client they are empty:
Schemas.Journal.namedContext("insertForm").invalidKeys()
or
error.invalidKeys
UPDATE:
I tried a few more tries at the syntax ON THE CLIENT. Same empty array result. Here are the attempts:
Schemas.Journal.namedContext().invalidKeys()
journalContext.invalidKeys()
Schemas.Journal.namedContext("insertForm").invalidKeys()

Meteor.js + autoform a working contact form example

Can we get a complete contact form example for Meteor beginners?
The steps so far.
Create the Schema
Show the contact form in a template
make sure the values are passed with a method
Add required packages
Create the helper for client side
Create the method for server side (Sends the email)
Show a message on success
Working from the info on https://github.com/aldeed/meteor-autoform#an-example-contact-form
both/collections/contact.coffee
#Contacts = new Meteor.Collection('contacts')
Schemas.Contacts = new SimpleSchema
name:
type: String
label: "Your name"
max: 50
optional: true
autoform:
placeholder: "John Doe"
email:
type: String
regEx: SimpleSchema.RegEx.Email
label: "E-mail address"
optional: true
autoform:
placeholder: "John#doe.com"
message:
type: String
label: "Message"
max: 1000
optional: true
autoform:
placeholder: "Message"
rows: 3
Contacts.attachSchema(Schemas.Contacts)
views/contact/contact.html
<template name="contactPage">
<h2>Get in Contact</h2>
{{> quickForm
schema=contactFormSchema
id="contactForm"
type="method"
meteormethod="sendEmail"
template="bootstrap3-horizontal"
label-class="col-sm-3"
input-col-class="col-sm-9"
}}
</template>
.meteor/packages
coffeescript
aldeed:collection2
aldeed:simple-schema
aldeed:autoform
twbs:bootstrap
email
views/contact/contact.coffee
if Meteor.isClient
Template.contactPage.helpers
contactFormSchema: ->
Schemas.Contacts
server/contact-send.coffee
if Meteor.isServer
Meteor.methods
sendEmail: (doc) ->
# Important server-side check for security and data integrity
check doc, Schemas.contacts
# Build the e-mail text
text = 'Name: ' + doc.name + '\n\n' + 'Email: ' + doc.email + '\n\n\n\n' + doc.message
#unblock()
console.log "about to send the email"
# Send the e-mail
Email.send
to: 'someone#somewhere.com'
from: doc.email
subject: 'Website Contact Form - Message From ' + doc.name
text: text

Meteor: Why is Iron Router's onBeforeAction called multiple times?

When I visit a route in my browser I expect Iron Router to call onBeforeAction once before loading the route. But it looks like it is being called 3 times when first loading the route.
This is an issue for me because I want to put code that redirects the user if they do not have access to that document.
onBeforeAction: ->
console.log 'called once' #Called 3 times when first loading the route!
thread = Research.findOne(#params._id)
console.log thread # This is undefined at first run
thread = Research.findOne(#params._id)
if thread?
Meteor.subscribe 'collabUsers', #params._id
else
Router.go '/research'
Since it is called multiple times, it causes issues with redirecting. First users that do have access are also redirected because at first thread is undefined.
What I am trying to do if check if the user has access to the data the route depends on, if not then I need to redirect the user. So that is why in onBeforeAction I am trying to pull a document from database and if it exists then I will load the page or else I will redirect or throw and error message at the user.
But I notice that the console.log statement in onBeforeAction is called 3 times when the route is first loaded. And also on the first run the user does not have access to any research threads for some reason (I believe the subscription has not been setup and documents are not accessible on first run) So that causes issues with my trying to see if they have access to the document because on first run nobody has access.
Here is the entire router.coffee code
appendUserData = (array) ->
_.each array, (item) ->
user = Meteor.users.findOne(item.userId)
if user?.profile.firstName? && user?.profile.lastName?
item.firstName = user.profile.firstName
item.lastName = user.profile.lastName
item.username = user.username
userEnabled = () ->
if Meteor.user()
if $(window).width() > 768
if !$('.show-left').hasClass 'active'
Meteor.defer ->
$('.show-left').click()
requireLogin = (pause) ->
if !Meteor.user()
#setLayout 'layoutLoggedOut'
if Meteor.loggingIn()
#render #loadingTemplate
else
#render 'login'
pause()
else
#setLayout 'layout'
if window.location.pathname is '/' or undefined
Router.go('addAndSearchPosts')
else
Router.go(window.location.pathname)
Router.configure
layoutTemplate: 'layout'
loadingTemplate: 'loading'
onBeforeAction: ->
#this code get which ids we need to get data from to render template. Here we need to get data to notification of collab
params = {}
params.threadIds = []
params.userIds = []
notifications = Notifications.find {userId: Meteor.userId()}
notifications.forEach (notification) ->
params.threadIds.push notification.threadId
params.userIds.push notification.requesterId
#subscribe('notificationDataCollab', params).wait()
waitOn: ->
[
Meteor.subscribe 'myResearch', Meteor.userId()
Meteor.subscribe "notifications"
]
Router.onAfterAction userEnabled
Router.onBeforeAction requireLogin,
except: 'template1'
Router.onBeforeAction 'loading'
Router.onBeforeAction ->
Errors.clearSeen()
Router.map ->
#route 'posts_page',
path: '/posts',
#route 'template1',
path: '/template1',
#route 'login',
path: '/',
#route 'addAndSearchPosts',
path: '/bookmarks',
waitOn: ->
Meteor.subscribe 'myBookmarks', Meteor.userId()
data: ->
bookmarks: Bookmarks.find
_userId: Meteor.userId()
#route 'research',
path: '/research/:_id',
waitOn: ->
[
Meteor.subscribe 'threadNotes', #params._id, Meteor.userId()
Meteor.subscribe 'collabUsers', #params._id
]
onBeforeAction: ->
console.log 'called once'
#Meteor.subscribe 'collabUsers', #params._id
# thread = Research.findOne(#params._id)
# console.log thread
#thread = Research.findOne(#params._id)
# if thread?
# Meteor.subscribe 'collabUsers', #params._id
# else
# Router.go '/research'
#Errors.throw('Thread does not exist or you do not have access', false)
data: ->
# this code is for appending the user data to pending and current collaborators for this thread
thread = Research.findOne(#params._id)
if thread?.pending?.collaborators?.length > 0
appendUserData(thread.pending.collaborators)
if thread?.collaborators?.length > 0
appendUserData(thread.collaborators)
data =
researchThread: thread,
notes: Notes.find
_threadId: #params._id
,
sort:
date: -1
data
#route 'researchHome',
path: '/research'
#route 'profileEdit',
path: '/editprofile'
Here is publications.coffee
Meteor.publish 'myResearch', (id) ->
Research.find({$or: [{_userId: id}, {'collaborators.userId': id}] })
Meteor.publish 'threadNotes', (threadId) ->
Notes.find({_threadId: threadId})
Meteor.publish 'myBookmarks', (userId) ->
Bookmarks.find({_userId: userId})
Meteor.publish 'collabUsers', (threadId) ->
Meteor.users.find({}, {fields: {profile: 1, username: 1}})
Meteor.publish 'notifications', ->
Notifications.find()
Meteor.publish 'notificationDataCollab', (params) ->
[
Meteor.users.find({_id: {$in: params.userIds}}, {fields: {username: 1}})
Research.find({_id: {$in: params.threadIds}}, {fields: {name: 1}})
]
Any advice on how to handle this is appreciated.
onBeforeAction is run and rerun reactively. You probably want onRun.

Resources