when I refreshed the page in stripe it take payment (incomplete) php - javascript

Hi I am working in stripe and accept a payment through googlepay all my code working fine and I am accept payment.
This is my code
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Google Pay</title>
<script src="https://js.stripe.com/v3/"></script>
<?php include_once 'google.php';?>
</head>
<body>
<main>
home
<h1>Google Pay</h1>
<div id="payment-request-button">
<!-- A Stripe Element will be inserted here if the browser supports this type of payment method. -->
</div>
<div id="messages" role="alert" style="display: none;"></div>
</main>
</body>
</html>
`
this is my google.php
<?php require("stripe-php-master/init.php");
\Stripe\Stripe::setApiKey('sk_test_456'); $paymentIntent = \Stripe\PaymentIntent::create([ 'amount' => 2099, 'currency' => 'usd', ]);
?>
<script>
document.addEventListener('DOMContentLoaded', async () => {
// 1. Initialize Stripe
const stripe = Stripe("pk_test_51KdBQoC6Dz9QDrkL2stCBgcvY8936IiXUIpIjVD8n4Ug6jTs3QSEUnC9iSHrdPnSI20vxwNC6GTdEmXlBDw8UpP6005xVobO9", {
apiVersion: '2020-08-27',
});
// 2. Create a payment request object
var paymentRequest = stripe.paymentRequest({
country: 'US',
currency: 'usd',
total: {
label: 'Demo total',
amount: 1999,
},
requestPayerName: true,
requestPayerEmail: true,
});
// 3. Create a PaymentRequestButton element
const elements = stripe.elements();
const prButton = elements.create('paymentRequestButton', {
paymentRequest: paymentRequest,
});
// Check the availability of the Payment Request API,
// then mount the PaymentRequestButton
paymentRequest.canMakePayment().then(function (result) {
if (result) {
prButton.mount('#payment-request-button');
} else {
document.getElementById('payment-request-button').style.display = 'none';
addMessage('Google Pay support not found. Check the pre-requisites above and ensure you are testing in a supported browser.');
}
});
paymentRequest.on('paymentmethod', async (e) => {
// Make a call to the server to create a new
// payment intent and store its client_secret.
addMessage(`Client secret returned.`);
let clientSecret = '<?= $paymentIntent->client_secret; ?>';
// Confirm the PaymentIntent without handling potential next actions (yet).
let {error, paymentIntent} = await stripe.confirmCardPayment(
clientSecret,
{
payment_method: e.paymentMethod.id,
},
{
handleActions: false,
}
);
if (error) {
addMessage(error.message);
// Report to the browser that the payment failed, prompting it to
// re-show the payment interface, or show an error message and close
// the payment interface.
e.complete('fail');
return;
}
// Report to the browser that the confirmation was successful, prompting
// it to close the browser payment method collection interface.
e.complete('success');
// Check if the PaymentIntent requires any actions and if so let Stripe.js
// handle the flow. If using an API version older than "2019-02-11" instead
// instead check for: `paymentIntent.status === "requires_source_action"`.
if (paymentIntent.status === 'requires_action') {
// Let Stripe.js handle the rest of the payment flow.
let {error, paymentIntent} = await stripe.confirmCardPayment(
clientSecret
);
if (error) {
// The payment failed -- ask your customer for a new payment method.
addMessage(error.message);
return;
}
addMessage(`Payment ${paymentIntent.status}: ${paymentIntent.id}`);
}
addMessage(`Payment ${paymentIntent.status}: ${paymentIntent.id}`);
});
});
const addMessage = (message) => {
const messagesDiv = document.querySelector('#messages');
messagesDiv.style.display = 'block';
messagesDiv.innerHTML += '>' + message + '<br>';
console.log('StripeSampleDebug:', message);
}
</script>`
I am stuck whenever i refreshed page it charge payment incomplete and its irritating .I need that when user click on the pay button then they charge payment and it work fine but when i refreshed it charged payment and show in payment section stripe incomplete.

Related

How to create new property in google analytics using javascript code

