Error: "Hosted Fields payment is already in progress."
I have copied it from this PayPal documentation, and in the SDK URL pass a proper sandbox clientID.
if (paypal.HostedFields.isEligible()) {
paypal.HostedFields.render({
createOrder: function () {return "order-ID";}, // replace order-ID with the order ID
styles: {
'input': {
'font-size': '17px',
'font-family': 'helvetica, tahoma, calibri, sans-serif',
'color': '#3a3a3a'
},
':focus': {
'color': 'black'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: 'card number'
},
cvv: {
selector: '#cvv',
placeholder: 'card security number'
},
expirationDate: {
selector: '#expiration-date',
placeholder: 'mm/yy'
}
}
}).then(function (hf) {
$('#my-sample-form').submit(function (event) {
event.preventDefault();
hf.submit({
// Cardholder Name
cardholderName: document.getElementById('card-holder-name').value,
// Billing Address
billingAddress: {
streetAddress: document.getElementById('card-billing-address-street').value, // address_line_1 - street
extendedAddress: document.getElementById('card-billing-address-unit').value, // address_line_2 - unit
region: document.getElementById('card-billing-address-state').value, // admin_area_1 - state
locality: document.getElementById('card-billing-address-city').value, // admin_area_2 - town / city
postalCode: document.getElementById('card-billing-address-zip').value, // postal_code - postal_code
countryCodeAlpha2: document.getElementById('card-billing-address-country').value // country_code - country
}
});
});
});
}
You need to replace "order-ID" with an actual PayPal Order ID created for this checkout.
There are several ways to obtain one. See https://developer.paypal.com/docs/business/checkout/server-side-api-calls/#server-side-api-calls for how to call the orders API from your server to 'Create Order' and 'Capture Order'. You should use these to create two routes on your server that return only JSON data (no HTML or text)
As for how to fetch and commit this from the JS UI, see https://developer.paypal.com/demo/checkout/#/pattern/server for some demo code.
Alternatively, you could try doing an HTML/JS-only integration (no server) like https://developer.paypal.com/demo/checkout/#/pattern/client
Related
i have one form if user enter his details on his form and submit form, after submit form it stores to database and after successfully store users data in database only then i have to open paypal checkout modal otherwise not.
this is paypal
paypal.Button.render({
env: 'sandbox',
client: {
sandbox: ''
// production: 'demo_production_client_id'
},
locale: 'en_US',
style: {
layout: 'horizontal',
size: 'small',
color: 'blue',
shape: 'pill',
label: 'checkout',
height: 40,
tagline: 'false'
},
commit: true,
payment: (data, actions) => {
return actions.payment.create({
transactions: [{
amount: {
total: '1',
currency: 'USD'
}
}]
});
},
onAuthorize: function(data, actions) {
return actions.payment.execute()
.then(function() {
window.alert('Thank you for your purchase!');
});
}
}, this.paypalRef.nativeElement);
this is submit form api call
submit(){
const data={
url: this.URL,
email:this.email
}
this.home.websiteScratching(data)
.subscribe(res=>{
},err=>{
console.log(err);
})
}
after submit success response i want to go for paypal checkout process how to do it.. i am stuck.
In short you have to create new component and use dialogRef.
https://material.angular.io/components/dialog/overview
const dialogRef = this.dialog.open(SuccessPaymentPaypalComponent, {
disableClose: true,
data: { PaypaplRetunrnTrasactionId: this.params.Paypalid }
})
dialogRef.afterClosed().subscribe(() => {
});
I am going thrugh a react project and I came through few lines of code that I am not able to understand. I tried searching for it, but still didn't find anything. The function is as shown below:
export const getLocalizedStrings = (componentName) => {
app.logger.getLogger().info('Comp Name' + componentName);
var strings = getStrings(localizedStrings[componentName].strings,
localizedStrings[componentName].common);
return new LocalizedStrings(strings);
};
So, in the function, the line :
app.logger.getLogger().info('Comp Name' + componentName);
Here, I am not able to understand what's happening. I can see that app is not being imported anywhere in the file.So, I guess it is something that is in-built in javascript.I am sorry if this is something very basic, but I am new to Javascript and React, so can anyone please help me understand what is happening in this line app.logger.getLogger().info('Comp Name' + componentName);? Also, if anyone could help me understand what going on with the overall function it would be very helpful. Thanks in advance.
Edit 1: The code for the whole file is :
import LocalizedStrings from 'react-localization';
import { getStrings } from '../Common/Localization/commonStrings';
const localizedStrings = {
identityDrawerComponent: {
strings: {
en: {
emailErrorMsg : 'This email address is already registered ',
yourAccntSettings : 'Your Account Settings',
emailValidationSuccessMsg : ' is now your login email address. If you need to change it, you can edit it below',
emailValidationErrorMsg : 'The email address has not been added because either the link to verify your email address has expired, or the email address has already been added to you contact information',
activationError :'Activation Error'
}
},
common: ['globalError']
},
identityNameComponent: {
strings: {
en: {
firstName : 'First Name',
lastName : 'Last Name',
editName: 'Edit Name'
},
},
common: ['cancel','save']
},
identityEmailComponent: {
strings : {
en: {
editUserId : 'Edit User ID',
logInEmail : 'Log in email',
pendVerification : 'Pending Verification:',
noPendVerification : 'No pending Email',
confirmChanges : 'Confirm change of User ID to',
pendVerificationDescription : 'A verification email has been sent to your updated email address. Please follow the instructions in the email within 24 hours, or the update will be cancelled.'
},
},
common: ['cancel','save','yes','no']
},
identityPasswordComponent: {
strings : {
en: {
password : 'Password',
editPassword : 'Edit Password'
},
},
common: ['cancel','save']
},
identityLanguageComponent: {
strings : {
en: {
language : 'Language',
editLanguage : 'Edit Language',
languageHelp : 'You may choose to set a preferred language. When content is available in your preferred language, it will be displayed based on this setting; otherwise, content in English will be displayed.'
},
},
common: ['cancel','save']
}
};
export const getLocalizedStrings = (componentName) => {
app.logger.getLogger().info('Comp Name' + componentName);
var strings = getStrings(localizedStrings[componentName].strings,
localizedStrings[componentName].common);
return new LocalizedStrings(strings);
};
is there a way to automatically submit the form after the user has chosen a payment method with the Braintree Drop-in?
The problem is that the user is asked to choose a payment method, then press Ok, then again Ok, then press the actual Checkout button on my page.
It is a very weird behavior.
Here's the code I use to create the Drop-In.
<script>
var form = document.querySelector('#payment-form');
var nonceInput = document.querySelector('#nonce');
braintree.dropin.create({
authorization: '{{ $client_token }}',
container: '#dropin-container',
paypal: {
flow: 'vault',
currency: 'EUR',
buttonStyle: {
color: 'blue',
shape: 'rect',
size: 'medium'
}
},
card: {
cardholderName: true
}
}, function (err, dropinInstance) {
if (err) {
// Handle any errors that might've occurred when creating Drop-in
console.error(err);
return;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
dropinInstance.requestPaymentMethod(function (err, payload) {
if (err) {
// Handle errors in requesting payment method
return;
}
$.fancybox.open({
src : '#processing-loading',
type : 'inline',
opts : {
toolbar: false,
buttons: false,
smallBtn: false
}
});
// Send payload.nonce to your server
nonceInput.value = payload.nonce;
form.submit();
});
});
});
</script>
I'm working with charging credit cards on an ionic application. If I check the Stripe website, only the token is created successfully. There is no event for the charge. When I check Firebase everything seems to be working (previously I had error message "An error occurred with our connection to Stripe" which was eliminated by upgrading to paid version Blaze).
I've structured the following code so you can see the sequence of events.
Here is the sequence of events:
1) Here I get the token and pass to payByStripe function:
checkOut() {
let alert = this.alertCtrl.create({
title: 'card information',
cssClass:'alert-css',
inputs: [{
name: 'cardNumber',
placeholder: 'card number',
},
{
name: 'expMonth',
placeholder: 'expMonth',
},
{
name: 'expYear',
placeholder: 'expYear',
},
{
name: 'cvc',
placeholder: 'cvc',
}],
buttons: [{
text: 'Cancel',
role: 'cancel',
handler: data => {
console.log('Cancel clicked');
}
},
{
text: 'PAY',
handler: data => {
this.stripe.setPublishableKey('pk_test_abcdef1BC');
let card = {
number: data.cardNumber,
expMonth: data.expMonth,
expYear: data.expYear,
cvc: data.cvc
};
this.stripe.createCardToken(card)
.then(token => {
this.goodsData.payByStripe(this.totalMoniesPlusTaxAndCharge,this.userEmail,token);
let alert = this.alertCtrl.create({
title: 'Charged',
cssClass:'alert-css',
subTitle: 'Successful Charge!',
buttons: ['Dismiss']
});
alert.present();
}, error => {
this.loading.dismiss();
let alert = this.alertCtrl.create({
title: 'ERROR',
cssClass:'alert-css',
subTitle: JSON.stringify(error),
buttons: ['Dismiss']
});
alert.present();
})
.catch(error => console.log(JSON.stringify(error)) );
}
}]
});
alert.present();
}
2) Here, I push the charge to Firebase, where cloud functions will handle it:
payByStripe(amount,email,token): firebase.database.Reference {
return firebase.database().ref('/stripe_customers/charges/').push({
amount:amount,
email:email,
token:token
});
}
3) Here is what the cloud functions are doing:
const functions = require('firebase-functions'),
admin = require('firebase-admin'),
logging = require('#google-cloud/logging')();
admin.initializeApp(functions.config().firebase);
const stripe = require('stripe')(functions.config().stripe.token),
currency = functions.config().stripe.currency || 'USD';
// [START chargecustomer]
// Charge the Stripe customer whenever an amount is written to the Realtime database
exports.createStripeCharge = functions.database.ref('/stripe_customers/charges/').onWrite(event => {
const val = event.data.val();
// This onWrite will trigger whenever anything is written to the path, so
// noop if the charge was deleted, errored out, or the Stripe API returned a result (id exists)
if (val === null || val.id || val.error) return null;
// Look up the Stripe customer id written in createStripeCustomer
// Create a charge using the pushId as the idempotency key, protecting against double charges
const amount = val.amount;
const email = val.email;
const token = val.token;
stripe.charges.create({
amount: amount,
currency: "usd",
source: token,
description: "Charge for " + email
}).then(response => {
// If the result is successful, write it back to the database
return event.data.adminRef.set(response);
}, error => {
// We want to capture errors and render them in a user-friendly way, while
// still logging an exception with Stackdriver
return event.data.adminRef.child('error').set(userFacingMessage(error)).then(() => {
return reportError(error, {user: event.params.userId});
});
});
});
// [END chargecustomer]]
I'm pretty sure that's a Firebase-specific error, so if the cause isn't clear, you may want to reach out to them - though someone else with more Firebase experience may have a more useful answer for you!
I am creating a new payment option in website. I implemented the square space successfully. But it creates issue when some one removes any item from the cart.
When ajax is called, it loads the whole content again. but then, form doesn't load and shows console error undefined object SqPaymentForm.
var sqPaymentForm = new SqPaymentForm({
// Replace this value with your application's ID (available from the merchant dashboard).
// If you're just testing things out, replace this with your _Sandbox_ application ID,
// which is also available there.
applicationId: '***********',
inputClass: 'sq-input',
cardNumber: {
elementId: 'sq-card-number',
placeholder: "0000 0000 0000 0000"
},
cvv: {
elementId: 'sq-cvv',
placeholder: 'CVV'
},
expirationDate: {
elementId: 'sq-expiration-date',
placeholder: 'MM/YY'
},
postalCode: {
elementId: 'sq-postal-code',
placeholder: 'Postal Code'
},
inputStyles: [
// Because this object provides no value for mediaMaxWidth or mediaMinWidth,
// these styles apply for screens of all sizes, unless overridden by another
// input style below.
{
fontSize: '14px',
padding: '3px'
},
// These styles are applied to inputs ONLY when the screen width is 400px
// or smaller. Note that because it doesn't specify a value for padding,
// the padding value in the previous object is preserved.
{
mediaMaxWidth: '400px',
fontSize: '18px',
}
],
callbacks: {
cardNonceResponseReceived: function(errors, nonce, cardData) {
if (errors) {
var errorDiv = document.getElementById('errors');
errorDiv.innerHTML = "";
errors.forEach(function(error) {
var p = document.createElement('p');
p.innerHTML = error.message;
errorDiv.appendChild(p);
});
} else {
// This alert is for debugging purposes only.
alert('Nonce received! ' + nonce + ' ' + JSON.stringify(cardData));
// Assign the value of the nonce to a hidden form element
var nonceField = document.getElementById('card-nonce');
nonceField.value = nonce;
// Submit the form
document.getElementById('form').submit();
}
},
unsupportedBrowserDetected: function() {
// Alert the buyer that their browser is not supported
}
}
});
I am using default code provided by gateway doc. Payment option is addon of event manager pro.
It looks like you have forgotten to include this line
<script type="text/javascript" src="https://js.squareup.com/v2/paymentform"></script>
Also note that Square and Squarespace are very different companies.
JSFiddle Link
`
/* onGetCardNonce is triggered when the "Pay $1.00" button is clicked */
function onGetCardNonce(event) {
/* Don't submit the form until SqPaymentForm returns with a nonce */
event.preventDefault();
/* Request a nonce from the SqPaymentForm object */
paymentForm.requestCardNonce();
}
function Initialize(){
console.log("Initialize square");
/* Create and initialize a payment form object */
const paymentForm = new SqPaymentForm({
/* Initialize the payment form elements*/
/* TODO: Replace with your sandbox application ID */
applicationId: "{API_KEY}",
inputClass: 'sq-input',
autoBuild: false,
/* Customize the CSS for SqPaymentForm iframe elements*/
inputStyles: [{
fontSize: '16px',
lineHeight: '24px',
padding: '16px',
placeholderColor: '#a0a0a0',
backgroundColor: 'transparent',
}],
/* Initialize the credit card placeholders */
cardNumber: {
elementId: 'sq-card-number',
placeholder: '{card_number}',
},
cvv: {
elementId: 'sq-cvv',
placeholder: '{cvv}',
},
expirationDate: {
elementId: 'sq-expiration-date',
placeholder: '{mmyy}',
},
postalCode: {
elementId: 'sq-postal-code',
placeholder: '{postal}',
},
/*SqPaymentForm callback functions*/
callbacks: {
/*
* callback function: cardNonceResponseReceived
* Triggered when: SqPaymentForm completes a card nonce request
*/
cardNonceResponseReceived: function (errors, nonce, cardData) {
var errorDiv = $("#square-form-error");
errorDiv.html("");
if (errors) {
/* Log errors from nonce generation to the browser developer console. */
console.error('Encountered errors:');
errors.forEach(function (error) {
console.error(' ' + error.message);
errorDiv.append('<div class="alert alert-danger m-t-15"><strong>' + error.message + '</strong></div>');
});
/*alert('Encountered errors, check browser developer console for more details');*/
return;
}
/* add card_nonce and card_zip parameters */
var $nonceInput = $('<input/>').attr({'name':'card_nonce','value':nonce,'type':'text'});
var $billingPostalCode = $('<input/>').attr({'name':'card_zip','value':cardData.billing_postal_code,'type':'text'});
$('#square-form-container').append($nonceInput);
$('#square-form-container').append($billingPostalCode);
/* submit form */
$('#square-form-container').closest('form')[0].submit();
/*nonce */
},
unsupportedBrowserDetected: function() {
/* Alert the buyer that their browser is not supported*/
alert("browser does not support ");
}
}
});
/* call after Initialization*/
paymentForm.build();
}
(function() {
setTimeout(function() { Initialize(); }, 5000);
})();
`