Card payments with the Payment Request API not working - javascript

I am looking into the Payment Request API as a way to streamline payments on our site checkout and have run into a bit of a brick wall on how to use it with card payments. There are a few demos explaining how to use the payment request API, this one seemed to be the simplest and easiest to follow, but it is also quite out of date (as a lot of PR API demos i've found seem to be). Here is my code than runs when the payment button is clicked:
const paymentMethods = [
{
supportedMethods: ['basic-card', 'visa', 'mastercard', 'amex'],
data: {
supportedNetworks: ['visa', 'mastercard', 'amex']
}
}
];
const details = { total: { label: 'Test payment', amount: { currency: 'GBP', value: '1.00' } } };
// Show a native Payment Request UI and handle the result
const request = new PaymentRequest(paymentMethods, details);
request.show()
.then(response => {
console.log('yep');
console.log(response);
})
.catch(err => {
console.error(err);
});
I get the following error in the console:
Uncaught RangeError: Failed to construct 'PaymentRequest': Invalid payment method identifier format
I did some digging and found that the 'basic-card' supportedMethod is deprecated, and simple references to credit card providers don't seem to be supported anymore. The MDN docs for supportedMethods actually state
Starting with more recent browsers, this parameter is more generic than credit cards, it is a single string, and the meaning of the data parameter changes with the supportedMethods. For example, the Example Pay payment method is selected by specifying the string https://example.com/pay here.
Which is all well and good, but if i want to support Visa or Mastercard credit and debit card payments what URL do i use for them under supported methods? The payment processor for our website is Worldpay, so is this something i'd ask them for? Or do i need to find individual urls for Visa and Mastercard? I have done some googling and can't find anything relevant for either of them. Maybe i'm just bad at googling, but i don't really know how to proceed with this and wondered if anyone else had experience in setting up the payment request API to use credit and debit cards.
Oh, and i'm testing this in Chrome 103 btw.
Thanks

Related

Error with AWS SDK-JS API when Retrieving Seller Partner Product Catalog Inventory

I need to retrieve the product catalog of my seller partner on Amazon. Although the API refers to this as "Inventory," I couldn't find this term in the SDK documentation. I assume that the "Catalog" namespace is the equivalent.
Update:
My custom application requires a list of the following product values:
ASINs
UPCs
SKUs
FNSKUs
I have read the documentation and found an API that returns what I need, which can be found here:
https://developer-docs.amazon.com/sp-api/docs/fba-inventory-api-v1-use-case-guide
According to the documentation, I need to create a signature in order to use the API. However, it is noted that if I use the AWS SDK, I do not need to calculate the signature myself. Therefore, I understand that the best practice is to use the AWS SDK.
I have the necessary IAM role permissions and the SP-API app has been published. I am currently attempting to use the AWS SDK.
I have made some changes based on recommendations, but I am not completely sure what else I need to do. Here is my current code:
```
export const /*bundle */ start = async () => {
const client = new MarketplaceCatalogClient({
region: REGION,
credentials: {
accessKeyId: ACCESS_KEY_ID,
secretAccessKey: ACCESS_SECRET_KEY,
},
});
const params = {
/** input parameters */
};
const answer = await client.send(
new ListEntitiesCommand({ Catalog: "AWSMarketplace", EntityType: "ContainerProduct" })
);
console.log(100, answer);
return answer;
};
```
I got the next answer with "AmiProduct" or "ContainerProduct":
{
'$metadata': {
httpStatusCode: 200,
requestId: '91fc5fed-6cdc-42d6-97ec-1ed3cc9d5796',
extendedRequestId: undefined,
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
},
EntitySummaryList: []
}
I'm having difficulty understanding how to correctly implement this. Any guidance would be greatly appreciated.
The docs should be better. I spent a good 15 mins on the docs at https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/welcome.html and failed to find a full list of valid EntityType values.
Some EntityType values are documented here: https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/seller-products.html
AmiProduct
ContainerProduct
It looks like these types correspond to the product types in the index of the seller guide here -> https://docs.aws.amazon.com/marketplace/latest/userguide/machine-learning-products.html. It's not clear what the other valid values are.
Some other EntityType values are documented here: https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/private-marketplace.html
Experience
Procurement Policy
It looks the way to go for now is to scrounge these valid values from examples in the docs https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/welcome.html. Not the best developer experience :grimace:
Assuming you are a seller, that you have registered successfully with your AWS account. You can then use Marketplace APIs.
To use them, you have to create an IAM role or a user with policies to grant access to invoke the selected APIs like listEntities, describeEntity, etc.
Here I again assume you have the Cognito authorized credentials if using AWS SDK.
Now to view the list of products successfully published, you use listEntites command.
You can only view AMI or Containter product types. Read here.
It uses minimum two required parameters Catalog and EntityType. The former has a fixed value AWSMarketplace, and latter can have a value either AmiProduct or ContainerProduct.
To get a detailed information about a specific product, you use describeEntity command. It takes minimum 2 required parameters Catalog and EntityID.
The former again has a fixed value AWSMarketplace. For latter, you'll obtain it from the listEntites response.

Unsupported Apple Pay validation domain

Hi we are trying to integrate Apple Pay on a website using the payment provider Pay360. 
Pay360 have provided us with the domain-verification file and we have uploaded it to the merchant domain -
https://example.com/.well-known/apple-developer-merchantid-domain-association
When we try to checkout we get this message in the dev console -
"Unsupported Apple Pay validation domain"
This is the Pay360 integration docs:
https://docs.pay360.com/alternative-payments/getting-started-with-apple-pay/
I've included the code used at the checkout that creates the Apple Pay session but it's not triggering the 'session.onvalidatemerchant' function because of that I can't get 'validationURL' from that event.
Here's the code -
jQuery(document).on('click','#applePay',function() {
var paymentRequest = {
countryCode: 'GB',
currencyCode: 'GBP',
supportedNetworks: ['visa', 'masterCard', 'amex', 'discover'],
merchantCapabilities: [ 'supports3DS' ],
total: { label: 'Online Store', amount: '0.05' },
};
var session = new ApplePaySession(3, paymentRequest);
session.onvalidatemerchant = function (event) {
console.log(event);
var url = event.validationURL;
alert(url);
}
session.onpaymentauthorized = function (event) {
console.log(event);
}
session.oncancel = function(event) {
console.log(event);
}
session.begin();
});
We asked Pay360 Support for help but they asked us to contact Apple for help. Here is what Pay360 said -
Unfortunately at this point Pay360 cannot support you anymore as it is not a problem at our end.
The issue is between the yourself and ApplePay especially as you are going down the API path. Therefore, if you are still encountering further issues after the previous advice has been taken, you should in the first instance review ApplePay's integration documentation or contact ApplePay.
Previous advice -
From the code snippet given, the merchant is calling begin() before they've finished initialising the ApplePaySession object - it makes sense that it wouldn't trigger the onvalidatemerchant event if there wasn't one set at that point.
The merchant should bind onvalidatemerchant and onpaymentauthorized (and anything else they want to bind on the session) before calling the begin() function.
This should enable the merchant to continue debugging the problem.
Please can someone advise how to fix?

StripeInvalidRequestError: You cannot accept payments using this API as it is no longer supported in India

I have been building an ecommerce web application and wanted to Integrate my Checkout with the Stripe API , but when i run the application and make a transaction. I get the following message error..
I came to find that Payment Intent API are to be used as per new RBI regulations, I cannot get how to change my code so that it again accepts my transaction with a 201 response.
Here is my code snippet.
import StripeCheckout from "react-stripe-checkout";
const STRIPE_PUBLISHABLE =
"my_api_key";
const onToken = (user, checkout) => (token) => checkout(user, token.id);
const Checkout = ({ amount, user, checkout }) => (
<StripeCheckout
amount={amount * 100}
token={onToken(user, checkout)}
currency="INR"
stripeKey={STRIPE_PUBLISHABLE}
/>
);
export default Checkout;
Your code is using Stripe's Legacy Checkout product which was deprecated back in 2019 already. You can't really "modify" that code since it's not supported in India due to the new RBI regulations. You have to rewrite your integration instead to use a different product.
The easiest option is to use Stripe's "newer" product called Payment Links. This allows you to configure a payment flow with a URL for a certain product: https://stripe.com/docs/payments/payment-links
Alternatively, you can use the newer version of Checkout which is hosted by Stripe and handles all the payment collection for you: https://stripe.com/docs/payments/checkout
Finally, if those solutions don't work for you, you will have to use the Payment Intents API to accept a payment and the Payment Element to collect card details: https://stripe.com/docs/payments/accept-a-payment

Gatsby/React - Get Referring Url

Building a jobs board. Need to know if the user clicked on our link from monster.com, jobs.com, foobar.com, etc. This needs to happen in the code, as I need to send it to an API.
What is the best way to accomplish this?
I tried searching around, but can only find articles on internal routing, e.g.:
How to get previous url in react gatsby
If I need to do this in plain Javascript (not available "out-of-the-box"), please point me in the right direction there too. Not even sure what to google for this other than "UTM parameters". We are using Google Analytics and the marketing team is including utm params in the links, if that helps.
In gatsby each page component has a location prop with some useful info. So you could do something like:
import React from "react"
const IndexPage = ({ location }) => {
console.log(location.search.split("?")[1].split("&"))
return (
<div>
My homepage
</div>
)
}
export default IndexPage
So visiting https://myapp.com/?campaign=foo&id=bar would log ["campaign=foo", "id=bar"]. With that info, you could decide how and when to communicate with your APIs to log the relevant info.
This question was very vague, because I did not understand what I was asking when I posted it. There is two scenarios here that should help you get started. If you have specific questions, follow up - I will try to help.
Scenario 1 (will most likely NOT work, but here for completeness): You are getting referrals from websites you are not at all associated with. For example, you run mycoolsite.com and someone at someforum.com linked to you. The ONLY way you are going to be able to know this without anything additional is if someforum.com sends something called a Referer Request Header. Many popular sites do not.
Scenario 2: Your marketing team pays someone to link to you for a specific promotion. E.g., your marketing team tells someforum.com to link mycoolsite.com for money or as a favor. In this case, they can request that scenario 1 be followed OR, more likely, they can include something called utm params, e.g. when they send the link it's not mycoolsite.com?utm_campaign=monster&utm_source=monsterjobs
When the request comes in to your site, you can then pull these utm params out, to identify which campaign is working.
The code for that looks something like this:
function buildUtmInfoString(currentUrlString) {
const url = new URL(currentUrlString);
let referrerString = '';
utmParamNames.forEach(paramName => {
const paramValue = url.searchParams.get(paramName.standard);
if(!paramValue) {
return;
}
const paramString = `${paramName.colloquial}: ${paramValue}, `;
referrerString += paramString;
});
referrerString = referrerString.substring(0, referrerString.length-2);
return referrerString;
}
Note that you might need to look up utm param standard names, they are supported by Google Analytics out of the box, if your company uses that, but you can use them without GA.
const standardUtmParamNames = {
SOURCE: 'utm_source',
MEDIUM: 'utm_medium',
CAMPAIGN: 'utm_campaign',
TERM: 'utm_term',
CONTENT: 'utm_content'
};
const utmParamNames = [
{
standard: standardUtmParamNames.SOURCE,
colloquial: 'Source'
},
{
standard: standardUtmParamNames.MEDIUM,
colloquial: 'Medium'
},
{
standard: standardUtmParamNames.CAMPAIGN,
colloquial: 'Campaign'
},
{
standard: standardUtmParamNames.TERM,
colloquial: 'Term'
},
{
standard: standardUtmParamNames.CONTENT,
colloquial: 'Content'
}
];
export default utmParamNames;
Note that there are also hacks to accomplish this, but they are not reliable and can be seen as abuse of your user's privacy, so they aren't viable business solutions and I don't recommend wasting time on them.

Using Negative Testing via Paypal Express Checkout client-side JS button implementation

I'm currently working on a PayPal Express checkout integration using the Client-side JS approach for taking payments. I'm looking to utilise their "Negative Testing" feature to try to simulate potential errors and provide appropriate responses to the customer.
Just a reference to the relevant doc page here for reference
It seems to enable negative testing you need to pass an extra header along with the the payment request specifying the particular error you would like to trigger for that payment.
This is my current JS for setting up the transaction:
<script>
//We need to convert our generated json string into a bonified javascript object
var paypal_transaction = JSON.parse(JSON.stringify(<?php echo $paypal_json; ?>));
paypal.Button.render({
env: 'sandbox', // 'production'/'sandbox',
commit: true, // Show a 'Pay Now' button - Allows us to capture the payment right away
client: {
sandbox: 'Ab_hPp7h70DoFKChLMSynNxacQQbGcb_tP1cDbzW9jC6a0rYIZH0CkEYYfkw6csvmlyTmfLnagelqB85',
production:''
},
//How we want the button to look
style: {
size: 'responsive',
color: 'gold',
shape: 'rect',
label: 'pay'
},
headers: {
'{"mock_application_codes":"INSTRUMENT_DECLINED"}'
}
payment: function(data,actions) {
return actions.payment.create({
//Pass our created transaction to paypal.
payment:paypal_transaction,
/**
* We have to set the following fields to prevent the client from
* changing their delivery address when they're at PayPal
*/
experience: {
input_fields: {
no_shipping: 0,
address_override:1
},
}
});
},
onAuthorize: function(data, actions) {
/**
* [description]
* #param payment - The authorised transaction returned from paypal
* #return redirect - We redirect the cutomer to our confirmation page as soon as we return from PayPal as we're confident we have the correct
*/
return actions.payment.execute().then(function(payment) {
actions.redirect();
});
},
onError: function(err) {
console.log(err);
// Show an error page here, when an error occurs
},
onCancel: function(data, actions) {
return actions.redirect();
// Show a cancel page or return to cart
}
}, '#paypal-button');
Essentially my question is where do I specify the mock application codes like this in the above implementation.
In the docs they give an example cURL request with the below as the extra header that needs to be passed:
"PayPal-Mock-Response:{\"mock_application_codes\":\"INSTRUMENT_DECLINED\"}"
I just don't know how to do this via the JS approach. Can negative testing only be used with a server side implementation?
Hope that's all clear enough!
Had similar issue myself, and the official answer I got was that it is not available:
"I understand this is a frustrating situation. Unfortunately we do not
have any way to offer negative testing for client side integrations.
It may possible for you to do so using Postman, however, we do not
have documentation to offer."
This is really sad though, other payment providers have fixed card numbers for certain error scenarios for example, or have special payment value based codes. PayPal only has that for the Payflow integration, and the request header based mocking stuff is also only possible if you are directly calling their REST APIs.
PayPal is really lame in these aspects, as even if you are mocking behavior with server integration (not that hard, for this at least they have proper code examples), this mocking is explicit and you control the error. If it would be implicit, and originate from an actually validated but invalid card for example, it would be more realistic.

Categories