This is my first time using analytics api to create new property
I got the below code from here
developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/webproperties/insert
window.onload = function insertProperty() {
var request = gapi.client.analytics.management.webproperties.insert(
{
'accountId': '123456789',
'resource': {
'websiteUrl': 'http://www.examplepetstore.com',
'name': 'Example Store'
}
});
request.execute(function (response) { console.log(response);});
}
<script src="https://apis.google.com/js/api.js"></script>
when i run the code with valid account id ex:'123456789'
I am getting this error
Uncaught TypeError: Cannot read properties of undefined (reading 'analytics') at insertProperty
what should i do to create new property using this code
The below code is the setup of authorization and rest code
// Replace with your client ID from the developer console.
var CLIENT_ID = '';
// Set authorized scope.
var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];
function authorize(event) {
// Handles the authorization flow.
// `immediate` should be false when invoked from the button click.
var useImmdiate = event ? false : true;
var authData = {
client_id: CLIENT_ID,
scope: SCOPES,
immediate: useImmdiate
};
gapi.auth.authorize(authData, function(response) {
var authButton = document.getElementById('auth-button');
if (response.error) {
authButton.hidden = false;
}
else {
authButton.hidden = true;
queryAccounts();
}
});
}
function queryAccounts() {
// Load the Google Analytics client library.
gapi.client.load('analytics', 'v3').then(function() {
// Get a list of all Google Analytics accounts for this user
gapi.client.analytics.management.accounts.list().then(handleAccounts);
});
}
function handleAccounts(response) {
// Handles the response from the accounts list method.
if (response.result.items && response.result.items.length) {
// Get the first Google Analytics account.
var firstAccountId = response.result.items[0].id;
// Query for properties.
queryProperties(firstAccountId);
} else {
console.log('No accounts found for this user.');
}
}
function queryProperties(accountId) {
// Get a list of all the properties for the account.
gapi.client.analytics.management.webproperties.list(
{'accountId': accountId})
.then(handleProperties)
.then(null, function(err) {
// Log any errors.
console.log(err);
});
}
function handleProperties(response) {
// Handles the response from the webproperties list method.
if (response.result.items && response.result.items.length) {
// Get the first Google Analytics account
var firstAccountId = response.result.items[0].accountId;
// Get the first property ID
var firstPropertyId = response.result.items[0].id;
// Query for Views (Profiles).
queryProfiles(firstAccountId, firstPropertyId);
} else {
console.log('No properties found for this user.');
}
}
function queryProfiles(accountId, propertyId) {
// Get a list of all Views (Profiles) for the first property
// of the first Account.
gapi.client.analytics.management.profiles.list({
'accountId': accountId,
'webPropertyId': propertyId
})
.then(handleProfiles)
.then(null, function(err) {
// Log any errors.
console.log(err);
});
}
function handleProfiles(response) {
// Handles the response from the profiles list method.
if (response.result.items && response.result.items.length) {
// Get the first View (Profile) ID.
var firstProfileId = response.result.items[0].id;
// Query the Core Reporting API.
queryCoreReportingApi(firstProfileId);
} else {
console.log('No views (profiles) found for this user.');
}
}
function queryCoreReportingApi(profileId) {
// Query the Core Reporting API for the number sessions for
// the past seven days.
gapi.client.analytics.data.ga.get({
'ids': 'ga:' + profileId,
'start-date': '7daysAgo',
'end-date': 'today',
'metrics': 'ga:sessions'
})
.then(function(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
})
.then(null, function(err) {
// Log any errors.
console.log(err);
});
}
// Add an event listener to the 'auth-button'.
document.getElementById('auth-button').addEventListener('click', authorize);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Analytics - A quickstart guide for JavaScript</title>
</head>
<body>
<button id="auth-button" hidden>Authorize</button>
<h1>Hello Analytics</h1>
<textarea cols="80" rows="20" id="query-output"></textarea>
<script src="https://apis.google.com/js/client.js?onload=authorize"></script>
</body>
</html>
yes i did , when i click on Authorize i got this Error {error: {code: 403, message: "Request had insufficient authentication scopes.",…}}
not sure why..?
The developer hasn’t given you access to this app. It’s currently being tested and it hasn’t been verified by Google
The issue is that your project is still in testing, you need to add users who you want to grant permission to test your app.
Go to google cloud console Under consent screen look for the button that says "add Users" add the email of the user you are trying to run the app with.
Understanding Property, Account, and View in Google Analytics
Your Analytics profile consists of 3 different components. They are account, property, and view (if you’re using Universal Analytics).
Here’s a closer look at each of them:
Account: You should have at least one account to access the analytics report.
Property: A property can be a website or a mobile app that you’d like to track in Google Analytics and has a unique tracking ID.
View: A view is the access point for your reports if you’re using Universal Analytics. For example, within a property you can have different views for viewing all the data for your website, viewing only a specific subdomain, like blog.example.com, or viewing only Google Ads traffic. Views do not exist in Google Analytics 4.

