Recreating payment session and Yandex Pay buttons
Sometimes, you might need to recreate a payment session and payment buttons. For example, the button might be shown in a dynamic block, and the session might need to be recreated when accessing a dynamic catalog.
In the process of recreation, active sessions and buttons are deleted before new ones are created.
Deleting a payment session
When you delete a session, all the payment buttons related to this session are also deleted.
Deleting a payment session and buttons
paymentSession.destroy();
Deleting a payment button
// Deleting a payment button on a specific DOM node
paymentSession.unmountButton(
document.querySelector('<selector>')
);
Example
function onYaPayLoad() {
const YaPay = window.YaPay;
// Payment details
const paymentData = {
// For debugging, you need to explicitly specify the `SANDBOX` environment.
// For the production environment, you can omit this parameter or specify `PRODUCTION`.
env: YaPay.PaymentEnv.Sandbox,
// Version 2 points at paying via Yandex Pay
// The user pays in the Yandex Pay form,
// and only the result of the payment transfer is returned to the merchant
version: 3,
// Code of the currency in which you are going to accept payments
currencyCode: YaPay.CurrencyCode.Rub,
// Merchant ID received on registration in Yandex Pay
merchantId: '<YOUR_MERCHANT_ID>',
// IMPORTANT!
// Paid order ID
// If it's available, the payment form is shown
// rather than the checkout form
orderId: 'order-id',
// Details of the customer's cart (optional)
cart: {
// Items in the cart
items: [
{
productId: '1',
total: '26990.00',
},
{
productId: '3',
// If needed, specify the number of items
quantity: { count: 2 },
// Total for two items is (7990 * 2)
total: '15980.00',
},
],
},
// Arbitrary additional data for the cart (optional)
// After applying encodeURIComponent, the data couldn't be longer than 128 characters
metadata: 'order-metadata',
};
// Payment success handler
function onPaymentSuccess(event) {
// Order placed successfully
// show the order success screen to the user
console.log(`OrderId — ${event.orderId}\nMetadata — ${event.metadata}`);
}
// Payment error handler
function onPaymentError(event) {
// Show a message that the payment method is unavailable at the moment
// and suggest the user to try another method.
console.log(`Payment error — ${event.reason}`);
}
// Payment cancellation handler
function onPaymentAbort(event) {
// The user closed the Yandex Pay form.
// Suggest the user to try another payment method.
}
// Create a payment session
YaPay.createSession(paymentData, {
onSuccess: onPaymentSuccess,
onAbort: onPaymentAbort,
onError: onPaymentError,
})
.then(function (paymentSession) {
// Show the Yandex Pay button on the page.
paymentSession.mountButton(document.querySelector('#button_container'), {
type: YaPay.ButtonType.Checkout,
theme: YaPay.ButtonTheme.Black,
width: YaPay.ButtonWidth.Auto,
});
})
.catch(function (err) {
// Couldn't create a payment session.
});
}