How to intergrate with Stripe Checkout JS/HTML - javascript

I am trying to follow this documentation in trying to implement stripe's checkout:
https://stripe.com/docs/payments/checkout/one-time
I currently haven't got it working as when I click my buy now button in my html file, it doesn't do anything (this is through my localhost for test purposes). When I say it doesn't do anything, I mean I click the button and nothing loads, remain on the same page.
Below is the html code for the buy now button along with sone javascript code:
<script src="https://js.stripe.com/v3/"></script>
...
<a class="buy-btn" onclick="showStripe()">Buy Now</a>
...
<script src="myScript.js"></script>
<script src="stripe.js"></script>
I then have two javascript files that deal with the stripe and which you can compare with the documentation:
myScript.js:
var stripe = Stripe('pk_test_xxxx'); //xxxx out key for SO
function showStripe(){
stripe.redirectToCheckout({
// Make the id field from the Checkout Session creation API response
// available to this file, so you can provide it as parameter here
// instead of the {{CHECKOUT_SESSION_ID}} placeholder.
sessionId: '{{CHECKOUT_SESSION_ID}}'
}).then(function (result) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `result.error.message`.
});
}
stripe.JS
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
const stripe = require('stripe')('sk_test_xxxx'); //xxxx out key for SO
(async () => {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [{
name: 'title',
description: 'description',
images: ['img/top-view-img.jpg'],
amount: 25,
currency: 'gbp',
quantity: 1,
}],
payment_intent_data: {
capture_method: 'manual',
},
success_url: 'http://localhost:8080/order-confirmation',
cancel_url: 'http://localhost:8080/',
});
})();
My question is simply how can I get this to work?

The stripe.JS file you have there is server-side code, meant to run on Node.js - it won't work in the browser, and you should never ever share your Secret Key.
You can do client-only (i.e., only in the browser) Checkout, but it's a different approach: https://stripe.com/docs/payments/checkout/client-only

Related

serverless - How to dynamically add resources generated from a javascript file and merge them with other resources?

