Basic concepts
One of the features of the MoneyHash iOS SDK is providing a single state for each step in the payment flow. The state along with stateDetails guide the actions and methods required to proceed and complete the flow.
SDK States Table
State | Action | Intent Type |
---|---|---|
MethodSelection | The MethodSelection state contains an IntentMethods object with available payment methods. You can render these methods natively with custom styles. After the user selects a method, use moneyHashSDK.proceedWithMethod to proceed. | Payment , Payout |
FormFields | Render form fields received in FormFields state, including card fields, billing, and shipping fields. Submit them using moneyHashSDK.submitForm . For more information on card fields, refer to Card Form Fields. | Payment , Payout |
UrlToRender | Use moneyHashSDK.renderForm to let MoneyHash handle the current stage of the payment/payout flow. After completing the process, MoneyHash will call the completion handler with intent details or an error. | Payment , Payout , CardToken |
SavedCardCVV | Collect CVV using the schema from stateDetails.cvvField , then use moneyHashSDK.submitCardCVV to proceed with the payment. | Payment |
IntentForm | Use moneyHashSDK.renderForm to let MoneyHash handle the current stage of the payment/payout flow. After completing the process, MoneyHash will call the completion handler with intent details or an error. | Payment , Payout |
IntentProcessed | Display a success confirmation UI with the intent details. | Payment , Payout |
TransactionFailed | Display a failure UI with the intent details. | Payment , Payout |
TransactionWaitingUserAction | Display a pending actions confirmation UI with the intent details and any externalActionMessage if provided in TransactionData . | Payment , Payout |
Expired | Display an expired intent UI. | Payment , CardToken |
Closed | Display a closed intent UI. | Payment , Payout ,CardToken |
CardIntentSuccessful | Display a success UI for the created card token. | CardToken |
CardIntentFailed | Display a failure UI for the created card token. | CardToken |
States Handling:
When handling the FormFields
state in MoneyHash, you will deal with two primary tasks:
- Handling Billing or Shipping Data if
billingFields
orshippingFields
are passed on the state and not null. - Handling Card Form if the
tokenizeCardInfo
is passed on the state object and not null.
1. Handling Billing or Shipping Data
-
Rendering Input Fields:
Use the
InputField
data inbillingFields
orshippingFields
to render the form fields. Each field has properties likelabel
,name
,isRequired
, andmaxLength
that can be used to guide the form's construction.
Example of how to render billing and shipping fields:
if case let .formFields(_, billingFields, shippingFields) = intentState {
// Rendering billing fields
if let billingFields = billingFields {
for field in billingFields {
print("Billing Field: \(field.label), Required: \(field.isRequired)")
// Use this information to dynamically render input components
// Example: Create UITextField programmatically using the field data
}
}
// Rendering shipping fields
if let shippingFields = shippingFields {
for field in shippingFields {
print("Shipping Field: \(field.label), Required: \(field.isRequired)")
// Use this information to dynamically render input components
}
}
}
-
Collecting User Input:
Collect the user input from the form fields and store it in a dictionary for both billing and shipping data. Use each field's
name
attribute as the key.
Example of collecting billing and shipping data:
let billingData: [String: String] = [
"firstName": "John",
"lastName": "Doe",
"email": "[email protected]"
]
let shippingData: [String: String] = [
"addressLine1": "123 Main St",
"city": "Anytown",
"country": "US"
]
2. Handling Card Form
For the card form, use the tokenizeCardInfo
property to handle card data input securely.
- Common Steps (Collect Card Information)
- Scenario 1: Create New Token (Save Card)
- Scenario 2: Pay with the Collected Card Info
3. Submit Form
After collecting the necessary billing, shipping, and card data, the next step is to submit this data using the submitForm
method provided by the MoneyHash SDK.
Ensure that you set the public API key when initializing the SDK. The submitForm
method allows you to send the collected information to proceed with the payment or payout process. Make sure to pass the selectedMethod
from the IntentDetails
object to the API.
import { MoneyHashSDKBuilder } from '@moneyhash/reactnative-sdk';
const moneyHashSDK = MoneyHashSDKBuilder()
.setPublicKey("your_public_key") // Set your public API key here
.build();
async function submitPayment(intentDetails) {
try {
// Get form fields from the intent details
const billingFields = intentDetails.intentState?.billingFields || [];
const shippingFields = intentDetails.intentState?.shippingFields || [];
// Prepare billing data based on the input fields
const billingData = {};
billingFields.forEach((field) => {
billingData[field.name] = 'user_input_value'; // Replace with actual input values
});
// Prepare shipping data based on the input fields
const shippingData = {};
shippingFields.forEach((field) => {
shippingData[field.name] = 'user_input_value'; // Replace with actual input values
});
// Optionally collect card data if needed
const cardData = {}; // Assume card data is collected from card form if tokenizeCardInfo is present
// Submit the form data
const submittedIntentDetails = await moneyHashSDK.submitForm(
intentDetails.intent?.id || '',
intentDetails.selectedMethod || '',
billingData, // Optional
shippingData, // Optional
cardData // Optional
);
// Handle success
console.log('Form submitted successfully:', submittedIntentDetails);
} catch (error) {
// Handle error
console.error('Error submitting form:', error);
}
}
In this example:
- The
MoneyHashSDKBuilder
is configured with a public API key using thesetPublicKey
method before building the SDK instance. - Billing and shipping data are extracted from
FormFields
inintentState
. - The
submitForm
method sends the data, including theselectedMethod
, along with optional card data, to complete the payment.
The UrlToRender
state occurs when you need to render a URL as part of the payment or payout flow. The UrlToRender
case in the IntentStateDetails
enum provides two key properties:
url
: The URL that needs to be rendered.renderStrategy
: A suggestion on how the URL should be rendered (e.g.,iframe
,popupIFrame
, orredirect
), using theRenderStrategy
enum.
In this state, you should use the moneyHash.renderForm()
method to handle the payment or payout flow. This method takes care of rendering the URL based on the intent and manages the interaction flow. Once the process is complete (successfully or with an error), it returns the corresponding IntentDetails
or throws an exception.
Steps to Handle the UrlToRender
State
UrlToRender
State-
Invoke the
renderForm()
Method:Call the
renderForm()
method with the necessaryintentId
,intentType
, and optionalembedStyle
to proceed with rendering the form and handling the current stage of the payment or payout flow.Example of handling the
UrlToRender
state:if case let .redirectToURL(url, renderStrategy) = intentState { moneyHashSDK.renderForm( on: viewController, intentId: intentId, embedStyle: nil, // Optional: Custom embed style if needed intentType: .payment, // Example intent type: payment or payout completionHandler: { result in switch result { case .success(let intentDetails): print("Form rendered successfully:", intentDetails) case .failure(let error): print("Error rendering form:", error) } } ) }
-
Completion Handling:
- On Success: The
renderForm()
method returns anIntentDetails
object that provides the final state and outcome of the process. - On Error: If an error occurs during the process, the method throws an exception. You should handle this exception appropriately to display an error message or take corrective action.
- On Success: The
// Example of handling the UrlToRender state in your app
if case let .redirectToURL(url, renderStrategy) = intentState {
do {
moneyHashSDK.renderForm(
on: viewController,
intentId: intentId,
embedStyle: nil, // Optional styling
intentType: .payout // Example intent type: payment or payout
) { result in
switch result {
case .success(let intentDetails):
print("Payment completed:", intentDetails)
case .failure(let error):
print("Error during form rendering:", error)
}
}
} catch {
// Handle error
print("Error during URL rendering:", error)
}
}
In this example, MoneyHash handles the entire flow of rendering the URL and managing user interaction. After the form rendering is complete, it returns either IntentDetails
if processed or throws an exception if something goes wrong.
Tip: You can customize the form appearance by providing an
EmbedStyle
object, allowing for a more tailored user interface during the form rendering process.
The SavedCardCVV
state occurs when a saved card requires the user to input their CVV to proceed with the payment. In this state, you will collect the CVV from the user and submit it using the submitCardCVV()
method.
The SavedCardCVV
case in the IntentStateDetails
enum provides two key properties:
cvvField
: AnInputField
object that describes the CVV field, including its label, validation requirements, and other metadata.cardTokenData
: Optional information about the saved card for which the CVV is being collected, represented byCardTokenData
.
Steps to Handle the SavedCardCVV
State
SavedCardCVV
State-
Render the CVV Input Field:
- Use the
cvvField
property from theSavedCardCVV
state to render the input field for the CVV. - Ensure you apply the field validation based on the rules provided in the
cvvField
.
- Use the
-
Retrieve Card Details and CVV Field Information from the State:
- Access Card Details: Use the
CardTokenData
property to access details about the saved card. - Access CVV Field Information: Use the
cvvField
property to obtain information about the CVV input field, including its label, validation requirements, and other metadata.
Example of Retrieving Card Details and CVV Field Information:
if case let .savedCardCVV(cvvField, cardTokenData) = intentState { // Access card details if let cardDetails = cardTokenData { let last4 = cardDetails.last4 ?? "" let brand = cardDetails.brand ?? "Unknown" let expiryMonth = cardDetails.expiryMonth ?? "" let expiryYear = cardDetails.expiryYear ?? "" let cardHolderName = cardDetails.cardHolderName ?? "" // Display card information to the user print("Using saved card ending with \(last4) (\(brand)) expiring on \(expiryMonth)/\(expiryYear)") // Optionally, update your UI with this information // Example: // cardInfoLabel.text = "Card: \(brand) **** **** **** \(last4)" // expiryLabel.text = "Expires: \(expiryMonth)/\(expiryYear)" } else { print("No card details available.") } // Access CVV field information let fieldName = cvvField.name ?? "cvv" let fieldLabel = cvvField.label ?? "CVV" let isRequired = cvvField.isRequired let maxLength = cvvField.maxLength ?? 4 let minLength = cvvField.minLength ?? 3 let hint = cvvField.hint ?? "Enter the 3 or 4-digit code on the back of your card" // Use cvvField information to render the input field // Example, assuming you have a UITextField for CVV input: cvvTextField.placeholder = fieldLabel cvvTextField.isSecureTextEntry = true cvvTextField.delegate = self cvvTextField.keyboardType = .numberPad // Apply other configurations based on cvvField properties }
Available Properties in
cvvField
(InputField
):type
: The type of the input field (e.g.,.text
).name
: The name of the field (e.g.,"cvv"
).label
: The label to display for the field (e.g.,"CVV"
).isRequired
: A boolean indicating whether the field is required.maxLength
: The maximum allowed length of the input.minLength
: The minimum required length of the input.hint
: A hint or placeholder text for the input field.readOnly
: A boolean indicating whether the field is read-only (typicallyfalse
for CVV).- Other properties as applicable.
- Access Card Details: Use the
-
Collect the CVV Value:
After the user inputs their CVV, collect the value and validate it based on the constraints provided in
cvvField
. -
Submit the CVV Using
submitCardCVV()
:Once you have the CVV from the user, use the
submitCardCVV()
method to submit the CVV and proceed with the payment.// Example of handling the SavedCardCVV state if case let .savedCardCVV(cvvField, cardTokenData) = intentState { let cvv = cvvTextField.text ?? "" Task { do { let intentDetails = try await moneyHashSDK.submitCardCVV( intentID: "your_intent_id", cvv: cvv ) print("Payment processed successfully:", intentDetails) // Handle success, e.g., navigate to a confirmation screen } catch let error as MHError { // Handle MHError specifically print("Error during CVV submission: \(error.message)") } } }
-
Completion Handling:
- On Success: If the CVV is submitted successfully, the
submitCardCVV()
method returns anIntentDetails
object, containing information about the current intent state. - On Error: If an error occurs during the CVV submission, handle the exception appropriately by displaying an error message or prompting the user to retry.
- On Success: If the CVV is submitted successfully, the
The IntentForm
state occurs when MoneyHash needs to handle the current stage of the payment or payout flow via the embedded form. In this state, you will use the renderForm()
method to render the form and handle the completion of the process through the provided completion handler.
The IntentForm
case in the IntentStateDetails
enum indicates that a form is required for the user to enter necessary details to proceed with the intent.
Steps to Handle the IntentForm
State
IntentForm
State-
Render the MoneyHash Form:
Use the
renderForm()
method to render the form within your app, passing the required parameters such asintentId
,intentType
, and optionally,embedStyle
to customize the form's appearance. -
Handle Completion or Error:
The form will guide the user through the payment or payout process. After the user completes the form, MoneyHash will call the completion handler with the
IntentDetails
if the process is successful, or an error if it fails.
Example of Handling the IntentForm
State
IntentForm
State// Example of handling the IntentForm state
if case .intentForm = intentState {
let intentId = "your_intent_id"
let intentType: IntentType = .payment // Example: .payment or .payout
let embedStyle: EmbedStyle? = nil // Optional: Customize the form's appearance
moneyHashSDK.renderForm(
on: viewController,
intentId: intentId,
embedStyle: embedStyle,
intentType: intentType
) { result in
switch result {
case .success(let intentDetails):
print("Form completed successfully:", intentDetails)
// Handle success, e.g., navigate to a confirmation screen
case .failure(let error):
if let mhError = error as? MHError {
print("Error rendering form: \(mhError.message)")
if !mhError.errors.isEmpty {
for errorInfo in mhError.errors {
print("Error key: \(errorInfo.key), message: \(errorInfo.message)")
}
}
} else {
print("Unexpected error rendering form:", error.localizedDescription)
}
}
}
}
In this example:
- Rendering the Form: The
renderForm()
method is called with the necessary parameters to display the form to the user. - Handling Success: If the form is completed successfully, the
IntentDetails
object is returned, and you can handle the success accordingly (e.g., show a confirmation screen). - Handling Errors: If an error occurs during form rendering or submission, it is handled by checking if it's an
MHError
and then processing the error message and details.
Tip: You can customize the form's appearance by providing an
EmbedStyle
object, allowing for a more tailored user interface during the form rendering process.
Other Available MoneyHash SDK Methods
In addition to the essential steps and methods previously described, the MoneyHash iOS Swift SDK provides other methods to customize the user experience. These additional methods are presented and described below.
In the MoneyHash SDK for iOS, you can reset the selected payment method for a specific intent using the resetSelectedMethod()
method. This allows your customers to go back and choose a different payment method if needed. It can be used in the following scenarios:
- Offering a button to let the customer return and select a new payment method after they have already selected one.
- Allowing the customer to retry and choose a different payment method after a failed transaction.
Example of Resetting the Selected Method
do {
let intentId = "your_intent_id"
let intentType: IntentType = .payment // or .payout
// Reset the selected method
let methodsResult = try await moneyHashSDK.resetSelectedMethod(intentId: intentId, intentType: intentType)
print("Intent details:", methodsResult.intentData)
// You can now render available payment methods again for the user to select a different one.
} catch let error as MHError {
// Handle MHError
print("Error resetting selected method: \(error.message)")
if !error.errors.isEmpty {
for errorInfo in error.errors {
print("Error key: \(errorInfo.key), message: \(errorInfo.message)")
}
}
}
By using this method, you can offer more flexibility to your users during the payment flow, letting them go back and change their payment method even after selection.
In the MoneyHash SDK for iOS, you can delete a customer's saved card using the deleteSavedCard()
method. This is useful when managing a list of customer-saved cards, allowing them to remove a card they no longer wish to keep on file.
Example of Deleting a Saved Card
do {
let cardTokenId = "your_card_token_id" // The ID of the saved card to be deleted
let intentSecret = "your_intent_secret" // The intent secret for verification
// Call the method to delete the saved card
try await moneyHashSDK.deleteSavedCard(cardTokenId: cardTokenId, intentSecret: intentSecret)
print("Card deleted successfully.")
// Handle any post-deletion logic, like refreshing the card list or showing a confirmation message
} catch let error as MHError {
// Handle MHError
print("Error deleting saved card: \(error.message)")
if !error.errors.isEmpty {
for errorInfo in error.errors {
print("Error key: \(errorInfo.key), message: \(errorInfo.message)")
}
}
}
By using this method, you can allow users to manage their saved cards within your app, providing the option to delete cards as needed.
In the MoneyHash SDK for iOS, you can update the fees associated with an intent using the updateFees()
method. This method requires the intentId
and a list of FeeItem
objects, allowing you to adjust the fees at the intent level.
Please note that fees cannot be updated for intents that already have transactions.
Example of Updating Fees
do {
let intentId = "your_intent_id" // The ID of the intent to update the fees
let fees: [FeeItem] = [
FeeItem(
title: [
.english: "Service Fee",
.arabic: "رسوم الخدمة",
.french: "Frais de service"
],
value: "10",
discount: nil
),
FeeItem(
title: [
.english: "Handling Fee",
.arabic: "رسوم المناولة",
.french: "Frais de manutention"
],
value: "15",
discount: nil
)
]
// Call the method to update the fees
if let updatedFees = try await moneyHashSDK.updateFees(intentId: intentId, fees: fees) {
print("Fees updated successfully: \(updatedFees.amount ?? "N/A")")
} else {
print("Fees updated successfully.")
}
// Handle any post-update logic, like refreshing the fee display
} catch let error as MHError {
// Handle MHError
print("Error updating fees: \(error.message)")
if !error.errors.isEmpty {
for errorInfo in error.errors {
print("Error key: \(errorInfo.key), message: \(errorInfo.message)")
}
}
}
This method enables you to modify the fees associated with an intent while following the necessary restrictions regarding existing transactions.
In the MoneyHash SDK for iOS, you can update the discount for an intent using the updateDiscount()
method. This method allows you to pass the intentId
and a DiscountItem
object to adjust the discount on an intent level.
Please note the following restrictions when updating a discount:
- Discounts can't be updated for intents that have transactions.
- Can't update discount when the intent has product items that have a discount.
- Can't update discount when the intent has fees that have a discount.
- Discount value must not be more than the intent amount.
Example of Updating a Discount
do {
let intentId = "your_intent_id" // The ID of the intent to update the discount
let discount = DiscountItem(
title: [
.english: "Promo Code",
.arabic: "رمز العرض",
.french: "Code Promo"
],
type: .amount, // DiscountType.amount or .percentage
value: "10" // Discount value
)
// Call the method to update the discount
if let updatedDiscount = try await moneyHashSDK.updateDiscount(intentId: intentId, discount: discount) {
print("Discount updated successfully: \(updatedDiscount.amount ?? "N/A")")
} else {
print("Discount updated successfully.")
}
} catch let error as MHError {
// Handle MHError
print("Error updating discount: \(error.message)")
if !error.errors.isEmpty {
for errorInfo in error.errors {
print("Error key: \(errorInfo.key), message: \(errorInfo.message)")
}
}
}
This method allows you to apply or update a discount on an intent, adhering to the defined conditions and limitations.
In the MoneyHash SDK for iOS, you can set the locale to handle localization for different languages by calling the setLocale()
method and passing the desired Language
enum value.
Example of Setting Locale
moneyHashSDK.setLocale(.arabic)
print("Locale set to Arabic successfully")
You can choose from the following languages:
Language.arabic
Language.english
Language.french
This allows the SDK to present text and messages in the selected language, enhancing the user experience for a multilingual audience.
To authenticate and make use of the MoneyHash SDK, you need to set your public API key by calling the setPublicKey()
method. This should be done early in your application's initialization process.
Example of Setting Public Key
// Set the public API key
moneyHashSDK.setPublicKey("your_public_api_key")
print("Public key set successfully")
Make sure to replace "your_public_api_key"
with your actual public API key.
You can adjust the SDK's log level using the setLogLevel()
method. The LogLevel
enum defines the possible levels of logging, allowing you to control the verbosity of the logs.
Example of Setting Log Level
// Set the log level to 'debug'
moneyHashSDK.setLogLevel(logLevel: .debug)
print("Log level set to debug successfully")
You can set the log level to any of the following options:
LogLevel.verbose
LogLevel.debug
LogLevel.info
LogLevel.warn
LogLevel.error
LogLevel.assertion
This helps manage the SDK's logging behavior, which can be useful for debugging and monitoring purposes.
Customization
With MoneyHash's iOS Swift SDK, you can customize the appearance of the embedded form, including the submit button, input fields, and loader. To do so, you can pass an EmbedStyle
object when calling the renderForm()
method, allowing you to modify styles according to your brand’s needs.
Here’s how you can use the customization options with EmbedStyle
for different components:
Customizing Submit Button
You can customize the submit button by providing the EmbedButtonStyle
inside the EmbedStyle
. This allows you to style the button's base, hover, and focus states.
Example:
// Define the base style for the submit button
let baseButtonStyle = EmbedButtonViewStyle(
color: "#FFFFFF",
fontFamily: "Arial, sans-serif",
fontWeight: "bold",
fontSize: "16px",
fontSmoothing: nil,
lineHeight: nil,
textTransform: nil,
letterSpacing: nil,
background: "#000000",
padding: "10px",
borderRadius: "5px",
boxShadow: nil,
borderStyle: nil,
borderColor: nil,
borderWidth: nil
)
// Define the hover style for the submit button
let hoverButtonStyle = EmbedButtonViewStyle(
color: nil,
fontFamily: nil,
fontWeight: nil,
fontSize: nil,
fontSmoothing: nil,
lineHeight: nil,
textTransform: nil,
letterSpacing: nil,
background: "#333333",
padding: nil,
borderRadius: nil,
boxShadow: nil,
borderStyle: nil,
borderColor: nil,
borderWidth: nil
)
// Define the focus style for the submit button
let focusButtonStyle = EmbedButtonViewStyle(
color: nil,
fontFamily: nil,
fontWeight: nil,
fontSize: nil,
fontSmoothing: nil,
lineHeight: nil,
textTransform: nil,
letterSpacing: nil,
background: nil,
padding: nil,
borderRadius: nil,
boxShadow: nil,
borderStyle: nil,
borderColor: "#FF0000",
borderWidth: nil
)
// Combine the button styles into EmbedButtonStyle
let buttonStyle = EmbedButtonStyle(
base: baseButtonStyle,
hover: hoverButtonStyle,
focus: focusButtonStyle
)
Customizing Input Fields
The EmbedInputStyle
allows you to customize the base, focus, and error states of the input fields in the form. This helps you to match the input fields with the overall design of your application.
Example:
// Define the base style for the input fields
let baseInputStyle = EmbedInputViewStyle(
height: nil,
padding: "10px",
background: "#F5F5F5",
borderRadius: "5px",
boxShadow: nil,
borderStyle: nil,
borderColor: "#CCCCCC",
borderWidth: nil,
color: nil,
fontFamily: nil,
fontWeight: nil,
fontSize: nil,
fontSmoothing: nil,
lineHeight: nil
)
// Define the focus style for the input fields
let focusInputStyle = EmbedInputViewStyle(
height: nil,
padding: nil,
background: nil,
borderRadius: nil,
boxShadow: nil,
borderStyle: nil,
borderColor: "#000000",
borderWidth: nil,
color: nil,
fontFamily: nil,
fontWeight: nil,
fontSize: nil,
fontSmoothing: nil,
lineHeight: nil
)
// Define the error style for the input fields
let errorInputStyle = EmbedInputViewStyle(
height: nil,
padding: nil,
background: nil,
borderRadius: nil,
boxShadow: nil,
borderStyle: nil,
borderColor: "#FF0000",
borderWidth: nil,
color: nil,
fontFamily: nil,
fontWeight: nil,
fontSize: nil,
fontSmoothing: nil,
lineHeight: nil
)
// Combine the input styles into EmbedInputStyle
let inputStyle = EmbedInputStyle(
base: baseInputStyle,
error: errorInputStyle,
focus: focusInputStyle
)
Customizing Loader
You can also customize the appearance of the loader that is shown during the form submission process using the EmbedLoaderStyle
.
Example:
// Define the loader style
let loaderStyle = EmbedLoaderStyle(
backgroundColor: "#000000",
color: "#FFFFFF"
)
Applying the Custom Styles
Once you’ve customized the styles, you can apply them when calling the renderForm()
API method.
Example:
do {
// Combine all styles into EmbedStyle
let customEmbedStyle = EmbedStyle(
submitButton: buttonStyle,
loader: loaderStyle,
input: inputStyle
)
// Render the form with custom styles
try moneyHashSDK.renderForm(
on: self, // Your UIViewController instance
intentId: "your_intent_id",
embedStyle: customEmbedStyle,
intentType: .payment
) { result in
switch result {
case .success(let intentDetails):
print("Form rendered successfully with details: \(intentDetails)")
case .failure(let error):
if let mhError = error as? MHError {
print("Failed to render form: \(mhError.message)")
if !mhError.errors.isEmpty {
for errorInfo in mhError.errors {
print("Error key: \(errorInfo.key), message: \(errorInfo.message)")
}
}
} else {
print("Failed to render form: \(error.localizedDescription)")
}
}
}
} catch let error as MHError {
// Handle MHError
print("Error applying custom styles: \(error.message)")
if !error.errors.isEmpty {
for errorInfo in error.errors {
print("Error key: \(errorInfo.key), message: \(errorInfo.message)")
}
}
}
Handling Errors in the SDK
In the MoneyHash iOS Swift SDK, errors are represented using the MHError
struct. This struct provides detailed information about the error that occurred during a request or operation, including the error message, type, and additional details. This allows you to handle different error scenarios effectively and provide users with meaningful feedback.
The MHError
struct contains the following key attributes:
message
: A user-friendly error message describing the issue.errors
: A list ofErrorInfo
objects that provide more granular details about specific fields or issues.type
: AnErrorType
enum value that categorizes the type of error.
The ErrorType
enum categorizes the errors that can occur within the SDK. The possible types are:
NETWORK
: Indicates a network-related issue, such as connectivity problems or API errors.UNKNOWN
: An unexpected or unknown error occurred.CARD_VALIDATION
: Validation failed for card details provided by the user.CANCELLED
: The operation was cancelled by the user or the system.APPLE_PAY_TRANSACTION_FAILED
: The Apple Pay transaction could not be completed.NOT_COMPATIBLE_WITH_APPLE_PAY
: The device is not compatible with Apple Pay.
The ErrorInfo
struct provides additional context for specific errors. Each error has:
key
: The specific field or component that caused the error.message
: A detailed message explaining the error related to that field or component.
Example of ErrorInfo
:
ErrorInfo
:let errorDetail = ErrorInfo(key: "cardNumber", message: "Invalid card number")
print("Error with field: \(errorDetail.key), Message: \(errorDetail.message)")
Error Handling Example
When an error occurs during an operation, such as submitting payment details, you can catch the MHError
and handle it accordingly.
do {
// Example of a MoneyHash SDK operation
let intentDetails = try await moneyHashSDK.submitCardCVV(intentID: "your_intent_id", cvv: "123")
print("Payment submitted successfully.")
} catch let error as MHError {
// Handle different error types
switch error.type {
case .network:
print("Network error: \(error.message)")
case .cardValidation:
print("Card validation failed: \(error.message)")
case .cancelled:
print("Operation cancelled: \(error.message)")
case .applePayTransactionFailed:
print("Apple Pay transaction failed: \(error.message)")
case .notCompatibleWithApplePay:
print("Device not compatible with Apple Pay: \(error.message)")
case .unknown:
print("Unknown error: \(error.message)")
}
// Additional error details
if !error.errors.isEmpty {
for errorInfo in error.errors {
print("Error detail - Key: \(errorInfo.key), Message: \(errorInfo.message)")
}
}
} catch {
// Handle other types of errors if necessary
print("An unexpected error occurred: \(error.localizedDescription)")
}
This documentation provides iOS developers with the necessary guidance to handle various SDK states, use additional methods, customize the embedded form, and handle errors effectively, following the same structure and sections as the iOS documentation provided.
Updated 23 days ago