### Install Hyvä Themes React Checkout via GitHub
Source: https://github.com/friends-of-hyva/magento2-react-checkout/blob/main/README.md
Install the module directly from GitHub using Composer. This method requires configuring the repository first.
```bash
composer config repositories.hyva-themes/magento2-react-checkout git git@github.com:friends-of-hyva/magento2-react-checkout.git
composer require hyva-themes/magento2-react-checkout
```
--------------------------------
### Install Hyvä React Checkout via Composer
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Install the React checkout module using Composer. You can choose between Packagist or GitHub installation.
```bash
# Install via Packagist
composer require hyva-themes/magento2-react-checkout
```
```bash
# Or install via GitHub
composer config repositories.hyva-themes/magento2-react-checkout git git@github.com:friends-of-hyva/magento2-react-checkout.git
composer require hyva-themes/magento2-react-checkout
```
```bash
# Enable the module
bin/magento setup:upgrade
```
--------------------------------
### Install Hyvä Themes React Checkout via Composer
Source: https://github.com/friends-of-hyva/magento2-react-checkout/blob/main/README.md
Use this command to install the module via Packagist. Ensure you have Composer installed and configured.
```bash
composer require hyva-themes/magento2-react-checkout
```
--------------------------------
### Enable Hyvä Themes React Checkout Module
Source: https://github.com/friends-of-hyva/magento2-react-checkout/blob/main/README.md
After installation via Composer, run this command to enable the module in your Magento 2 instance.
```bash
bin/magento setup:upgrade
```
--------------------------------
### Place Order Action
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Initiates the order placement process. This action supports custom payment actions and returns order details upon success.
```javascript
import { placeOrderAction } from './context/Cart/order/actions';
// Place order with support for custom payment actions
async function performPlaceOrder(dispatch, appDispatch, formValues, paymentActions) {
const order = await placeOrderAction(
dispatch,
appDispatch,
formValues,
paymentActions // Custom payment action callbacks by method code
);
if (order?.order_number) {
// Order placed successfully
console.log('Order Number:', order.order_number);
}
return order;
}
```
--------------------------------
### Initialize Checkout Data with useEffect
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Initializes checkout data on component mount by fetching aggregated data and storing it in the application's contexts. Ensures data is fetched only once.
```jsx
import React, { useEffect, useState } from 'react';
import Login from '../login';
import ShippingAddress from '../shippingAddress';
import BillingAddress from '../billingAddress';
import ShippingMethodsForm from '../shippingMethod';
import PaymentMethod from '../paymentMethod';
import CouponCode from '../couponCode';
import CartItemsForm from '../items';
import Totals from '../totals';
import PlaceOrder from '../placeOrder';
import { AddressWrapper } from '../address';
import { aggregatedQueryRequest } from '../../api';
function CheckoutForm() {
const [isRequestSent, setIsRequestSent] = useState(false);
const { appDispatch, setPageLoader, storeAggregatedAppStates } = useCheckoutFormAppContext();
const { isVirtualCart, storeAggregatedCartStates } = useCheckoutFormCartContext();
const { storeAggregatedFormStates } = useCheckoutFormContext();
// Initialize checkout data on mount
useEffect(() => {
if (isRequestSent) return;
(async () => {
setPageLoader(true);
setIsRequestSent(true);
const data = await aggregatedQueryRequest(appDispatch);
storeAggregatedCartStates(data);
storeAggregatedAppStates(data);
storeAggregatedFormStates(data);
setPageLoader(false);
})();
}, [isRequestSent]);
return (
{!isVirtualCart && }
{!isVirtualCart && }
);
}
```
--------------------------------
### Place Order Action
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Action for placing the final order.
```APIDOC
## Place Order Action
### Description
Action for placing the final order.
### Method
`performPlaceOrder(dispatch, appDispatch, formValues, paymentActions)`
### Parameters
- `dispatch`: Dispatch function for cart context.
- `appDispatch`: Dispatch function for app context.
- `formValues`: Object containing form data for the order.
- `paymentActions`: Object containing custom payment action callbacks keyed by method code.
### Request Example
```javascript
const formValues = { /* ... order form data ... */ };
const paymentActions = { /* ... custom payment callbacks ... */ };
performPlaceOrder(dispatch, appDispatch, formValues, paymentActions);
```
### Response
- `order` (object) - Contains order details, including `order_number` on success.
### Response Example (Success)
```json
{
"order_number": "123456789"
}
```
```
--------------------------------
### Fetch Initial Checkout Data with aggregatedQueryRequest
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Initializes the checkout process by fetching all required data in a single GraphQL request. Ensure cartId is set before calling.
```javascript
import { aggregatedQueryRequest } from './api';
import LocalStorage from './utils/localStorage';
// Initialize checkout with aggregated data
async function initializeCheckout(appDispatch) {
try {
// Ensure cartId is set
if (!LocalStorage.getCartId()) {
LocalStorage.saveCartId(config.cartId);
}
// Fetch all checkout data in single request
const data = await aggregatedQueryRequest(appDispatch);
// Response includes:
// - cart: { id, email, is_virtual, items, prices, billing_address, shipping_addresses, available_payment_methods }
// - countries: [{ id, full_name_english, available_regions }]
// - checkoutAgreements: [{ agreement_id, name, content, checkbox_text }]
// - customer (if logged in): { addresses: [...] }
return data;
} catch (error) {
console.error('Failed to initialize checkout:', error);
}
}
```
--------------------------------
### Initialize Local Storage for Checkout Data
Source: https://github.com/friends-of-hyva/magento2-react-checkout/blob/main/src/reactapp/public/index.html
This script checks for existing local storage data for the Magento cache. If not found, it prompts the user to enter a quoteId or a quoteId:Token, then stores this information in local storage for guest or signed-in quotes.
```javascript
var mageCacheStorage = window.localStorage.getItem( 'mage-cache-storage' );
if (!mageCacheStorage) {
const input = prompt( 'No quoteId or Token found. Enter quoteId:Token or only quoteId for guest quote' );
const [cartId, signin_token] = input.split(':');
window.localStorage.setItem( 'mage-cache-storage', JSON.stringify({ cart: { cartId }, customer: { signin_token}}) );
}
```
--------------------------------
### Configure React App Backend URL
Source: https://github.com/friends-of-hyva/magento2-react-checkout/blob/main/src/reactapp/README.md
Specify a different backend URL for the React application by setting the REACT_APP_BASE_URL environment variable in a .env file.
```env
REACT_APP_BASE_URL=http://test.com
```
--------------------------------
### Place Order Request
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Submits the order via GraphQL and returns the order number. Requires all previous checkout steps to be completed. Clears checkout storage and redirects on success.
```javascript
import { placeOrderRequest } from './api';
// Place order via GraphQL
async function submitOrder(appDispatch) {
try {
const orderResult = await placeOrderRequest(appDispatch);
// Response:
// orderResult = { order_number: '000000123' }
if (orderResult.order_number) {
// Clear checkout storage and redirect
LocalStorage.clearCheckoutStorage();
window.location.replace('/checkout/onepage/success');
}
return orderResult;
} catch (error) {
console.error('Order placement failed:', error.message);
}
}
```
--------------------------------
### Payment Method Actions
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Actions for managing payment method state.
```APIDOC
## Payment Method Actions
### Description
Actions for managing payment method state.
### Methods
- `selectPayment(dispatch, appDispatch, methodCode)`: Sets the payment method via GraphQL.
- `selectPaymentREST(dispatch, appDispatch, paymentData, isLoggedIn)`: Sets the payment method via REST API, typically for methods requiring a separate REST call.
### Request Example (selectPayment)
```javascript
selectPayment(dispatch, appDispatch, 'creditcard');
```
### Request Example (selectPaymentREST)
```javascript
const paymentData = {
paymentMethod: {
method: 'braintree',
additional_data: {
payment_method_nonce: 'nonce-from-braintree'
}
}
};
selectPaymentREST(dispatch, appDispatch, paymentData, true);
```
```
--------------------------------
### Access Application State with useAppContext
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Use useAppContext to access global application state like customer login status, loading states, and country lists. It also provides dispatch functions for state management.
```javascript
import useAppContext from './hook/useAppContext';
function MyComponent() {
const {
isLoggedIn,
customer,
pageLoader,
countryList,
checkoutAgreements,
appDispatch,
setPageLoader,
setMessage,
setErrorMessage,
setSuccessMessage,
} = useAppContext();
const handleAction = async () => {
setPageLoader(true);
try {
// ... perform action
setSuccessMessage('Action completed successfully!');
} catch (error) {
setErrorMessage(error.message);
} finally {
setPageLoader(false);
}
};
return (
{isLoggedIn &&
Welcome, {customer.firstname}!
}
);
}
```
--------------------------------
### Access Checkout Form State with useCheckoutFormContext
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Use useCheckoutFormContext for form registration, validation, and managing checkout data. It allows registering form sections, payment actions, and pre-order actions.
```javascript
import useCheckoutFormContext from './hook/useCheckoutFormContext';
function CustomFormSection() {
const {
aggregatedData,
submitHandler,
registerFormSection,
registerPaymentAction,
registerBeforePlaceOrderAction,
executeBeforePlaceOrderActions,
checkoutFormValidationSchema,
} = useCheckoutFormContext();
// Register a custom form section
useEffect(() => {
registerFormSection({
id: 'custom_section',
initialValues: { customField: '' },
validationSchema: {
customField: Yup.string().required('Required')
}
});
}, [registerFormSection]);
// Register a before-place-order action
useEffect(() => {
registerBeforePlaceOrderAction(
'validateCustomField',
async (formikData) => {
const value = formikData.values.custom_section?.customField;
if (!value) throw new Error('Custom field required');
},
50 // Sort order (lower = earlier execution)
);
}, [registerBeforePlaceOrderAction]);
return Custom Section
;
}
```
--------------------------------
### Place Order Mutation
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Execute this mutation to place the order for the given cart ID. This is the final step in the checkout process.
```graphql
mutation placeOrderMutation($cartId: String!) {
placeOrder(input: { cart_id: $cartId }) {
order { order_number }
}
}
```
--------------------------------
### aggregatedQueryRequest - Fetch Initial Checkout Data
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Fetches all required checkout data in a single GraphQL request, including cart information, country list, checkout agreements, and customer addresses.
```APIDOC
## aggregatedQueryRequest - Fetch Initial Checkout Data
### Description
Fetches all required checkout data in a single GraphQL request including cart information, country list, checkout agreements, and customer addresses (if logged in).
### Method
GraphQL
### Endpoint
[store-url]/hyvareactcheckout/reactcheckout
### Parameters
None directly for this function, it's a GraphQL query.
### Request Example
```javascript
import { aggregatedQueryRequest } from './api';
import LocalStorage from './utils/localStorage';
async function initializeCheckout(appDispatch) {
try {
if (!LocalStorage.getCartId()) {
LocalStorage.saveCartId(config.cartId);
}
const data = await aggregatedQueryRequest(appDispatch);
return data;
} catch (error) {
console.error('Failed to initialize checkout:', error);
}
}
```
### Response
#### Success Response (200)
- **cart** (object) - Contains cart details like id, email, items, prices, addresses, and payment methods.
- **countries** (array) - List of countries with their IDs and names.
- **checkoutAgreements** (array) - Details of checkout agreements.
- **customer** (object) - Customer information including addresses, if logged in.
#### Response Example
```json
{
"cart": {
"id": "123",
"email": "customer@example.com",
"is_virtual": false,
"items": [...],
"prices": {...},
"billing_address": null,
"shipping_addresses": [],
"available_payment_methods": [...]
},
"countries": [
{ "id": "US", "full_name_english": "United States", "available_regions": [...] }
],
"checkoutAgreements": [
{ "agreement_id": 1, "name": "Terms and Conditions", "content": "...", "checkbox_text": "I agree to the terms" }
],
"customer": {
"addresses": [...]
}
}
```
```
--------------------------------
### Customer Login Request
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Authenticates a customer via AJAX login and merges guest cart with customer cart. Saves credentials and reloads the page to refresh checkout data.
```javascript
import { ajaxLoginRequest, mergeCartsRequest } from './api';
// Login customer during checkout
async function loginCustomer(appDispatch, email, password) {
const credentials = {
username: email,
password: password
};
const response = await ajaxLoginRequest(appDispatch, credentials);
if (!response.errors) {
const sourceCartId = LocalStorage.getCartId();
const signInToken = response.data?.customer?.signin_token;
const newCartId = response.data?.cart?.cartId || sourceCartId;
// Save credentials
LocalStorage.saveCartId(newCartId);
LocalStorage.saveCustomerToken(signInToken);
// Merge carts if needed
if (newCartId !== sourceCartId) {
await mergeCartsRequest(appDispatch, {
sourceCartId,
destinationCartId: newCartId
});
}
// Reload page to refresh checkout with customer data
window.location.reload();
}
return response;
}
```
--------------------------------
### Enable Hyvä React Checkout in Magento Config
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Enable the React checkout module in the Magento Admin panel. This XML snippet shows the configuration path and default value.
```xml
1
```
--------------------------------
### GraphQL Mutations Reference
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
GraphQL mutations used for checkout operations.
```APIDOC
## GraphQL Mutations Reference
### Cart Address Mutations
#### Set Shipping Address
```graphql
mutation setShippingAddress(
$cartId: String!
$firstname: String!
$lastname: String!
$company: String
$street: [String]!
$city: String!
$region: String
$regionId: Int
$zipcode: String!
$country: String!
$phone: String!
$saveInBook: Boolean
) {
setShippingAddressesOnCart(
input: {
cart_id: $cartId
shipping_addresses: [{
address: {
firstname: $firstname
lastname: $lastname
company: $company
street: $street
city: $city
region: $region
region_id: $regionId
postcode: $zipcode
country_code: $country
telephone: $phone
save_in_address_book: $saveInBook
}
}]
}
) {
cart {
id
email
shipping_addresses {
available_shipping_methods {
carrier_code
method_code
carrier_title
method_title
amount { value currency }
}
}
}
}
}
```
#### Set Billing Address
```graphql
mutation setBillingAddress(
$cartId: String!
$firstname: String!
$lastname: String!
$street: [String]!
$city: String!
$zipcode: String!
$country: String!
$phone: String!
$isSameAsShipping: Boolean
) {
setBillingAddressOnCart(
input: {
cart_id: $cartId
billing_address: {
same_as_shipping: $isSameAsShipping
address: {
firstname: $firstname
lastname: $lastname
street: $street
city: $city
postcode: $zipcode
country_code: $country
telephone: $phone
}
}
}
) {
cart { id billing_address { firstname lastname city } }
}
}
```
### Checkout Flow Mutations
#### Set Shipping Method
```graphql
mutation setShippingMethodMutation(
$cartId: String!
$carrierCode: String!
$methodCode: String!
) {
setShippingMethodsOnCart(
input: {
cart_id: $cartId
shipping_methods: [{ carrier_code: $carrierCode, method_code: $methodCode }]
}
) {
cart {
shipping_addresses {
selected_shipping_method {
carrier_code
method_code
amount { value currency }
}
}
}
}
}
```
```
--------------------------------
### Use Customer Address as Shipping Action
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Utilize an existing customer address as the shipping address for the cart. Requires the address ID and a flag indicating if billing is the same.
```javascript
// Use existing customer address as shipping
async function useCustomerAddress(dispatch, appDispatch, addressId) {
const isBillingSame = true;
const cartInfo = await setCustomerAddrAsShippingAddrAction(
dispatch,
appDispatch,
addressId,
isBillingSame
);
return cartInfo;
}
```
--------------------------------
### Apply Coupon Code to Cart Request
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Applies a coupon/discount code to the cart and returns updated pricing. Handles invalid coupon code errors.
```javascript
import { applyCouponCodeToCartRequest, removeCouponCodeFromCartRequest } from './api';
// Apply coupon code
async function applyCoupon(appDispatch, couponCode) {
try {
const cartInfo = await applyCouponCodeToCartRequest(appDispatch, couponCode);
// Response includes updated pricing:
// cartInfo.applied_coupons = [{ code: 'SAVE20' }]
// cartInfo.prices.discounts = [{ amount: { value: 20.00 }, label: '20% Off' }]
return cartInfo;
} catch (error) {
// Handle invalid coupon code error
console.error('Coupon code error:', error.message);
}
}
// Remove coupon code
async function removeCoupon(appDispatch, couponCode) {
const cartInfo = await removeCouponCodeFromCartRequest(appDispatch, couponCode);
return cartInfo;
}
```
--------------------------------
### Apply Coupon Code Mutation
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Apply a coupon code to the cart using this mutation. It returns the updated cart details including applied coupons and price information.
```graphql
mutation applyCouponToCartMutation($cartId: String!, $couponCode: String!) {
applyCouponToCart(input: { cart_id: $cartId, coupon_code: $couponCode }) {
cart {
applied_coupons { code }
prices {
grand_total { value currency }
discounts { amount { value } label }
}
}
}
}
```
--------------------------------
### Set Payment Method via GraphQL Action
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Sets the payment method for the cart using a GraphQL action. This function requires dispatch functions and the payment method code.
```javascript
import {
setPaymentMethodAction,
setRestPaymentMethodAction
} from './context/Cart/paymentMethod/actions';
// Set payment method via GraphQL
async function selectPayment(dispatch, appDispatch, methodCode) {
await setPaymentMethodAction(dispatch, appDispatch, methodCode);
}
```
--------------------------------
### Set Payment Method Mutation
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Use this mutation to set the selected payment method for the cart. Ensure the cart ID and payment method code are provided.
```graphql
mutation setPaymentMethodMutation($cartId: String!, $code: String!) {
setPaymentMethodOnCart(
input: { cart_id: $cartId, payment_method: { code: $code } }
) {
cart {
selected_payment_method { code title }
available_payment_methods { code title }
}
}
}
```
--------------------------------
### Track Selected Shipping Address Action
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
This action is used to track the selected address ID for UI state management. It takes dispatch functions and the address ID as arguments.
```javascript
// Track selected address ID for UI state
setSelectedShippingAddressAction(dispatch, appDispatch, 'address-123');
```
--------------------------------
### GraphQL Mutation: Set Shipping Method
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
This GraphQL mutation sets the shipping method for the cart. It requires the cart ID, carrier code, and method code.
```graphql
# Set Shipping Method
mutation setShippingMethodMutation(
$cartId: String!
$carrierCode: String!
$methodCode: String!
) {
setShippingMethodsOnCart(
input: {
cart_id: $cartId
shipping_methods: [{ carrier_code: $carrierCode, method_code: $methodCode }]
}
) {
cart {
shipping_addresses {
selected_shipping_method {
carrier_code
method_code
amount { value currency }
}
}
}
}
}
```
--------------------------------
### Shipping Address Actions
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Actions for managing shipping address state within the cart.
```APIDOC
## Shipping Address Actions
### Description
Actions for managing shipping address state.
### Methods
- `saveNewShippingAddress(dispatch, appDispatch)`: Adds a new shipping address to the cart.
- `useCustomerAddress(dispatch, appDispatch, addressId)`: Uses an existing customer address as the shipping address.
- `setSelectedShippingAddressAction(dispatch, appDispatch, addressId)`: Tracks the selected address ID for UI state.
### Request Example (saveNewShippingAddress)
```javascript
const shippingAddress = {
firstname: 'John',
lastname: 'Doe',
street: ['123 Main Street'],
city: 'New York',
region: 'NY',
regionId: 43,
zipcode: '10001',
country: 'US',
phone: '+1 555 123 4567'
};
saveNewShippingAddress(dispatch, appDispatch, shippingAddress);
```
### Request Example (useCustomerAddress)
```javascript
useCustomerAddress(dispatch, appDispatch, 'customer-address-id');
```
### Request Example (setSelectedShippingAddressAction)
```javascript
setSelectedShippingAddressAction(dispatch, appDispatch, 'address-123');
```
```
--------------------------------
### Set Shipping Address with setShippingAddressRequest
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Sets the shipping address on the cart via a GraphQL mutation. The response includes updated cart data with available shipping methods.
```javascript
import { setShippingAddressRequest } from './api';
// Set shipping address
async function saveShippingAddress(appDispatch, addressData) {
const shippingAddress = {
firstname: 'John',
lastname: 'Doe',
company: 'Acme Inc',
street: ['123 Main Street'],
city: 'New York',
region: 'NY',
regionId: 43, // Magento region ID
zipcode: '10001',
country: 'US',
phone: '+1 555 123 4567',
saveInBook: true // Save to customer address book
};
const cartInfo = await setShippingAddressRequest(appDispatch, shippingAddress);
// Response includes updated cart with shipping methods:
// cartInfo.shipping_addresses[0].available_shipping_methods = [
// { carrier_code: 'flatrate', method_code: 'flatrate', carrier_title: 'Flat Rate', method_title: 'Fixed', amount: { value: 5.00 } }
// ]
return cartInfo;
}
```
--------------------------------
### Set Shipping Method Request
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Sets the selected shipping method on the cart using carrier and method codes. The response includes updated cart prices with shipping costs.
```javascript
import { setShippingMethodRequest } from './api';
// Set shipping method
async function selectShippingMethod(appDispatch) {
const shippingMethod = {
carrierCode: 'flatrate',
methodCode: 'flatrate'
};
const cartData = await setShippingMethodRequest(appDispatch, shippingMethod);
// Response includes updated cart prices with shipping costs
// cartData.shipping_addresses[0].selected_shipping_method = {
// carrier_code: 'flatrate',
// method_code: 'flatrate',
// amount: { value: 5.00, currency: 'USD' }
// }
return cartData;
}
```
--------------------------------
### Set Payment Method Request
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Sets the payment method on the cart using the payment method code. The response includes the selected payment method and available payment methods.
```javascript
import { setPaymentMethodRequest } from './api';
// Set payment method
async function selectPaymentMethod(appDispatch, methodCode) {
// methodCode examples: 'checkmo', 'cashondelivery', 'banktransfer'
const cartData = await setPaymentMethodRequest(appDispatch, methodCode);
// Response includes:
// cartData.selected_payment_method = { code: 'checkmo', title: 'Check / Money order' }
// cartData.available_payment_methods = [...]
return cartData;
}
```
--------------------------------
### Manage Checkout Data with LocalStorage API
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Provides utility functions for managing checkout-related data in the browser's localStorage, including cart ID, customer tokens, address IDs, and recent addresses.
```javascript
import LocalStorage from './utils/localStorage';
// Cart ID management
const cartId = LocalStorage.getCartId();
LocalStorage.saveCartId('new-cart-id-123');
// Customer token management (for authenticated requests)
const token = LocalStorage.getCustomerToken();
LocalStorage.saveCustomerToken('customer-auth-token');
// Address selection persistence
LocalStorage.saveCustomerShippingAddressId('address-123');
LocalStorage.saveCustomerBillingAddressId('address-456');
const shippingAddrId = LocalStorage.getCustomerShippingAddressId();
const billingAddrId = LocalStorage.getCustomerBillingAddressId();
// Billing same as shipping preference
LocalStorage.saveBillingSameAsShipping(true);
const isSame = LocalStorage.getBillingSameAsShippingInfo();
// Most recently used addresses (for guest checkout)
LocalStorage.addAddressToMostRecentlyUsedList({
firstname: 'John',
lastname: 'Doe',
street: ['123 Main St'],
city: 'New York',
// ...
});
const recentAddresses = LocalStorage.getMostRecentlyUsedAddressList();
LocalStorage.updateMostRecentlyAddedAddress('new_address_1', updatedAddress);
LocalStorage.removeMostRecentlyUsedAddress('new_address_1');
// Clear all checkout data (after order placement)
LocalStorage.clearCheckoutStorage();
```
--------------------------------
### Access Cart State with useCartContext
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Use useCartContext to access cart data, including items, prices, addresses, and payment methods. It also provides functions to modify cart state and place orders.
```javascript
import useCartContext from './hook/useCartContext';
function CartSummary() {
const {
cart,
cartId,
order,
cartItems,
shippingAddress,
billingAddress,
shippingMethod,
paymentMethod,
appliedCoupon,
setShippingAddress,
setBillingAddress,
setShippingMethod,
setPaymentMethod,
placeOrder,
setOrderInfo,
} = useCartContext();
const grandTotal = cart?.prices?.grand_total?.value || 0;
const currency = cart?.prices?.grand_total?.currency || 'USD';
return (
Order Total: {currency} {grandTotal.toFixed(2)}
{cartItems.map(item => (
-
{item.product.name} x {item.quantity} = ${item.prices.row_total.value}
))}
);
}
```
--------------------------------
### GraphQL Mutation: Set Billing Address
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
This GraphQL mutation sets the billing address on the cart. It can be set independently or as the same as the shipping address.
```graphql
# Set Billing Address
mutation setBillingAddress(
$cartId: String!
$firstname: String!
$lastname: String!
$street: [String]!
$city: String!
$zipcode: String!
$country: String!
$phone: String!
$isSameAsShipping: Boolean
) {
setBillingAddressOnCart(
input: {
cart_id: $cartId
billing_address: {
same_as_shipping: $isSameAsShipping
address: {
firstname: $firstname
lastname: $lastname
street: $street
city: $city
postcode: $zipcode
country_code: $country
telephone: $phone
}
}
}
) {
cart { id billing_address { firstname lastname city } }
}
}
```
--------------------------------
### Register Custom Stripe Payment Method Renderer
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Registers a custom payment method renderer for Stripe, including its payment action logic. This allows for third-party payment integrations within the checkout flow.
```jsx
import React, { useEffect } from 'react';
import RadioInput from '../common/Form/RadioInput';
import useCheckoutFormContext from '../../hook/useCheckoutFormContext';
import usePerformPlaceOrderByREST from '../../hook/usePerformPlaceOrderByREST';
function StripePaymentMethod({ method, selected, actions }) {
const { registerPaymentAction } = useCheckoutFormContext();
const performPlaceOrder = usePerformPlaceOrderByREST('stripe_payments');
// Register custom payment action
useEffect(() => {
registerPaymentAction('stripe_payments', async (values) => {
// Custom Stripe payment processing
const stripeToken = await getStripeToken(); // Your Stripe integration
await performPlaceOrder(values, {
additionalData: {
cc_stripejs_token: stripeToken.id
},
extensionAttributes: {
stripe_metadata: { /* ... */ }
}
});
});
}, [registerPaymentAction, performPlaceOrder]);
return (
{selected?.code === method.code && (
{/* Stripe Card Element */}
)}
);
}
// Register renderer in PaymentMethodList
const methodRenderers = {
stripe_payments: StripePaymentMethod,
};
```
--------------------------------
### setBillingAddressRequest - Set Billing Address on Cart
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Sets the billing address on the cart, supporting a 'same as shipping' option for non-virtual carts.
```APIDOC
## setBillingAddressRequest - Set Billing Address on Cart
### Description
Sets the billing address on the cart. Supports "same as shipping" option for non-virtual carts.
### Method
GraphQL Mutation
### Endpoint
[store-url]/hyvareactcheckout/reactcheckout
### Parameters
#### Request Body
- **billingAddress** (object) - Required - Details of the billing address.
- **firstname** (string) - Required
- **lastname** (string) - Required
- **company** (string) - Optional
- **street** (array of strings) - Required
- **city** (string) - Required
- **region** (string) - Required
- **regionId** (integer) - Required - Magento region ID.
- **zipcode** (string) - Required
- **country** (string) - Required - ISO 3166-1 alpha-2 country code (e.g., 'US').
- **phone** (string) - Optional
- **saveInBook** (boolean) - Optional - Whether to save the address to the customer's address book.
- **isVirtualCart** (boolean) - Required - Indicates if the cart is virtual.
### Request Example
```javascript
import { setBillingAddressRequest } from './api';
async function saveBillingAddress(appDispatch, billingData, isVirtualCart) {
const billingAddress = {
firstname: 'John',
lastname: 'Doe',
company: 'Acme Inc',
street: ['456 Business Ave'],
city: 'Los Angeles',
region: 'CA',
regionId: 12,
zipcode: '90001',
country: 'US',
phone: '+1 555 987 6543',
isSameAsShipping: false,
saveInBook: false
};
const cartInfo = await setBillingAddressRequest(
appDispatch,
billingAddress,
isVirtualCart
);
return cartInfo;
}
```
### Response
#### Success Response (200)
- **cartInfo** (object) - Updated cart information.
#### Response Example
```json
{
"cartInfo": {
// ... updated cart details
}
}
```
```
--------------------------------
### Add New Shipping Address Action
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Use this action to add a new shipping address to the cart. It requires dispatch functions and shipping address details.
```javascript
import {
addCartShippingAddressAction,
setCustomerAddrAsShippingAddrAction,
setSelectedShippingAddressAction
} from './context/Cart/shippingAddress/actions';
// Add new shipping address to cart
async function saveNewShippingAddress(dispatch, appDispatch) {
const shippingAddress = {
firstname: 'John',
lastname: 'Doe',
street: ['123 Main Street'],
city: 'New York',
region: 'NY',
regionId: 43,
zipcode: '10001',
country: 'US',
phone: '+1 555 123 4567'
};
const isBillingSame = true;
const cartInfo = await addCartShippingAddressAction(
dispatch,
appDispatch,
shippingAddress,
isBillingSame
);
return cartInfo;
}
```
--------------------------------
### Set Billing Address with setBillingAddressRequest
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Sets the billing address on the cart. This function supports setting the billing address independently from the shipping address for non-virtual carts.
```javascript
import { setBillingAddressRequest } from './api';
// Set billing address (different from shipping)
async function saveBillingAddress(appDispatch, billingData, isVirtualCart) {
const billingAddress = {
firstname: 'John',
lastname: 'Doe',
company: 'Acme Inc',
street: ['456 Business Ave'],
city: 'Los Angeles',
region: 'CA',
regionId: 12,
zipcode: '90001',
country: 'US',
phone: '+1 555 987 6543',
isSameAsShipping: false, // Set to true if same as shipping
saveInBook: false
};
const cartInfo = await setBillingAddressRequest(
appDispatch,
billingAddress,
isVirtualCart
);
return cartInfo;
}
```
--------------------------------
### Set Payment Method via REST Action
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Sets the payment method for the cart using a REST API action, typically for payment methods that require a separate REST call. It accepts payment data and login status.
```javascript
// Set payment method via REST (for payment methods requiring REST API)
async function selectPaymentREST(dispatch, appDispatch, paymentData, isLoggedIn) {
const paymentMethod = {
paymentMethod: {
method: 'braintree',
additional_data: {
payment_method_nonce: 'nonce-from-braintree'
}
}
};
await setRestPaymentMethodAction(dispatch, appDispatch, paymentMethod, isLoggedIn);
}
```
--------------------------------
### GraphQL Mutation: Set Shipping Address
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
This GraphQL mutation is used to set the shipping address on the cart. It requires various address details and the cart ID.
```graphql
# Set Shipping Address
mutation setShippingAddress(
$cartId: String!
$firstname: String!
$lastname: String!
$company: String
$street: [String]!
$city: String!
$region: String
$regionId: Int
$zipcode: String!
$country: String!
$phone: String!
$saveInBook: Boolean
) {
setShippingAddressesOnCart(
input: {
cart_id: $cartId
shipping_addresses: [{
address: {
firstname: $firstname
lastname: $lastname
company: $company
street: $street
city: $city
region: $region
region_id: $regionId
postcode: $zipcode
country_code: $country
telephone: $phone
save_in_address_book: $saveInBook
}
}]
}
) {
cart {
id
email
shipping_addresses {
available_shipping_methods {
carrier_code
method_code
carrier_title
method_title
amount { value currency }
}
}
}
}
}
```
--------------------------------
### setShippingAddressRequest - Set Shipping Address on Cart
Source: https://context7.com/friends-of-hyva/magento2-react-checkout/llms.txt
Sets the shipping address on the cart using a GraphQL mutation and returns updated cart data, including available shipping methods.
```APIDOC
## setShippingAddressRequest - Set Shipping Address on Cart
### Description
Sets the shipping address on the cart using a GraphQL mutation. Returns updated cart data with available shipping methods.
### Method
GraphQL Mutation
### Endpoint
[store-url]/hyvareactcheckout/reactcheckout
### Parameters
#### Request Body
- **shippingAddress** (object) - Required - Details of the shipping address.
- **firstname** (string) - Required
- **lastname** (string) - Required
- **company** (string) - Optional
- **street** (array of strings) - Required
- **city** (string) - Required
- **region** (string) - Required
- **regionId** (integer) - Required - Magento region ID.
- **zipcode** (string) - Required
- **country** (string) - Required - ISO 3166-1 alpha-2 country code (e.g., 'US').
- **phone** (string) - Optional
- **saveInBook** (boolean) - Optional - Whether to save the address to the customer's address book.
### Request Example
```javascript
import { setShippingAddressRequest } from './api';
async function saveShippingAddress(appDispatch, addressData) {
const shippingAddress = {
firstname: 'John',
lastname: 'Doe',
company: 'Acme Inc',
street: ['123 Main Street'],
city: 'New York',
region: 'NY',
regionId: 43,
zipcode: '10001',
country: 'US',
phone: '+1 555 123 4567',
saveInBook: true
};
const cartInfo = await setShippingAddressRequest(appDispatch, shippingAddress);
return cartInfo;
}
```
### Response
#### Success Response (200)
- **cartInfo** (object) - Updated cart information.
- **shipping_addresses** (array) - Contains the set shipping address.
- **available_shipping_methods** (array) - List of available shipping methods for the set address.
- **carrier_code** (string)
- **method_code** (string)
- **carrier_title** (string)
- **method_title** (string)
- **amount** (object) - Shipping cost.
- **value** (float)
#### Response Example
```json
{
"cartInfo": {
"shipping_addresses": [
{
"available_shipping_methods": [
{ "carrier_code": "flatrate", "method_code": "flatrate", "carrier_title": "Flat Rate", "method_title": "Fixed", "amount": { "value": 5.00 } }
]
}
]
}
}
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.