Create Payment Request API - google-api-nodejs-client

I am trying to integrate the Payment Request API for the Google Pay for Payments using javascript but my code returns a PaymentRequest is not defined error.
Here is my code.
CODE:
const supportedInstruments = [
{
supportedMethods: ['https://tez.google.com/pay'],
data: {
pa: 'abc#gmail.com',
pn: 'abc',
tr: '1234ABCD', // your custom transaction reference ID
url: 'http://url/of/the/order/in/your/website',
mc: '1234', // your merchant category code
tn: 'Purchase in Merchant',
},
}
];
const details = {
total: {
label: 'Total',
amount: {
currency: 'INR',
value: '10.01', // sample amount
},
},
displayItems: [{
label: 'Original Amount',
amount: {
currency: 'INR',
value: '10.01',
},
}],
};
let request = null;
try {
request = new PaymentRequest(supportedInstruments, details);
}
catch (e) {
console.log('Payment Request Error: ' + e.message);
return;
}
if (!request) {
console.log('Web payments are not supported in this browser.');
return;
}
Error Message:
Payment Request Error: PaymentRequest is not defined

Sounds to me like you are testing it in an older browser that simply doesn't support it. Browser support is pretty good these days, but not universal. You just need to do a simple bit of feature detection and wrap your code in an if statement to check the browser supports it:
if (window.PaymentRequest) {
// your payment request code here
}

Related

Invalid parameters error on createConversation in #google-cloud/contact-center-insights SDK

I'm trying to call createConversation function of CCAI insights SDK #google-cloud/contact-center-insights but getting below error
ERROR ==> Error: 3 INVALID_ARGUMENT: Request contains an invalid argument.
What would be the correct request payload? I'm not able to find sample request payload for this function.
I'm using below code:
const [conversation] = await client.createConversation({
parent: client.locationPath(projectId, 'us-central1'),
conversation: {
medium: 'CHAT',
name: 'TestModel',
transcript: {
transcriptSegments: [{
segmentParticipant: {
role: 'HUMAN_AGENT',
userId: '1234'
},
text: 'Thank you for calling IBC, how can I help you today?',
confidence: 0.90,
sentiment: {
magnitude: 0.2,
score: 0.9
},
}]
}
}
});
console.info(`Created `, conversation.name);
Note: It's working for below github code but I need to send the payload in transcript format.
ccai-insight-github code
And even if we store the conversation in Storage bucket, what would be the format?
Thanks

braintree.paypalCheckout.create add dynamical amount to the paypal button

I use HostedFields for credit card and paypal web for paypal.
So inside of braintree.client.create i have braintree.hostedFields.create and braintree.paypalCheckout.create.
Code example of paypal:
braintree.paypalCheckout.create({
client: clientInstance
}, function (paypalCheckoutErr, paypalCheckoutInstance) {
if (paypalCheckoutErr) {
console.error('Error creating PayPal Checkout:', paypalCheckoutErr);
return;
}
paypal.Button.render({
env: 'sandbox',
commit: true,
buttonStyle: {
color: 'blue',
shape: 'rect',
size: 'medium'
},
payment: function () {
return paypalCheckoutInstance.createPayment({
flow: 'checkout',
locale: ''+langanalytics+'',
amount: '10.00',
currency: 'EUR'
});
},
onAuthorize: function (data, actions) {
return paypalCheckoutInstance.tokenizePayment(data, function (err, payload) {
document.getElementById("paynonce").value = payload.nonce;
document.getElementById("paymentform").submit();
});
},
onCancel: function (data) {
console.log('checkout.js payment cancelled', JSON.stringify(data, 0, 2));
},
onError: function (err) {
console.error('checkout.js error', err);
}
}, '#paypal-button').then(function () {
});
});
The problem is according to my client he want a single page checkout, where the amount get generated dynamically.
For example if someone change the country or payment method the price can change for some €. A click EventListener start the calculation and changes the total sum in real time.
My Problem:
I cant change the amount of my paypal intialization of this part:
return paypalCheckoutInstance.createPayment({
flow: 'checkout',
locale: ''+langanalytics+'',
amount: '10.00',
currency: 'EUR'
});
Is there any way to update the amount outsite of the function as soon as total sum changes (i have full control of this).
I already tried to intialize the whole braintree.client.create new on total sum change but i get errors from hosted fields a instance is already created and for paypal i recieve multiple buttons.

Getting an ' instance.requestPaymentMethod is not a function' in Braintree's sample

