Set Stripe checkout custom amount from GET parameter - stripe-payments

I can't figure out, just want to pass to checkout page a value as GET parameter
so that https://xxxxxx/?setAmount=200000 did go to a page with this script
<form action="custom action" method="POST">
<script
let params = new URLSearchParams(document.location.search.substring(1));
let amount=params.get(setAmount);
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_UUbDY16wDCECOujIs0vQ2vTi"
data-amount=amount;
data-name="Company"
data-description="Widget"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto"
data-zip-code="true"
data-currency="eur">
</script>
</form>
The checkout button show out but didn't get the amount parameter, so that no amount is defined.
I didn't have access to server side on the server hosting the website with the button so I need to go forth and back to another site using Podio Globiflow.

Stripe Checkout supports two modes -- Simple and Custom. Custom lets you control what pops up using javascript instead of data properties set on the server. To get the behavior you seek, you could do something like this:
$('#customButton').on('click', function(e) {
const params = new URLSearchParams(document.location.search)
const amountInCents = params.get("amount")
const displayAmount = parseFloat(amountInCents / 100).toFixed(2);
// Open Checkout with further options
handler.open({
name: 'Demo Site',
description: 'Custom amount ($' + displayAmount + ')',
amount: amountInCents,
});
e.preventDefault();
});
// Close Checkout on page navigation
$(window).on('popstate', function() {
handler.close();
});
It is worth noting, that this amount has no impact on how much you actually Charge your Customer and is only for display purposes. Checkout tokenizes the Card details; the amount Charged is entirely controlled by server side logic as outlined in the official Stripe docs.

Related

Stripe Checkout Shipping Address

I'm using Stripe Checkout API to direct user to make a payment. I want to get the shipping address to ship them as well.
Here's the code that I'm using in my WordPress widget:
<!-- Load Stripe.js on your website. -->
<script src="https://js.stripe.com/v3"></script>
<!-- Create a button that your customers click to complete their purchase. Customize the styling to suit your branding. -->
<button
style="background-color:#6772E5;color:#FFF;padding:8px 12px;border:0;border-radius:4px;font-size:1em"
id="checkout-button-price_1HhPY2IT1E1kKJAOCUoQDPxI"
role="link"
type="button"
>
Checkout
</button>
<div id="error-message"></div>
<script>
(function() {
var stripe =Stripe('pk_live_51H7oCMIT1E1kKJAOeiJKZvF4R2uIJfFCIrOJ1hW8Krned1tfG0abtsQdMD6pRmRyqh5gNNnfxVCzltFc29K7C5Iq00YJyFHBZZ');
var checkoutButton = document.getElementById('checkout-button-price_1HhPY2IT1E1kKJAOCUoQDPxI');
checkoutButton.addEventListener('click', function () {
/*
* When the customer clicks on the button, redirect
* them to Checkout.
*/
stripe.redirectToCheckout({
lineItems: [{price: 'price_1HhPY2IT1E1kKJAOCUoQDPxI', quantity: 1}],
mode: 'payment',
/*
* Do not rely on the redirect to the successUrl for fulfilling
* purchases, customers may not always reach the success_url after
* a successful payment.
* Instead use one of the strategies described in
* https://stripe.com/docs/payments/checkout/fulfill-orders
*/
successUrl: window.location.protocol + '//GLOBESITY.FOUNDATION/success',
cancelUrl: window.location.protocol + '//GLOBESITY.FOUNDATION/canceled',
})
.then(function (result) {
if (result.error) {
/*
* If `redirectToCheckout` fails due to a browser or network
* error, display the localized error message to your customer.
*/
var displayError = document.getElementById('error-message');
displayError.textContent = result.error.message;
}
});
});
})();
</script>
This code is working fine in getting the payments but it doesn't get the shipping address. Also I want the shipping address default country to be United States. Thank you!
You'll need to use the server+client version of Checkout (the client-only version doesn't support this), and create the CheckoutSession following this example. Specifically, you'll want to pass shipping_address_collection with allowed_countries: ['US'].

How to add audio/spotify attachments to azure bot service?

