React Installation

This is a react wrapper for the amwal-checkout-button package allowing it to be used directly in react projects

Example Repository and Demo

For a complete working example and live demonstration:

Installation

npm i amwal-checkout-button-react

Usage

import { AmwalCheckoutButton } from 'amwal-checkout-button-react'
import React, { useEffect, useRef, useState } from 'react';

const ReactPage = () => {
    const amwalRef = useRef<any>();
    const [shippment, setShippment] = useState<any>([
        { "id": "1", "label": "Free shipping", "price": 0 }
    ]);

    return (
        <AmwalCheckoutButton 
            ref={amwalRef}
            merchantId="sandbox-amwal-4e876d00-a50e-482c-a6e1-a1a9df400ce5" 
            amount="20" 
            countryCode="SA"
            locale="ar" 
            darkMode="auto"
            addressRequired={true}
            emailRequired={false}
            shippingMethods={shippment}
            addressHandshake
            
            // Address update event (you already have this)
            onAmwalAddressUpdate={(event) => {
                console.log('Address updated:', event.detail);
                setShippment([{ "id": "1", "label": "Free shipping", "price": 0 }])
                setTimeout(() => {
                    amwalRef.current.dispatchEvent(new Event('amwalAddressAck'))
                }, 1000)
            }}
            
            // Country selection event
            onAmwalAddressCountryUpdate={(event) => {
                console.log('Country selected:', event.detail);
                // Handle country change
            }}
            
            // State selection event
            onAmwalAddressStateUpdate={(event) => {
                console.log('State selected:', event.detail);
                // Handle state change
            }}
            
            // Payment success event
            onAmwalCheckoutSuccess={(event) => {
                console.log('Payment successful!', event.detail);
                const orderId = event.detail.orderId;
                // Handle successful payment
            }}
            
            // Modal dismissed event
            onAmwalDismissed={(event) => {
                console.log('Modal dismissed, success:', event.detail);
                // Handle modal dismissal
            }}
            
            // Pre-checkout trigger (requires enablePreCheckoutTrigger prop)
            onAmwalPreCheckoutTrigger={(event) => {
                console.log('Pre-checkout triggered:', event.detail);
                // Perform validation or pre-checkout logic
                // Then acknowledge or error:
                // amwalRef.current.dispatchEvent(new Event('amwalPreCheckoutTriggerAck'))
                // or
                // amwalRef.current.dispatchEvent(new Event('amwalPreCheckoutTriggerError'))
            }}
            
            // Pre-pay trigger (requires enablePrePayTrigger prop)
            onAmwalPrePayTrigger={(event) => {
                console.log('Pre-pay triggered:', event.detail);
                // Perform final validation before payment
                // Then acknowledge or error:
                // amwalRef.current.dispatchEvent(new Event('amwalPrePayTriggerAck'))
                // or
                // amwalRef.current.dispatchEvent(new Event('amwalPrePayTriggerError'))
            }}
            
            // Alternative payment success event
            onUpdateOrderOnPaymentsuccess={(event) => {
                console.log('Order updated on payment success:', event.detail);
                const orderId = event.detail.orderId;
                // Handle order update
            }}
        />
    );
}

Properties