I want to create a serverless file that deploys Cognito resources to AWS. I have a config.yml file that holds all the scopes that should be created in the Cognito Resource Server.
config.yml
- name: scope1
description: Description of scope1
- name: scope2
description: Description of scope2
What I want to accomplish is to dynamically generate one Cognito App Client for each scope we register, as well as adding these scopes to a Cognito Resource Server (in my case, the Cognito User Pool and Domain Name are already created).
To do that, I tried to make a javascript file that will load the config.yml file and generate two variables:
userPoolClientList which holds a list of Cognito App Client resources.
scopeList which represents a list of scopes that should be registered in the Cognito Resource Server.
sls-template.js
const fs = require("fs");
const yaml = require("js-yaml");
const scopeList = yaml.safeLoad(fs.readFileSync("config.yml"));
module.exports = {
scopeList: function () {
return scopeList.map(({ name, description }) => ({
ScopeName: name,
ScopeDescription: description,
}));
},
userPoolClientList: function (serverless) {
const { cognitoUserPoolId } = serverless.service.custom;
const scopeResourceList = scopeList.map(({ name, description }) => ({
[`cognitoUserPoolClient-${name}`]: {
Type: "AWS::Cognito::UserPoolClient",
Properties: {
AllowedOAuthScopes: [`server/${name}`],
UserPoolId: cognitoUserPoolId,
},
DependsOn: "cognitoResourceServer",
},
}));
return Object.assign({}, ...scopeResourceList);
},
};
Now this looks like it returns exactly what I wanted (I've tested it and it works great).
My problem is rather in the implementation on the serverless.yml file and how to combine a fixed Resources and a dynamically generated one.
serverless.yml
resources:
Resources:
${file(sls-template.js):userPoolClientList}
cognitoResourceServer:
Type: AWS::Cognito::UserPoolResourceServer
Properties:
Identifier: server
Name: Server
Scopes: ${file(sls-template.js):scopeList}
UserPoolId: ${self:custom.cognitoUserPoolId}
This throws an error as the syntax is not correct. However, when I try to deploy the resources individually (one time just the cognitoResourceServer resource, the other time the generated variable from the javascript file), everything works fine.
The problem really is on how I should combine or merge these two resources.
I've been trying a lot of different combinations to try to make it work, but it always give me an invalid template.
So I was wondering if what I try to accomplish is even possible in serverless and if so, how can I change my final serverless.yml file to make it work.
Thanks a lot.
Yes resource blocks can be merged.
I believe this should do it:
resources:
- Resources: ${file(sls-template.js):userPoolClientList}
- Resources:
cognitoResourceServer:
Type: AWS::Cognito::UserPoolResourceServer
Properties:
Identifier: server
Name: Server
Scopes: ${file(sls-template.js):scopeList}
UserPoolId: ${self:custom.cognitoUserPoolId}
Not 100% sure whether the dynamic block needs to generate Resources top-level key or whether you can hard-code it like I've shown in the example.

Paylike modal amount parameter

I'm currently testing the paylike's web sdk and I can use the sandbox easy. But how can I avoid the user can change the amount on the client side? The amount parameter is required, but how can I ensure about after a success callback about the amount? Can I get it from the server side?
The following code is fine, but I have problem with the amount parameter
<script src="//sdk.paylike.io/3.js"></script>
<script>
var paylike = Paylike('your key');
paylike.popup({
currency: 'DKK',
amount: 1000,
}, function( err, res ){
if (err)
return console.log(err);
console.log(res.transaction.id);
alert('Thank you!');
});
</script>
Two steps are important regarding transactions. The first step is authorization.
Authorization is done with the code you added here, on the frontend. The user can tamper with the amount, but this is merely a reservation and is not taking funds from the payer credit card.
The second step is called capture. You can only capture the funds from the Paylike dashboard, or via your server. When you do that, you generally send the same amount that you initially wanted the user to pay, and if the authorization were less, you would get an error. You can also fetch the transaction to inspect the amount that was authorized if you want to reject an order, for example. You can also send a custom parameter that you might use to validate on the server, similar to a checksum if you want to.
You have a private key, which users are not able to get, so that makes it safe. The 2 step approach is a validation on its own, but as I mentioned, you can also inspect the transaction.
You can check the API docs here: https://github.com/paylike/api-docs, where you will also find links to client-side SDKs.
If you are using PHP, using the PHP library (which I maintain) you can do this to inspect a transaction:
$paylike = new \Paylike\Paylike($private_api_key);
$transactions = $paylike->transactions();
$transaction = $transactions->fetch($transaction_id);
The transaction variable will look like this:
{
"id":"5da8272132aad2256xxxxxxx",
"test":true,
"merchantId":"594d3c455be12d547xxxxxx",
"created":"2019-10-17T08:32:34.362Z",
"amount":35,
"refundedAmount":0,
"capturedAmount":0,
"voidedAmount":0,
"pendingAmount":35,
"disputedAmount":0,
"card":{
"id":"5da82743735e61604xxxxxxx",
"bin":"410000",
"last4":"0000",
"expiry":"2023-11-30T22:59:59.999Z",
"code":{
"present":true
},
"scheme":"visa"
},
"tds":"none",
"currency":"JPY",
"custom":{
"email":"customer#example.com",
"orderId":"Could not be determined at this point",
"products":[
[
{
"ID":"48",
"name":"Hoodie with Pocket",
"quantity":"1"
}
]
],
"customer":{
"name":"John Doe",
"email":"customer#example.com",
"phoneNo":"020 91X XXXX",
"address":"123 Main Street, New York, NY 10030",
"IP":"10.0.2.2"
},
"platform":{
"name":"WordPress",
"version":"5.2.4"
},
"ecommerce":{
"name":"WooCommerce",
"version":"3.7.1"
},
"paylikePluginVersion":"1.7.2"
},
"recurring":false,
"successful":true,
"error":false,
"descriptor":"PHP API WRAPPER TEST",
"trail":[
]
}

Office.context.mailbox.displayNewMessageForm not able to attach files in outlook online clients

We are using Office.context.mailbox.displayNewMessageForm api for creating compose form in that we are adding attachments parameter with type set to file. But in this scenario, Outlook is not able to attach file in compose form of outlook online clients whereas the same scenario is working in windows Outlook 2016 and outlook for Mac.
We are referring to the example below, given in https://learn.microsoft.com/en-us/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox#displaynewmessageformparameters
Office.context.mailbox.displayNewMessageForm(
{
// Copy the To line from current item.
toRecipients: Office.context.mailbox.item.to,
ccRecipients: ['sam#contoso.com'],
subject: 'Outlook add-ins are cool!',
htmlBody: 'Hello <b>World</b>!<br/>',
attachments: [
{
type: 'file',
name: 'image.png',
url: 'http://contoso.com/image.png',
isInline: false
}
]
});
After using this api outlook creates new compose form with attachment (Note: I can't view or download that attachment, it is attached as label only). Refer to this image for more details
And, that attachment vanishes after some time and outlook gives an error in notification bar i.e. The following file couldn't be attached: image.png. Please try again later.Refer this image for more details
Also the same api is able to attach items in outlook online clients when attachments.type is set to item as follows:
attachments: [
{
type: 'item',
name: 'filename.png',
itemId: ewsId
}
]
Can anyone suggest why is this happening and any workaround for the above issue?

Integrating GiroPay and SOFORT via Stripe

I tried to integrate the other offered payments offered by stripe. I followed the docs but it seems I overread something (read everthing like 10 times).
First I activated the payment methods.
I added the library: <script src="https://js.stripe.com/v3/"></script>
I created a Stripe client: var stripe = Stripe('pk_live_512dfvL8d63Kcs9d5Lsp548c6Sp'); (tried this with both test and publishable key)
I added an instance of Elements: var elements = stripe.elements(); (Not using it though)
Depending on the choosen payment something else gets triggered. Well here is my code:
function buyingProcess() {
console.log(choosenPaymentMethod);
if (choosenPaymentMethod == "mastervisa") {
// This works like a charm
} else if (choosenPaymentMethod == "giropay") {
stripe.createSource({
type: 'giropay',
amount: 1099,
currency: 'eur',
owner: {
name: 'Jenny Rosen',
},
redirect: {
return_url: 'https://shop.example.com/crtA6B28E1',
},
}).then(function(result) {
console.log(result);
// handle result.error or result.source
});
}
}
The last console.log function shows me the source object. While using the test key console.log(result.error) stated out, that I have to use the publishable key.
Thanks for any help. I wrote the Stripe Team. yesterday at this time but I apreciate any help. Thanks.
If you are seeing a source object in your console, then you have successfully created a source! The next step is to set up a webhook endpoint, and listen for a source.chargeable event.
Once you have received that your customer has authorized the source to be charged, and you can create a charge on your server using your secret key:
https://stripe.com/docs/sources/best-practices#charge-creation
You can delete var elements = stripe.elements(); as you don't need Elements to create sources, just the Stripe.js library.

After creating source in stripe using stripe.js stripeResponseHandler function is not calling

i have been trying from last 4 hours but this problem is not solving. i am creating charge for bitcoin using stripe.js.
the charge is creating successfully but after creating the charge the function "stripeResponseHandler" is not calling. I have try so many things but it no avail.
my code is
stripe.createSource({
type: 'bitcoin',
amount: 1000,
currency: 'usd',
owner: {
email: 'jenny.rosen#example.com',
},
}, stripeResponseHandler);
function stripeResponseHandler(status, response) {
console.log("here");
console.log(status);
console.log(response);
}
Nothing is printing on the console. I have checked my dashboard events and logs and the charge is creating.
Thanks in advance.
I also struggled to extract the data from Stripe's create source response. This worked for me:
stripe.createSource({type: 'card', owner: {
name: 'Jenny Rosen'
}}).then(function(result, err) {
console.log(result.source)
console.log(err.source)
});
If you need to extract the Id, replace result.source with result.source.id and so on. Here is the API reference.
Also, make sure you enable the View test data switch and use Stripe's test cards. You can find all the calls to your stripe account under Developers > Logs in your dashboard.

Categories

Resources