Right now I'm successfully creating a Stripe subscription that has a hardcoded quantity:
customer = stripe.Customer.create(email=request.form['stripeEmail'], source=request.form['stripeToken'])
# For the moment, change the quantity parameter for each customer
subscription = stripe.Subscription.create(
customer = customer.id,
items = [
{
'plan': 'plan_*************',
'quantity': 7,
},
],
)
The idea would be to obtain that value for quantity from the frontend. I already have a selector that sets the quantity value programmatically and I'm actually using it to print variable amounts in Stripe Checkout:
<script>
var handler = StripeCheckout.configure({
key: "{{pub_key}}",
image: "https://stripe.com/img/documentation/checkout/marketplace.png",
locale: "auto",
zipCode: true,
token: function(token) {
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
document.getElementById("customButton").addEventListener("click", function(e) {
var quantity = document.getElementsByName("selectedQuantity")[0];
var text = quantity.options[quantity.selectedIndex].text;
// Open Checkout with further options:
handler.open({
name: "Company, Inc.",
description: text + " Subscriptions",
amount: 900 * text
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener("popstate", function() {
handler.close();
});
</script>
Notice that I'm getting the public key from the backend, but I don't know how to retrieve the quantity value from the frontend in the backend.
How do I do that?
EDIT:
When I wasn't using a custom Checkout integration I had a form that would do this:
<form action="{{ url_for('pay') }}" method="POST">
But there is no form here, so I'm not sure what should the next step be.
How are you submitting the token to your backend server(i.e. how have you implemented the token function)? Once you've done that, you can just submit the quantity in the same way.
One way to do this might be to use a form, add the Stripe token to a hidden input in that form, and then submit it with Javascript.
Here's an example : https://jsfiddle.net/53u96kvw/
Or if you don't have a form at all, you can make an AJAX request with the same information : https://jsfiddle.net/kcp12o3z/
Related
So I am working with this API and it auto calculates the delivery fee based on the address you input.
Here's the API docs I am using
https://developer.doordash.com/en-US/api/drive#operation/DeliveryQuote
So when I add my values to my form and get my data, it logs the fee in my console like this
My issue is how do I get this value from the data field?
I tried to do
const response = await client.createDelivery(
{
order_value: req.body.item1,
fee: fee,
tip: req.body.item1,
},
console.log(fee)
);
console.log(response);
res.send(response);
}
)
But it says fee is not defined?
I also tried fee: "" and that doesn't work either.
I even put console.log(data.fee) and it says data is not defined
My last attempt I change it to console.log(response.fee) and it still showed undefined in the console?
How do I even get the fee value to console.log?
Note I am using express and for my tip value I have my input form named "item1" so I can access it by saying req.body.item1 to get that value
However, for the fee value its auto generated by the API, so I can't change it or update it manually myself.
Try using
console.log(response.data.fee)
And I am not sure what your client.createDelivery does. If it sends response, then you need to display it like
const response = await client.createDelivery(
{
order_value: req.body.item1,
fee: fee,
tip: req.body.item1,
},
console.log(fee)
).then((res) => res.json()).then((resData) => console.log(resData.data.fee));
this is what the return object looks like
{
data {
currency: 'USD',
fee: 975,
otherData: otherData,
}
}
what you must do to fix your problem is first dive into the data object then retrieve fee from that object like data.fee
const response = await client.createDelivery(
{
order_value: req.body.item1,
fee: data.fee, // changed from fee to data.fee
tip: req.body.item1,
},
console.log(data.fee)
);
without retrieving it from the data object there would be no fee object to grab which is whats making it undefined...
I'm in test mode, I create a custom connected account successfully using JavaScript in frontend and PHP in backend.
The account created successfully but for some reason, the business profile is not showing on request body (I see this in stripe log in dashboard).
I see a warning message before form submition:
business_profile is not a recognized parameter
For your reference, here’s the API coding I used when I did my test:
https://stripe.com/docs/api/accounts/create?lang=php#create_account-business_profile
JavaScript
const accountResult = await stripe.createToken('account', {
business_type: 'company',
company: {...},
business_profile: {
mcc: "5812",
support_email: "test#example.com",
url: "https://example.com",
},
tos_shown_and_accepted: true,
});
PHP
// ...
$account = \Stripe\Account::create([
"country" => "FR",
"type" => "custom",
"account_token" => $account_token,
]);
// ...
stripe.createToken doesn't take a business_profile value, nor does it manage Stripe\Account objects at all - it creates a Stripe\Token. You'll have to update that information via a separate call to the Stripe API. The parameters it does take are documented here:
name, address_line1,address_line2, address_city, address_state, address_zip, address_country, currency
I'm trying to build a platform based on Meteor that uses Stripe Connect. I want to use the "preferred" authentication method from Stripe (Authentication via the Stripe-Account header, https://stripe.com/docs/connect/authentication) so that I can create plans and subscribe customers on behalf of my users. I cannot get it to work. I tried with a second params object, similar to the exemple in the documentation:
var stripeplancreate = Meteor.wrapAsync(Stripe.plans.create, Stripe.plans);
var plan = stripeplancreate({
amount: prod.price,
interval: prod.interv,
name: prod.name,
currency: prod.curr,
id: prod.id+"-"+prod.price+"-"+prod.curr+"-"+prod.interv,
metadata: { prodId: prod._id, orgId: org._id },
statement_descriptor: prod.descr
},{stripe_account: org.stripe_user_id});
but I get "Exception while invoking method 'createStripeProduct' Error: Stripe: Unknown arguments ([object Object]). Did you mean to pass an options object? See https://github.com/stripe/stripe-node/wiki/Passing-Options." which does not seem to accurately reflect the issue but prompted me to try adding stripe_account in the params object itself:
var stripeplancreate = Meteor.wrapAsync(Stripe.plans.create, Stripe.plans);
var plan = stripeplancreate({
amount: prod.price,
(...)
statement_descriptor: prod.descr,
stripe_account: org.stripe_user_id
});
I then get the following error: "Exception while invoking method 'createStripeProduct' Error: Received unknown parameter: stripe_account"
Any ideas? Has anybody managed to have Stripe Connect stripe_account authentication work with Meteor, especially with Meteor.wrapAsync(...)?
This should work for wrapAsync, HOWEVER check out my answer here for possible issues with wrapAsync - Wrapping Stripe create customer callbacks in Fibers in Meteor:
Here is also a great video on wrapAsync: https://www.eventedmind.com/feed/meteor-meteor-wrapasync
var createStripePlanAsync = function(shoppingCartObject, callback){
stripe.plans.create({
amount: shoppingCartObject.plan.totalPrice,
interval: shoppingCartObject.plan.interval,
name: shoppingCartObject.plan.planName,
currency: "usd",
id: shoppingCartObject.plan.sku //this ID needs to be unique!
}, function(err, plan) {
// asynchronously called
callback(err, plan);
});
};
var createStripePlanSync = Meteor.wrapAsync(createStripePlanAsync);
var myShoppingCart = {
customerInfo: {
name: "Igor Trout"
},
plan: {
totalPrice: 5000,
interval: "month",
name: "Set Sail For Fail Plan",
sku: "062015SSFF"
}
};
// Creates the plan in your Stripe Account
createStripePlanSync(myShoppingCart);
Later when you subscribe a customer to a plan you just refer to the plan via the id that you gave the plan when you first created it.
After much trying multiple things, for now, I just managed to get it working using the stripe-sync package instead of the "normal" one + wrapAsync.
try{
var plan = Stripe.plans.create({
amount: prod.price,
...
},{stripe_account: org.stripe_user_id});
}catch(error){
// ... process error
}
I've setup a stripe custom checkout using javascript. Every parameter goes through, I receive a status 200 in the log when we make a payment. Everything looks like it goes through. However the amount remains as "0" in the Parsed Request Query Parameters and not charging the card.
I've gone over documentation for hours and can't get my head around the issue.
<script src="https://checkout.stripe.com/checkout.js"></script>
<script>
var pinId = "<%= #id %>";
var from = "<%= #from %>";
var content = "Supersize+me";
var handler = StripeCheckout.configure({
key: 'Published-Key',
image: '/assets/campusboard-logo.png',
token: function(token, args) {
$.getJSON( "purchased/"+pinId )
.done(function( data ) {
window.location = "http://"+window.location.host+"/pins/"+pinId+"?utm_source=Purchased&utm_medium="+from+"&utm_campaign=Featured%20Pins&utm_content="+content;
})
.fail(function( jqxhr, textStatus, error ) {
alert("We've encountered a problem with the transaction. Please try again.");
});
}
});
document.getElementById('ssm').addEventListener('click', function(e) {
// Open Checkout with further options
handler.open({
name: 'CampusBoard',
description: 'Featured Pin (£29.00)',
amount: "100",
currency: 'GBP',
panelLabel: 'Supersize my Pin'
});
e.preventDefault();
});
document.getElementById('mmh').addEventListener('click', function(e) {
// Open Checkout with further options
handler.open({
name: 'CampusBoard',
description: 'Featured Pin (£59.00)',
amount: 5900,
currency: 'GBP',
panelLabel: 'Make my Pin Huge'
});
content = "Make+me+huge";
e.preventDefault();
});
</script>
Can someone see where I'm going wrong?
Stripe Checkout is just a well-done pre-made payment form. You actually have to create a Charge object on your server using your Stripe secret API key. Follow these tutorials for your specific language.
You are passing the amount as a string whereas I think stripe is expecting it as a number. So:
handler.open({
...
amount: 100,
...
});
I am trying to store an entry in a database after a click using an ajax call to a route that calls a controller function in javascript (in Laravel 4).
I have a resource "artists", that is controlled by an "ArtistsController". The view where I am making the call is called "show.blade.php" in an "artists" directory (i.e. the page shows different artists: artists/1, artists/2, etc...).
I also have a table called "fanartists", where I want to store this data. Basically, when a user clicks a button on a specific artist's page, I want the relationship to be stored in this table.
Here is the relevant code:
show.blade.php:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '*****************',
status : true,
cookie : true,
oauth : true
//xfbml : true
});
$( '.opener' ).click(function() {
FB.ui({
method: 'feed',
link: 'http://crowdtest.dev:8888/artists/',
name: 'Hello',
caption: 'Hello',
description: 'Hello!'
});
request = $.ajax({
url: "/artists/fbclick",
type: "post",
data: serialised data
});
});
};
</script>
<a class="add-list-button-no-margin opener" style="color: white; font:14px / 14px 'DINMedium','Helvetica Neue',Helvetica,Arial,sans-serif;">Play my city</a>
ArtistsController:
public function fbclick($id) {
$artist = Artist::find($id);
$fanartist = new Fanartist;
$fanartist->artist_id = $artist->id; //the id of the current artist page (i.e. artists/1, id=1)
$fanartist->fan_id = Auth::user()->id;
$fanartist->save();
}
routes:
Route::get('/artists/fbclick', array('uses' => 'ArtistsController#fbclick'));
When I include the ajax request, the FB feed does not pop up. When I remove it, it does. Also, it is not storing the data in the database like I want it to.
Do you see anything wrong here? Your help is much appreciated. Thank you.
I see some slight mistakes in your script.
In your ajax request you are using post as the method, but you have defined your route as get so either change your route to post or change ajax method to get. I will go with post route so your new route is Route::post('/artists/fbclick', array('uses' => 'ArtistsController#fbclick')');
And ajax data field should be in json format, so now you ajax request will look some what like this
$.ajax({
url: "/artists/fbclick",
type: "post",
data: {field_name :'data'}
});
Finally coming to you controller function, with silght changes
public function fbclick() {
// $artist = Artist::find($id);
$id=Input::get('field_name'); //field_name is the field name from your Json data
$fanartist = new Fanartist;
$fanartist->artist_id = $id; //the id of the current artist page (i.e. artists/1, id=1)
$fanartist->fan_id = Auth::user()->id;
$fanartist->save();
}
Everything should work now