PropertyAttributeDescriptionTypeDefault
addressHandshakeaddress-handshakeaddressHandshake specifies if address event and ack is activated ("true" or "false")booleanfalse
addressRequiredaddress-requiredaddressRequired specifies if shipping address is required or not ("true" or "false")booleantrue
allowedAddressCities--allowedAddressCities specifies an array of allowed states for the address example {"SA":{"XX1":["Riady","Afif"],"XX2":["Jeddah","Makkah"]},"US":{"US1":["San Jose","San Francisco"],"US2":["New york"]}}{ [index: string]: CitySpecs; }undefined
allowedAddressCountries--allowedAddressCountries specifies an array of allowed countries for the addressstring[]undefined
allowedAddressStates--allowedAddressStates specifies an array of allowed states for the address example {"SA":{"XX1":"State 1","XX2":"State 2"},"US":{"US1":"State 1","US2":"State 2"}}{ [index: string]: StateSpecs; }undefined
amountamountThe amount of money to charge the customernumberundefined
countryCodecountry-codeThe country code of the merchant (e.g. SA)SA"SA"
darkModedark-modeDark Mode: - on: turns on dark mode - off: turns on light mode - auto: use customer preference for dark mode"auto" | "off" | "on""off"
debugdebugdebug flag for verbose printing of debug messagesbooleanfalse
disableddisableddisables the checkout buttonbooleanfalse
discountdiscountdiscount specifies any discount to be appliednumber0
discountDescriptiondiscount-descriptiondiscountDescription provides description for the discountstringundefined
emailRequiredemail-requiredemailRequired specifies if email address is required or not ("true" or "false"). Can only be true if addressRequired is true.booleantrue
enableAppleCheckoutenable-apple-checkoutenableAppleCheckout specifies if Apple Checkout is enabledbooleanfalse
enableDynamicShippingDetailsenable-dynamic-shipping-detailsenableDynamicShippingDetails specifies if shipping countries, states and cities will load dynamically or prefilled in the parametersbooleanfalse
enablePreCheckoutTriggerenable-pre-checkout-triggerenable triggering a pre checkout click event to do initial tasks such as adding items to cartsbooleanfalse
enablePrePayTriggerenable-pre-pay-triggerenable triggering a pre pay event to do final task such as order creationbooleanfalse
feesfeesfees specifies any fees to be appliednumber0
feesDescriptionfees-descriptionfeesDescription provides description for the feesstringundefined
footerMessagefooter-messagetimelineFooterText specifies the text to be displayed in the footer of the timeline in the checkout modal.string''
initialAddress--initialAddress specifies a default address, Country field is country code (two letter ISO country code)IAddressundefined
initialEmailinitial-emailinitialEmail specifies a default emailstringundefined
initialFirstNameinitial-first-nameinitialFirstName specifies a default first namestringundefined
initialLastNameinitial-last-nameinitialLastName specifies a default last namestringundefined
initialPhoneNumberinitial-phone-numberinitialPhone specifies a default phone numberstringundefined
installmentOptionsUrlinstallment-options-urlThe installment options url is URL for the checkout page in the merchant websitestringundefined
installmentsCountinstallments-countNumber of installmentsnumber6
labellabelthe label of the button. Either checkout for final checkout or quicky-buy for per product buy"Bank Installments" | "Pay with Apple Pay" | "Quick Checkout""Quick Checkout"
localelocalethe language of the plugin. supported languages are Arabic ("ar") and English ("en")string"en"
merchantIdmerchant-idmerchantId is the key to use obtained from https://merchant.sa.amwal.techstringundefined
onlyShowBankInstallmentonly-show-bank-installmentonlyShowBankInstallment specifies if only bank installments should be shownbooleanfalse
postcodeOptionalCountries--enable postal code required optionstring[]undefined
refIdref-idrefId an identifier to be included in the installment transactionstringundefined
sendExtraAddressFieldssend-extra-address-fieldssendExtraAddressFields specifies if extra address fields are sent in amwalAddressUpdate eventbooleanfalse
shippingMethods--shippingMethods an array of shipping methodsIShippingMethod[][]
showContinueShoppingButtonshow-continue-shopping-buttondebug flag for verbose printing of debug messagesbooleanfalse
showDiscountRibbonshow-discount-ribbonshowDiscountRibbon to show discount ribbon values are ("true" or "false")booleanfalse
showPaymentBrandsshow-payment-brandsshowPaymentBrands to show supporeted brands under button values are ("true" or "false")booleanfalse
street2Requiredstreet2-requiredstreet2Required specifies if street 2 is required or not ("true" or "false"). Can only be true if addressRequired is true.booleanfalse
taxestaxestaxes specifies any additional taxesnumber0
testEnvironmenttest-environmentthis is an internal testing feature. don't specifystringundefined
timelineStyletimeline-styletimelineStyle specifies the style of the timeline in the checkout modal."default" | "simple"'default'
uniqueRefunique-refuniqueRef a boolean to enforce the uniqueness of refIdbooleanfalse

Events

EventDescriptionType
amwalAddressCountryUpdateamwalAddressCountryUpdate is a dom event fired on address country selection.CustomEvent<ICountry>
amwalAddressStateUpdateamwalAddressStateUpdate is a dom event fired on address country selection.CustomEvent<IState>
amwalAddressUpdateamwalAddressUpdate is a dom event fired on address selection.CustomEvent<IAddress>
amwalCheckoutSuccessamwalCheckoutSuccess is a dom event fired on success of installment. the event has orderId field which can be used to lookup transaction status at https://backend.sa.amwal.techCustomEvent<AmwalCheckoutStatus>
amwalDismissedamwalDismissed is a dom event fired when the amwal modal or popup window is dismissed, event.detail indicates if it's successfull or not (boolean)CustomEvent<AmwalDismissalStatus>
amwalPreCheckoutTriggeramwalPreCheckoutTrigger is a dom event fired once amwal checkout button is clicked before a transaction is created. It is enabled if enablePreCheckoutTrigger is set. It waits for either amwalPreCheckoutTriggerAck or amwalPreCheckoutTriggerError events to be sent back before proceeding with the normal checkout flow.CustomEvent<ITransactionDetails>
amwalPrePayTriggeramwalPrePayTrigger is a dom event fired once installment button is clicked before installment is processed. It is enabled if enablePrePayTrigger is set. It waits for either amwalPrePayTriggerAck or amwalPrePayTriggerError events to be sent back before proceeding to payment or aborting respectively.CustomEvent<ITransactionDetails>
updateOrderOnPaymentsuccessupdateOrderOnPaymentsuccess is a dom event fired on success of installment. the event has orderId field which can be used to lookup transaction status at https://backend.sa.amwal.techCustomEvent<AmwalCheckoutStatus>
📘

References

You can find references regarding attributes and events Example