setPayment(payment: BasketPayment): Promise<void>¶
The setPayment
method assigns a selected payment option to the basket's shipping configuration. This updates the basket's state with the chosen payment method.
Input parameters¶
payment¶
payment
is a mandatory parameter which represents the BasketPayment model specifying the payment method to be set for the basket.
Returned value¶
A returned value has a type of Promise<void>
, indicating that the method completes without returning any data upon successful execution.
Event Bus events¶
This API method dispatches the following events with the Event Bus:
- basket.setPayment - after a successful method execution
- basket.basketUpdated - after the payment has been successfully changed
- FlashMessengerApi.addFlashMessages - when an error occurs while setting a payment
- basket.unexpectedError - when an error occurs while setting a payment
Example¶
In this example, we use the basketPaymentsApi
to set a selected payment option for the basket shipping.
For this example let's assume we have a list of shippings with elements that have an id
attribute representing the id
of a specific payment option. To achieve that you can use the getAvailable method and render elements based on the data it returns.
Let's assume such HTML structure:
<div class="shipping-details">
<div data-shipping-option id="1">
Shipping details 1
</div>
<div data-shipping-option id="2">
Shipping details 2
</div>
<div data-shipping-option id="3">
Shipping details 3
</div>
</div>
We can select elements using the querySelectorAll method and attach an event listener to each of them which sets a new payment option like this:
useStorefront(async (storefront) => {
let basketPaymentsApi = storefront.getApiSync('basketPaymentsApi');
if (!basketPaymentsApi) {
const featureSystemApi = this.getApiSync('FeatureSystemApi');
await featureSystemApi.registerDynamic('basket');
basketPaymentsApi = storefront.getApiSync('basketPaymentsApi');
}
const $shippingOptionsArray = [...document.querySelectorAll('div[data-shipping-option]')];
$shippingOptionsArray.forEach(($shippingOption) => {
$shippingOption.addEventListener('click', async function(ev) {
const $target = ev.target;
const availablePaymentOptions = basketPaymentsApi.getAvailable();
const selectedPaymentOption = availablePaymentOptions.find(({ id }) => id === $target.id);
try {
await basketPaymentsApi.setPayment(selectedPaymentOption);
console.log('Payment option set successfully.');
} catch (error) {
console.error('Error setting payment option:', error);
}
});
});
});
Basket Payments API methods reference¶
- get
- select$
- getAvailable
- selectAvailable$
- setPaymentData
- getSelectedPayment
- selectSelectedPayment$
- getActivePaymentCost
- selectActivePaymentCost$
- getPaymentChannelStrategy
- addPaymentChannelStrategy
- addPaymentInfo
- getPaymentInfo
- getSectionValidation
- selectSectionValidation$