Using global variables properly in node.js or is there a better way of doing this?

I am trying to get a user entered amount from my checkout.html file ( below ) so that I can use it in the Stripe code on the server.js node server.
I wasn't able to get the amount field from the form to work so I disabled it and am working with console.log and variables. I was trying to make it work with a global variable passing the value.
These 2 files from the example on the Stripe website ( you select 'node' and 'html' from the page, and click 'prebuilt' also )
https://stripe.com/docs/checkout/integration-builder
My alterations
( sorry the var assignments numbers are all just random for testing )
**server.js**
( lines 8-9 )
var test = 2242;
// console.log( amountglobal);
( line 22 )
unit_amount: test,
**checkout.html** (line 47 )
amountglobal = 67865555;
My issue is that if I uncomment line 9 ( with the aim of trying to use the amountglobal gloabal var in line 22 ) then for some reason the server wont start, saying amountglobal is not defined ... so I possibly have the global variable wrong in checkout.html, it's
amountglobal = 67865555;
... and maybe there's a better way of doing this in the first place, I understand global variables are not the ideal usually.
The end result here is to be a payment form where the user can type in their own ( previously agreed) price.
Thanks.
FULL FILES
server.js
const stripe = require('stripe')
('sk_test_51IAvl4KYIMptSkmlXwuihwZa8jtdIrnD79kSQcnhvQKbg9dbAXiZisFmasrKHIK9B75d9jgeyYK8MULLbFGrGBpU00uQgDvtnJ');
const express = require('express');
const app = express();
app.use(express.static('.'));
const YOUR_DOMAIN = 'http://localhost:4242';
var test = 2242;
console.log( amountglobal);
app.post('/create-checkout-session', async (req, res) => {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: 'Stubborn Attachments',
images: ['https://i.imgur.com/EHyR2nP.png'],
},
unit_amount: test,
},
quantity: 1,
},
],
mode: 'payment',
success_url: `${YOUR_DOMAIN}/success.html`,
cancel_url: `${YOUR_DOMAIN}/cancel.html`,
});
res.json({ id: session.id });
});
app.listen(4242, () => console.log('Running on port 4242'));
Checkout.html
<!DOCTYPE html>
<html>
<head>
<title>Buy cool new product</title>
<link rel="stylesheet" href="style.css">
<script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<section>
<div class="product">
<img
src="https://i.imgur.com/EHyR2nP.png"
alt="The cover of Stubborn Attachments"
/>
<div class="description">
<h3>Stubborn Attachments</h3>
<h5>$20.00</h5>
</div>
</div>
<form id="frm12" action="#">
First name: <input type="text" name="amount" value = "435"><br>
<!-- <input type="button" onclick="myFunction()" value="Submit"> -->
<input type="submit" id="checkout-button" value="Checkout">
</form>
</section>
</body>
<script type="text/javascript">
function myFunction() {
console.log("test");
document.getElementById("frm1").submit();
}
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe("pk_test_51IAvl4KYIMptSkmlAwhNvG0CDJRnr2hyrJuRnfdnfaEEhHPwCWsr9QK183a1pKUQ4PLrrtEqiElFLTVHIiSueX6r00TyXooIcu");
var checkoutButton = document.getElementById("checkout-button");
var amount = document.getElementById("amount");
amountglobal = 67865555;
// console.log(amount);
checkoutButton.addEventListener("click", function () {
fetch("/create-checkout-session", {
method: "POST",
})
.then(function (response) {
return response.json();
})
.then(function (session) {
console.log('here');
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function (result) {
// If redirectToCheckout fails due to a browser or network
// error, you should display the localized error message to your
// customer using error.message.
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
console.error("Error:", error);
});
});
</script>
</html>
You need to POST the data from your client side code to your server side code, and then use a JSON body parser with Express so that it ends up in the server-side request.

Stripe client intergration not taking affect after I click buy now link

I followed this documentation and my stripe checkout is not working. I have taken out the sku and pk from the SO snippet below but can anybody see what I have done wrong as I thought I implemented it correctly.
When I click the buy now link, nothing happens, don't even redirect to the checkout page.
HTML link:
<a class="buy-btn">Buy Now</a>
...
Javascript:
<script>
(function () {
var stripe = Stripe('pk_test_xxx');
var checkoutButton = document.getElementsByClassName('buy-btn');
checkoutButton.addEventListener('click', function () {
// When the customer clicks on the button, redirect
// them to Checkout.
stripe.redirectToCheckout({
items: [{ sku: 'sku_xxx', quantity: 1 }],
// 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/fulfillment
successUrl: window.location.protocol + '//www.xxx-online.com/xxx-leap/success',
cancelUrl: window.location.protocol + '//www.xxx-online.com/xxx-leap/cancelled',
})
.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;
}
});
});
})();