I currently have a node bot embedded on my web app via direct line but I am struggling to attach:
Spotify Audio
I am trying to do so by using the URL attachment or an adaptive card, but the spotify embed doesn't play
Below is the code I use:
var send = {
text: "stuff",
attachments: [
contentType: "audio/ogg",
contentUrl: "spotifyEmbedUrl"
]
}
await stepContext.context.sendActivity(send);
I am unsure on how I can get spotify audio to play.
Is there a way I can return HTML code (and so get around it by adding an iframe into the chat etc?)
OR maybe I could create a modal popup that I could create the embed iframe?
Any help would be appreciated!
Unfortunately, you can't just send a file to a web page and it automatically start playing. Additionally, while Spotify provides embed URLs, which are not a direct link to an audio file, you can't simply tell the browser to play the file.
However, Spotify provides the embed code for displaying a play button that can be used in a page to play a song. Assuming you are using Web Chat in a web site (and even if you're not, this will give you an idea) and that, from the code you supplied, you are wanting to send the song in an activity, you can achieve this by sending the embed code in the activity, instead, via Web Chat's store. When the activity is received, the embed code is passed to a function to update the page and, thus, display the play button.
Be aware, the play button is essentially a UI widget, not a media player. There is no functionality available for telling the play button to auto play, stop, or anything else. The most you can do is display the button after which the user will be required to interact with it.
Also, this is a someone bare bones, simplified implementation. There are many things that aren't accounted for - please don't consider this a complete solution. There are aspects you will need to consider (e.g. multiple cards that utilize a postBack action).
In your bot: You want to send the embed code in an activity. Whether that is an event, message, or something else, is up to you. As you can see below, I have chosen to send a hero card that initiates a postBack when the button is pressed (a postBack sends data behind the scenes without displaying the action to the user).
const card = CardFactory.heroCard(
"Rome Wasn't Built in a Day",
null,
CardFactory.actions([
{
type: 'postBack',
title: 'Read more',
value: `<iframe src="https://open.spotify.com/embed/track/6lzd7dxYNuVSvh7sJDHIa3" width="300" height="380" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>`
}
]),
{
subtitle: 'Artist: Morcheeba',
text: 'Album: Parts of the Process - released 2003'
}
);
await stepContext.context.sendActivity({ attachments: [card]});
Web Chat: First, use Web Chat's store to filter on incoming activities that include attachments where the button type (action) is postBack. When the condition is met, get the last card rendered and assign an event listener. When the card's button is clicked, get the 'spotify' container element and update the innerHTML with the embed code that was sent in the activity, thus displaying the play button.*
Please note, the setTimeout() used below is necessary for enabling the click action. Without the time out, the event listener being appended to the button would occur before the store finished processing the incoming activity.
<div id="webchat" role="main"></div>
<div class='spotify'></div>
[...]
const store = window.WebChat.createStore( {}, ( { dispatch } ) => next => action => {
if ( action.type === 'DIRECT_LINE/INCOMING_ACTIVITY' ) {
const activity = action.payload?.activity;
if (activity.attachments && activity.attachments[0].content.buttons[0]?.type === 'postBack') {
setTimeout(() => {
const spotifyIframe = activity.attachments[0].content.buttons[0].value
let cards = document.querySelectorAll( '.ac-adaptiveCard' )
let cardLength = cards.length;
let card = cards[ cardLength - 1 ];
card.querySelectorAll( 'button' ).forEach( button => {
button.addEventListener( 'click', ( e ) => {
e.preventDefault();
const spotifyContainer = document.querySelector( '.spotify' );
spotifyContainer.innerHTML = spotifyIframe
} )
} );
}, 300);
}
next( action );
} );
Hope of help!

Stipe Checkout Form does not send token to server

I am trying to integrate a stripe checkout form onto my website which is run from a node.js server on heroku.
The form to collect payment information is provided by stripe:
<form action="/updatepayment" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_DNdN11LpouG0f1x4_____"
data-amount="999"
data-name="[Name]"
data-description="Widget"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto">
</script>
</form>
This are the instructions stripe gives:
The simple integration uses a <script> tag inside your payment form to render the blue Checkout button. Upon completion of the Checkout process, Checkout submits your form to your server, passing along a stripeToken and any elements your form contains. When adding the following code to your page, make sure that the form submits to your own server-side code within the action attribute
I have also tried different data-keys with no success. When the form is submitted, the page is redirected to the current page and the url then contains the token but nothing is sent to the server.
You can try below method
just add
<script src="https://checkout.stripe.com/checkout.js"></script>
in index.html File
and add <button (click)="openCheckout()">Purchase</button> in your component html File
and in ts file add below code
openCheckout() {
var tok=this;
var handler = (<any>window).StripeCheckout.configure({
key: '', // Enter your publishable key
locale: 'auto',
token: function (token: any) {
tok.token1(token);
}
});
handler.open({
name: 'Food Style',
description: 'Payment',
amount: this.price * 100,
});
}
token1(token){
console.log(token);
this.paymentservice.defaultcard(token)
.subscribe((result)=>{
console.log(result);
},
(err)=>{
console.log(err);
})
}

Stripe payment without any button

Currently I'm using a stripe payment button as a way to charge users. however, the process for this is:
they get an email, the email has a pay button.
once you press the button, the button launches a page with a stripe pay button.
pressing the stripe pay button opens the card payment.
I'd like to be able go straight from the user pressing the email's pay button to the card payment page opening up, instead of them having to press another button.
I've been using https://stripe.com/docs/checkout. I think that calling the stripecheckout.open directly would do the trick, however, I'm not sure how to format this call correctly with javascript.
For example, when the email pay button is pressed, the stripe pay button is generated like this
res.write('<script ');
res.write('src="https://checkout.stripe.com/v2/checkout.js" class="stripe-button"');
res.write('data-key="' + body[0].data_key + '"');
res.write('data-amount="' + body[0].data_amount +'"');
res.write('data-name="' + body[0].data_name + '"');
data_desc_string = body[0].data_description;
data_desc_short = data_desc_string.substring(7);
res.write('data-description="' + data_desc_short + '"');
res.write('data-currency="usd">');
res.write('</script>');
I'm not sure how I should rewrite it just for the stripecheckout.open.
The Custom Buttons section of the Checkout docs details how to call StripeCheckout.open().
In your case, you simply call StripeCheckout.open() once the page has loaded (because you want it to appear immediately) instead of in response to a button click (as in the example).
How exactly you'd go about that would vary with the JS framework you're using. Using jQuery as in their example code, you'd bind to $(document).ready():
<script src="https://checkout.stripe.com/v2/checkout.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<button id="customButton">Purchase</button>
<script>
$(document).ready(function(){
var token = function(res){
var $input = $('<input type=hidden name=stripeToken />').val(res.id);
$('form').append($input).submit();
};
StripeCheckout.open({
key: 'pk_test_czwzkTp2tactuLOEOqbMTRzG',
address: true,
amount: 5000,
currency: 'usd',
name: 'Joes Pistachios',
description: 'A bag of Pistachios',
panelLabel: 'Checkout',
token: token
});
return false;
});
</script>

How do you post data to CouchDB both with and without using JavaScript

I have a show which displays a form with fields populated from a document. I'd like to change the values in the field and then save the updated document.
I'm having trouble finding a clear, concise example of how to do this.
Seriously, just finishing this example would work wonders for so many people (I'm going to leave a lot of stuff out to make this concise).
Install Couchapp
This is outside the scope of my question, but here are the instructions for completeness.
Create a couchapp
Again, this is kind outside the scope of my question. Here is a perfectly concise tutorial on how to create a couchapp.
Create a template
Create a folder in the root of your couchapp called templates. Within the templates folder create an HTML page called myname.html. Put the following in it.
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<form method='post' action='#'>
<fieldset>
Hello <input type='text' name='name' value='{{ name }}'>
<input type='submit' name='submit' value='submit'>
</form>
</body>
</html>
Create a show
See the tutorial above for hwo to do this.
Add this code to a show called myname.
function(doc, req) {
if (doc) {
var ddoc = this
var Mustache = require("vendor/couchapp/lib/mustache");
var data = {
title: "The Name",
name: "Bobbert"
}
return Mustache.to_html(ddoc.templates.myname, data)
} else {
return ('nothing here baby')
}
}
Update the document with a new name by ...
So who can complete this step via both the client side and the server side?
Please don't point me to the guide, I need to read it in your words.
Thanks.
Edit:
Although the return value isn't pretty, just posting a form to the update handler will update the document.
You will probably want to look into update handler functions.
An update handler handles granular document transformations. So you can take 1 form, that has one distinct purpose, and only update the relevant fields in your document via the update handler.
Your update handler will need to take a PUT request from your form. A browser can't do this directly, so you'll need some javascript to handle this for you. If you're using jQuery, this plugin can take your form and submit it seamlessly via AJAX using PUT for you.
Inside the function, you can take the fields you are accepting, in this case name and apply that directly to the document. (input validation can be handled via the validate_doc_update function)
Update Handler (in your Design Document)
{
"updates": {
"name": function (doc, req) {
doc.name = req.form.name;
return [doc, "Name has been updated"];
}
}
}
HTML
<form id="myForm" action="/db/_design/ddoc/_update/name/doc_id">...</form>
JavaScript
$(document).ready(function() {
$('#myForm').ajaxForm({
type: "PUT",
success: function () {
alert("Thank you");
}
});
});
Once you've gotten this basic example up and running, it's not much more difficult to add some more advanced features to your update handlers. :)

Resources