I'm getting an instance.requestpaymentmethod is not a function when I was just following along the tutorial for custom-field integration found here:
https://developers.braintreepayments.com/start/tutorial-hosted-fields-node
The error happens when I click on the "Pay" button.
Did anyone solve this problem? My assumption is that the code isn't updated or the script sources changed somewhat. If anyone from Braintree can actually help, that'll be great.
Thanks!
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
I took a look at the example code snippet in the guide you shared and I was able to find the culprit. First off, the error you're getting is expected as the requestPaymentMethod method actually belongs to our Drop-In UI solution and the Hosted Fields JS library doesn't have such module. I informed our Documentation team to get that code example updated.
That being said, you can find a working example in our Hosted Fields guide. If you check the function (hostedFieldsErr, hostedFieldsInstance) callback function, you'll see that the payment nonce is created by the tokenize function of the hostedFieldsInstance.
I also ran into this issue today. Use the following code in <script> tag. It will work for you.
var form = document.querySelector('#hosted-fields-form');
var submit = document.querySelector('input[type="submit"]');
braintree.client.create({
authorization: '<YOUR_TOKENIZATION_KEY>'
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10/2019'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) {
console.error(hostedFieldsErr);
return;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
console.error(tokenizeErr);
return;
}
console.log('Got a nonce: ' + payload.nonce);
$.ajax({
type: 'POST',
url: '<YOUR_API_URL>',
data: { 'paymentMethodNonce': payload.nonce }
}).done(function (result) {
hostedFieldsInstance.teardown(function (teardownErr) {
if (teardownErr) {
console.error('Could not tear down Drop-in UI!');
} else {
console.info('Drop-in UI has been torn down!');
$('#submit-button').remove();
}
});
if (result.success) {
$('#checkout-message').html('<h1>Success</h1><p>Your Drop-in UI is working! Check your sandbox Control Panel for your test transactions.</p><p>Refresh to try another transaction.</p>');
} else {
console.log(result);
$('#checkout-message').html('<h1>Error</h1><p>Check your console.</p>');
}
});
});
}, false);
});
});

Paypal webhooks events are not triggered in sandbox

Hello I am using the following setup
Created paypal merchant and customer sandbox accounts
Configured paypal REST API app
Added a webhook url to my server and have validated that it works using the webhook simulator
Used the Express Checkout javascript implementation found here
I am able to make successful payments when viewing the notifications in sandbox but no webhook is ever triggered???
Below is a sample of my javascript implementation that I have used, please not that it's embedded in a coldfusion script file hence the use hashtags.
`
var items = #paypalItems#;
// Render the PayPal button
paypal.Button.render({
env: '#application.config.paypal.bSandbox ? "sandbox" : "production"#', // sandbox | production
commit: true,
//style the button
style: {
label: 'pay'
},
// PayPal Client IDs - replace with your own
client: {
sandbox: '#application.config.paypal.sandbox_key#',
production: '#application.config.paypal.live_key#'
},
// Wait for the PayPal button to be clicked
payment: function(data, actions) {
// Make a client-side call to the REST api to create the payment
return actions.payment.create({
payment: {
transactions: [{
amount: {
total: #trim(numberFormat( application.oCart.getTotal(bDiscount=1,bShipping=1) , "99999999.99" ))#,
currency: "AUD",
details: {
subtotal: #trim(numberFormat( application.oCart.getTotal() - application.oCart.getAmountGST( amount=application.oCart.getTotal(bDiscount=1), addGST=false ), "99999999.99" ))#,
tax: #trim(numberFormat(application.oCart.getAmountGST( amount=application.oCart.getTotal(bDiscount=1), addGST=false ), "99999999.99" ))#,
shipping: #trim(numberFormat( application.oCart.oShipping.getCartShippingAmount(country=session.fcbshoppingCart.order.shippingCountry), "99999999.99" ))#
}
},
invoice_number: "#orderNumber#",
item_list: {
items: items,
shipping_address: {
recipient_name: "#session.fcbshoppingCart.customer.firstName# #session.fcbshoppingCart.customer.lastName#",
line1: "#session.fcbshoppingCart.order.shippingAddress1#",
line2: "#session.fcbshoppingCart.order.shippingAddress2#",
city: "#session.fcbshoppingCart.order.shippingSuburb#",
country_code: "#paypalCountryCode#",
postal_code: "#session.fcbshoppingCart.order.shippingPostCode#",
state: "#session.fcbshoppingCart.order.shippingState#"
}
}
}]
}
});
},
// Wait for the payment to be authorized by the customer
onAuthorize: function(data, actions) {
console.log( "Paypal Authorize:", data );
// Execute the payment
return actions.payment.execute().then(function(payment) {
console.log( "Paypal Response:", payment );
//payment has been accepted so we can now generate an order
$.ajax({
type: "get",
url: "/apps/paypal/createOrder.cfm",
data: {
transactionNumber: "#orderNumber#",
payPalPaymentId: data.paymentID
},
dataType: "json",
success: function( res ) {
console.log('edharry create order data', res);
if( res.BPAYMENTPROCEED ) {
$('##paypal-message').addClass("show success").text('Payment Successfully Complete!');
//lets redirect to the checkout success page.
window.location.href = window.location.origin + '/shop/checkout/confirmation?productOrder=' + res.PRODUCTORDER.OBJECTID;
} else {
//need to handle a failed transaction
$('##paypal-message').addClass("show failure").text('Payment did not complete on server!');
}
},
error: function() {
//lets show an error
$('##paypal-message').addClass("show failure").text('Payment did not complete on server!');
}
})
$('##paypal-message').addClass("show success").text('Payment Successfully Complete!');
});
},
onCancel: function(data) {
console.log('The payment was cancelled!');
}
}, '##paypal-button-container');`
This is an ongoing issue with Paypal. They are aware of this issue and are currently working to resolve this.