Paypal Sandbox App login error

I've a problem with my sandbox app. I integrated the script given for the paypal checkout express payment in my web app. This the script :
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<div id="paypal-button-container"></div>
<script>
var total = 0;
$.getJSON("/Home/getTotal", function (result) {
total = result;
});
// Render the PayPal
paypal.Button.render({
// Set your environment
env: 'sandbox', // sandbox | production
// Specify the style of the button
style: {
label: 'buynow',
fundingicons: true, // optional
branding: true // optional
},
// PayPal Client IDs - replace with your own
// Create a PayPal app: https://developer.paypal.com/developer/applications/create
client: {
sandbox: 'AT9iydEDhcqfM_dhU8MR0lvkFgZBjD1oXQVrG-CR9CyK_vd-aXpNzEnyVV7um_hAPrkqQX8JhtjGCbBt'
},
// Wait for the PayPal button to be clicked
payment: function (data, actions) {
return actions.payment.create({
transactions: [
{
amount: { total: total, currency: 'USD' }
}
]
});
},
// Wait for the payment to be authorized by the customer
onAuthorize: function (data, actions) {
return actions.payment.execute().then(function () {
window.alert('Payment Complete!');
});
}
}, '#paypal-button-container');
</script>
This code displays a paypal button. When I click on the button, it shows me a login page to proceed to the payement. The problem is : I can't login on this page with a paypal account that I have. I read somewhere that only the sandbox's test accounts can be used to login on this page, but I want to let everyone who has a paypal account login in this page. What should I do ? Thank you for your answers!
I've found the solution : if you want to let everybody login into your payment's page, you've to pass to production mode.

PayPal in-context checkout doesn't always trigger startFlow?

We've built an online store that integrates the PayPal in-context / express checkout. This is using the Classic NVP API.
It has been receiving the token every time and logging to the console that it is starting the payment flow. However, every now and then it will not redirect the modal to the checkout, but I can run paypal.checkout.startFlow('<token_from_console>'); in the console and it successfully redirects.
Here's the js for the checkout process:
window.paypalCheckoutReady = function () {
paypal.checkout.setup('<?=$paypal_merchantID?>', {
locale: 'en_AU',
<? if ($paypal_platform == 'sandbox') { ?>environment: 'sandbox',<? } ?>
button: ['submitButton'],
condition: function() {
return $('#orderForm').valid();
},
click: function() {
// INITIALISE CHECKOUT
paypal.checkout.initXO();
// SET EXPRESS CHECKOUT AND GET TOKEN
setCheckout = $.post("/checkout.php?mode=setExpressCheckout", $("#orderForm").serialize());
setCheckout.done(function(response){
console.log(response);
if (response.substr(0,2) == 'EC') {
paypal.checkout.startFlow(response);
console.log('starting paypal flow');
}
});
setCheckout.fail(function(reponse){
paypal.checkout.closeFlow();
});
}
});
};

Categories

Resources