Error trying to access Paypal API from Parse.com Cloud Code

I'm trying to call Paypay from Parse.com Cloud Code.
I'm getting the following error on Firebug:
{"code":141,"error":"Uncaught Error: Can't form encode an Object"}
I'm using the example straight out of the Paypal example code. My cURL snippet works fine. When I try it with Parse Cloud Code, I get the above error. Here's my Parse Cloud Code:
Parse.Cloud.httpRequest({
url: 'https://svcs.sandbox.paypal.com/AdaptiveAccounts/CreateAccount',
method: 'POST',
headers: { "X-PAYPAL-SECURITY-USERID": "XXXXXXXXX",
"X-PAYPAL-SECURITY-PASSWORD": "XXXXXXXX",
"X-PAYPAL-SECURITY-SIGNATURE": "XXXXXXXXXXXXX",
"X-PAYPAL-REQUEST-DATA-FORMAT": "JSON",
"X-PAYPAL-RESPONSE-DATA-FORMAT": "JSON",
"X-PAYPAL-APPLICATION-ID": "APP-NNNNNNNNNNN",
"X-PAYPAL-DEVICE-IPADDRESS": "<my_actual_IP_address>",
"X-PAYPAL-SANDBOX-EMAIL-ADDRESS": "XXXXXXXXXXXXXX"
},
body: { "sandboxEmailAddress":"xyz#me.com",
"accountType":"PERSONAL",
"name": {"firstName":"Lenny","lastName":"Riceman"},
"address":{"line1":"123 Main St", "city":"Austin", "state":"TX", "postalCode":"78759", "countryCode":"US"},
"citizenshipCountryCode":"US",
"contactPhoneNumber":"512-555-5555",
"dateOfBirth":"1968-01-01Z",
"createAccountWebOptions": {"returnUrl":"http://www.example.com/success.html"},
"currencyCode":"USD",
"emailAddress":"lr12345#example.com",
"preferredLanguageCode":"en_US",
"registrationType":"Web",
"requestEnvelope": {"errorLanguage":"en_US"}
},
success: function() {
response.success("Paypal made!");
},
error: function(err) {
response.error(err);
console.error('Request failed with response code ' );
}
Update: May 9, 2014
OK. I don't know if this will help, but here is the exact code that is working for me.
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://api-3t.paypal.com/nvp -d',
body: {
USER: 'sr1.me.com',
PWD: 'LEgfdgfsdg8',
SIGNATURE: 'gfdgh',
METHOD: 'MassPay',
VERSION: '93',
RECEIVERTYPE: 'EmailAddress',
CURRENCYCODE: 'USD',
EMAILSUBJECT: 'You have a new payment from ',
L_EMAIL0: sellerEmail,
L_AMT0: paypalPmt,
L_NOTE0: paypalNote,
L_UNIQUEID0: bumpSoldTrans
}
Parse.Cloud.define("getUserPayPalToken", function(request, response){
//Setup private varaibles for paypal request to user
var receivers = new Array();
//Setup Receivers for Paypal when payment begins
//Primary Receiver --- Created first array for primary receiver
receivers[0] = new Array();
receivers[0][0] = {'amount':'1.00', 'email':'email-test-1#gmail.com'};
//receivers[0][0] = {'email':request.params.email};
//Secondary Receiver --- Created second array for secondary receiver
receivers[1] = new Array();
receivers[1][0] = {'amount':'2.00', 'email':'test-email#gmail.com'};
var receiverListParams = [{'receiver': receiverParams}];
var receiverParams = JSON.stringify(receiverListParams);
//Set Parse to call PayPal Adaptive Payments
Parse.Cloud.httpRequest({
method:'POST',
url: 'https://svcs.sandbox.paypal.com/AdaptivePayments/Pay',
headers: {
//Setting PayPal request headers
'X-PAYPAL-SECURITY-USERID' : 'xxxxx',
'X-PAYPAL-SECURITY-PASSWORD' : 'xxxxx',
'X-PAYPAL-SECURITY-SIGNATURE' : 'xxxxx',
// Global Sandbox Application ID
'X-PAYPAL-APPLICATION-ID ' : 'APP-80W284485P519543T',
// Input and output formats
'X-PAYPAL-REQUEST-DATA-FORMAT' : 'JSON',
'X-PAYPAL-RESPONSE-DATA-FORMAT' : 'JSON'
},
body:{
'actionType' : 'PAY',
'cancelUrl' : 'http://www.cancel.com',
'currencyCode' : 'USD',
'returnUrl' : 'http://www.return.com',
'requestEnvelope' : {"errorLanguage":"en_US"},
'receiverList' : receiverParams
},
success: function(httpResponse) {
console.log(httpResponse.text);
response.success(httpResponse.text);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error(httpResponse.text);
}
});
});