### Install Dependencies Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/README.md Run this command to install project dependencies. ```bash yarn ``` -------------------------------- ### Complete SwiftUI Example with PayTheory Integration Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/main/getting_started/quickstart.mdx A full example demonstrating the integration of PayTheory in a SwiftUI view, including initialization, form setup, card fields, and the payment button. Remember to replace placeholder API keys. ```swift import SwiftUI import PayTheory struct ContentView: View { let payTheory = PayTheory(apiKey: "your-api-key-here") { error in print("Error: \(error.error)") } var body: some View { PTForm { VStack { PTCardName() PTCardNumber() PTExp() PTCvv() PTCardPostalCode() Button("Pay") { payTheory.transact(amount: 1000, paymentMethod: .card) { response in switch response { case .success(let payment): print("Payment successful: \(payment.transactionId)") case .failure(let failure): print("Payment failed: \(failure.failureText)") case .error(let error): print("Error: \(error.error)") case .barcode: print("Barcode generation not applicable for card payments") } } } } } .environmentObject(payTheory) } } ``` -------------------------------- ### Start Local Development Server Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/README.md Starts a local development server. Changes are reflected live without restarting. ```bash yarn start ``` -------------------------------- ### Start Local Development Server Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/CLAUDE.md Use this command to start the local development server with hot reload enabled. ```bash npm start ``` -------------------------------- ### PayTheory Initialization Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/pay_theory_class.mdx Example of how to initialize the PayTheory class with specific parameters, including amount, API key, and an error handler. ```swift let payTheory = PayTheory( amount: 1000, // $10.00 apiKey: "partner-stage-1234567890abcdef", devMode: true ) { error in print("Error occurred: \(error.error)") } ``` -------------------------------- ### Update Fee Matrix Return Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/merchant.md Example of the data returned after a successful updateFeeMatrix mutation. ```json { "data": { "updateFeeMatrix": { "ach": { "merchant_fee": { "basis_points": 0, "fixed": 0, "max_fee": 0 }, "service_fee": { "basis_points": 0, "fixed": 0, "max_fee": 0, "min_fee": 0 } }, ... } } } ``` -------------------------------- ### User Query Response Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/users.md An example of the JSON response structure when querying for users. ```json { "data": { "users": [ { "username": "XXXXXX", "email": "XXXXXX", "user_status": "XXXXXX", "full_name": "XXXXXX", "phone": "XXXXXX" }, { "username": "XXXXXX", "email": "XXXXXX", "user_status": "XXXXXX", "full_name": "XXXXXX", "phone": "XXXXXX" } ] } } ``` -------------------------------- ### Create Batch Capture Response Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/settlement.md Example JSON response for the createBatchCapture mutation, indicating success. ```json { "data": { "createBatchCapture": true } } ``` -------------------------------- ### Example Cash Payment Form Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/ui_components/cash_fields.mdx An example demonstrating how to integrate PTCashName and PTCashContact within a PTForm. Ensure the PayTheory object is provided as an environment object. ```swift struct CashPaymentView: View { @EnvironmentObject var payTheory: PayTheory var body: some View { PTForm { VStack(spacing: 20) { PTCashName() PTCashContact() // Add other UI elements as needed, such as amount display or submit button } } .environmentObject(payTheory) } } ``` -------------------------------- ### Update Merchant Settings Return Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/merchant.md Example of the data returned after a successful updateMerchantSettings mutation, indicating success with a boolean value. ```json { "data": { "updateMerchantSettings": true } } ``` -------------------------------- ### Complete ContentView Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/main/online_payments/tokenizing/quickstart.mdx A full SwiftUI view integrating PayTheory initialization, form fields, and a payment tokenization button. ```swift import SwiftUI import PayTheory struct ContentView: View { let payTheory = PayTheory(apiKey: "your-api-key-here") { error in print("Error: \(error.error)") } var body: some View { PTForm { VStack { PTCardName() PTCardNumber() PTExp() PTCvv() PTCardPostalCode() Button("Tokenize Payment Method") { payTheory.tokenizePaymentMethod(paymentMethod: .card) { response in switch response { case .success(let token): print("Payment Method Generated: \(token.paymentMethodId)") case .error(let error): print("Error: \(error.code)") } } } } } .environmentObject(payTheory) } } ``` -------------------------------- ### Complete ACH Payment Form Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/ui_components/ach_fields.mdx An example demonstrating how to integrate all ACH UI fields within a PTForm. Ensure the PayTheory object is provided as an environment object. ```swift struct ACHPaymentView: View { @EnvironmentObject var payTheory: PayTheory var body: some View { PTForm { VStack(spacing: 20) { PTAchAccountName() PTAchAccountNumber() PTAchRoutingNumber() PTAchAccountType() } } .environmentObject(payTheory) } } ``` -------------------------------- ### GraphQL POST Request Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/main.md Example of how to execute a GraphQL query using a POST request with cURL. Ensure to replace placeholders with your actual credentials and API URL. ```shell curl --location --request POST '{GraphQL API URL}' --header 'Authorization: MERCHANT_UID;SECRET_KEY' --header 'Content-Type: application/graphql' --data '{"query":"{transactions(limit: 3) { items { transaction_id }}}"}' ``` -------------------------------- ### Pay Theory Button Setup Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/main/online_payments/payment_button.mdx This section outlines the parameters for initializing the Pay Theory button, which handles payment processing. ```APIDOC ## Initialize Pay Theory Button ### Description Initializes the Pay Theory button with the necessary configuration to handle payments. ### Method JavaScript Function Call ### Endpoint N/A (Client-side integration) ### Parameters #### Required Parameters - **apiKey** (string) - Required - The API key for your Pay Theory account. You can find this in your Pay Theory Portal. - **checkoutDetails** (object) - Required - The details for the checkout page that opens when the button is clicked. Details are mentioned [above](#3-prepare-the-checkout-details). #### Optional Parameters - **onReady** (function) - Optional - A function that will be called when the button is ready to be clicked. - **onClick** (function) - Optional - A function that will be called when the button is clicked. - **onError** (function) - Optional - A function that will be called when an error occurs. It is passed an error string. - **onCancel** (function) - Optional - A function that will be called when the user cancels the payment from the pop-up window. - **onSuccess** (function) - Optional - A function that will be called when the payment is successful. It is passed an object with the following values: - last_four (String) - The last four digits of the card number or account number. - amount (Int) - The amount of the transaction (service fee is included). - service_fee (Int) - The service fee of the transaction. - receipt_number (String) - The Pay Theory receipt number. - brand (String) - The brand of the card. - created_at (String) - The date and time the transaction was created. - state (String) - The status of the transaction. - metadata (JSON) - The metadata of the transaction. - payor_id (String) - The Pay Theory id for the payor that was used for the transaction. - payment_method_id (String) - The Pay Theory id for the payment method token. - **onBarcode** (function) - Optional - A function that will be called when a barcode is successfully created and the user closes the window. It is passed an object with the following values: - barcodeUrl (String) - The url for the barcode image. - mapUrl (String) - The url for the map to find retail locations to pay the barcode. ### Request Example ```javascript const payTheoryButton = new PayTheoryButton({ apiKey: "YOUR_API_KEY", checkoutDetails: { // ... checkout details object ... }, onSuccess: (data) => { console.log("Payment successful:", data); }, onError: (error) => { console.error("An error occurred:", error); } }); ``` ### Response #### Success Response (onSuccess callback) - **last_four** (String) - The last four digits of the card number or account number. - **amount** (Int) - The amount of the transaction (service fee is included). - **service_fee** (Int) - The service fee of the transaction. - **receipt_number** (String) - The Pay Theory receipt number. - **brand** (String) - The brand of the card. - **created_at** (String) - The date and time the transaction was created. - **state** (String) - The status of the transaction. - **metadata** (JSON) - The metadata of the transaction. - **payor_id** (String) - The Pay Theory id for the payor that was used for the transaction. - **payment_method_id** (String) - The Pay Theory id for the payment method token. #### Error Response (onError callback) - **error** (String) - A string describing the error that occurred. #### Barcode Response (onBarcode callback) - **barcodeUrl** (String) - The url for the barcode image. - **mapUrl** (String) - The url for the map to find retail locations to pay the barcode. ### Note Setting up a button session will only enable a single payment. If you want to enable multiple payments, you will need to clear the button from the DOM and create a new button. ``` -------------------------------- ### Complete Card Payment Form Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/state/card_state.mdx This Swift example demonstrates a complete card payment form using PayTheory's UI components. It utilizes the `CardState` and its sub-classes to provide real-time validation feedback and controls the submission button's enabled state based on the overall card validity. ```swift struct CardPaymentForm: View { @EnvironmentObject var payTheory: PayTheory var body: some View { VStack { PTCardNumber() .background(backgroundColor(for: payTheory.card.number)) PTExp() .background(backgroundColor(for: payTheory.card.exp)) PTCvv() .background(backgroundColor(for: payTheory.card.cvv)) PTCardPostalCode() .background(backgroundColor(for: payTheory.card.postalCode)) Button("Submit Card Payment") { submitPayment() } .disabled(!payTheory.card.isValid) } } private func backgroundColor(for field: ValidAndEmpty) -> Color { if field.isEmpty { return .white } else if field.isValid { return .green.opacity(0.2) } else { return .red.opacity(0.2) } } private func submitPayment() { // Card payment submission logic } } ``` -------------------------------- ### Pay Theory GraphQL API - POST Request Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/main.md A command-line example using cURL to send a POST request to the GraphQL API endpoint, including authentication and content type headers. ```APIDOC ## POST GraphQL Query Request ### Description This example demonstrates how to send a POST request to the GraphQL API endpoint using cURL. ### Method POST ### Endpoint `{GraphQL API URL}` ### Headers - `Authorization: MERCHANT_UID;SECRET_KEY` - `Content-Type: application/graphql` ### Request Body ```json { "query": "{transactions(limit: 3) { items { transaction_id } }}" } ``` ### cURL Example ```bash curl --location --request POST '{GraphQL API URL}' \ --header 'Authorization: MERCHANT_UID;SECRET_KEY' \ --header 'Content-Type: application/graphql' \ --data '{"query":"{transactions(limit: 3) { items { transaction_id } }}"}' ``` ``` -------------------------------- ### Checkout Example with updateAmount Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/functions/update_amount.mdx Demonstrates how to use updateAmount within a ViewModel to dynamically update the cart total and associated fees. Observe cardServiceFee and bankServiceFee for fee updates. ```swift class CheckoutViewModel: ObservableObject { @Published var payTheory: PayTheory @Published var cartTotal: Int = 0 // Amount in cents init() { payTheory = PayTheory( amount: 0, // Initial amount apiKey: "your-api-key-here", feeMode: .serviceFee // Using service fee model ) { error in print("PayTheory Error: \(error.error)") } } func updateCart(newTotal: Int) { cartTotal = newTotal payTheory.updateAmount(newAmount: newTotal) } } struct CheckoutView: View { @ObservedObject var viewModel: CheckoutViewModel var body: some View { VStack { Text("Cart Total: $\(Double(viewModel.cartTotal) / 100.0, specifier: \"%.2f\")") Text("Card Fee: $\(Double(viewModel.payTheory.cardServiceFee ?? 0) / 100.0, specifier: \"%.2f\")") Text("ACH Fee: $\(Double(viewModel.payTheory.bankServiceFee ?? 0) / 100.0, specifier: \"%.2f\")") // Payment form fields including PTCardNumber Button("Add $10 Item") { viewModel.updateCart(newTotal: viewModel.cartTotal + 1000) } } } } ``` -------------------------------- ### Payor Query Response Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/payor.md Example JSON response structure for a payor query, showing the returned items and total count. ```json { "data": { "payors": { "items": [ { "payor_id": "pt_pay_XXXXX", }, { "payor_id": "pt_pay_XXXXX", }, ... ], "total_row_count": 256 } } } ``` -------------------------------- ### Create Merchant Response Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/merchant.md Example response structure after creating a merchant, including the new merchant's UID. ```json { "data": { "createMerchant": { "merchant_uid": "XXXXXX", ... } } } ``` -------------------------------- ### Settlements Query Response Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/settlement.md Example JSON response structure for a settlements query, showing paginated items and total count. ```json { "data": { "settlements": { "items": [ { "settlement_batch": "42" }, { "settlement_batch": "41" }, ... ], "total_row_count": 256 } } } ``` -------------------------------- ### Implement Payment Button (ACH) Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/main/online_payments/ach_payments.mdx Add a button to initiate the payment process for ACH. This example shows how to handle the response, including success, failure, and error cases. ```swift Button("Pay") { payTheory.transact(amount: 1000, paymentMethod: .ach) { response in switch response { case .success(let payment): print("Payment successful: \(payment.transactionId)") case .failure(let failure): print("Payment failed: \(failure.failureText)") case .error(let error): print("Error: \(error.error)") case .barcode: print("Barcode generation not applicable for ach payments") } } } ``` -------------------------------- ### Using PayTheory in SwiftUI Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/pay_theory_class.mdx Example of integrating the PayTheory class into a SwiftUI view using @StateObject and passing it as an environment object. ```swift struct ContentView: View { @StateObject private var payTheory = PayTheory( apiKey: "your-api-key-here" ) { error in print("PayTheory Error: \(error.error)") } var body: some View { PTForm { // Your payment form contents } .environmentObject(payTheory) } } ``` -------------------------------- ### Set Service Fee Mode for Transaction Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/data_models/enums.mdx Example demonstrating how to set the fee mode to 'serviceFee' for a transaction, indicating the customer will pay the fee. Requires amount, payment method, and fee details. ```swift // Example: Setting up a transaction with a service fee payTheory.transact(amount: 1000, paymentMethod: .card, fee: 50, feeMode: .serviceFee) { // Handle transaction response } ``` -------------------------------- ### Async Transact Usage Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/functions/transact.mdx Use this async version for new projects with Swift 5.5+. It handles transactions and provides structured concurrency for better error handling. ```swift do { let response = try await payTheory.transact( amount: 1000, paymentMethod: .card, metadata: ["order_id": "12345"] ) switch response { case .success(let transaction): print("Transaction successful: \(transaction.transactionId)") case .failure(let failure): print("Transaction failed: \(failure.failureText)") case .error(let error): print("Error occurred: \(error.error)") case .barcode: print("Barcode generated (not applicable for card payments)") } } catch { print("An error occurred: \(error)") } ``` -------------------------------- ### Handle Errors with errorObserver in JavaScript Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/main/getting_started/error_handling.mdx Use the errorObserver to catch and manage errors from the SDK. This example shows how to log specific errors like FIELD_ERROR or NO_TOKEN. Ensure the SDK is initialized and ready before using this observer. ```javascript window.paytheory.errorObserver(error => { if (error.startsWith("FIELD_ERROR")) { // Logic to handle field-related errors console.log("There was an issue with fields on the DOM when mounting."); // Additional code specific to field errors } else if (error.startsWith("NO_TOKEN")) { // Logic to handle auth token fetching errors console.log("There was an error fetching the auth token when initializing the SDK."); // Additional code specific to auth token errors }}); ``` -------------------------------- ### Serve Built Site Locally Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/CLAUDE.md Use this command to serve the locally built static site. ```bash npm run serve ``` -------------------------------- ### Build Static Site for Production Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/CLAUDE.md This command builds the static site for production deployment. ```bash npm run build ``` -------------------------------- ### Deploy Website (Using SSH) Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/README.md Deploys the website using SSH. Assumes SSH is configured for deployment. ```bash USE_SSH=true yarn deploy ``` -------------------------------- ### Transaction Response Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/transaction.md This is an example of the JSON response structure when querying transactions. It includes a list of items, each with a transaction_id, and the total_row_count for pagination. ```javascript { "data": { "transactions": { "items": [ { "transaction_id": "pt-start-paytheorylab-rbdg98004adg" }, { "transaction_id": "pt-start-paytheorylab-rbdgaf004adh" }, ... ], "total_row_count": 256 } } } ``` -------------------------------- ### PayTheory Class Initialization Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/pay_theory_class.mdx Demonstrates how to initialize the PayTheory class with required parameters and an error handler. ```APIDOC ## PayTheory Class Initialization ### Description Initializes the `PayTheory` class, which is the core component for managing payment processing within the PayTheory iOS SDK. ### Method `init(amount: Int?, apiKey: String, devMode: Bool = false, errorHandler: @escaping (PTError) -> Void)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Description | |--------------|-------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | amount | `Int?` | An optional integer representing the transaction amount in cents. If provided, it will be used to calculate fees for Service Fee mode. Defaults to `nil`. | | apiKey | `String` | A string containing the API key for authentication with PayTheory services. It should be in the format `'{partner}-{paytheorystage}-{UUID}'`. | | devMode | `Bool` | A boolean flag indicating whether to run in development mode. When `true` it allows you to skip the app attestation process and run in the simulator. This cannot be turned on in production. | | errorHandler | `@escaping (PTError) -> Void` | A closure that handles any errors that might occur during initialization and other background actions. It takes a `PTError` parameter and doesn't return a value. | ### Request Example ```swift let payTheory = PayTheory( amount: 1000, // $10.00 apiKey: "partner-stage-1234567890abcdef", devMode: true ) { error in print("Error occurred: \(error.error)") } ``` ### Response #### Success Response (200) N/A (Initialization does not return a response body) #### Response Example N/A ``` -------------------------------- ### Create and Access Address Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/data_models/address.mdx Demonstrates how to create an Address object and access its properties. Properties can be accessed using optional chaining. ```swift let address = Address( line1: "123 Main St", line2: "Apt 4B", city: "Anytown", country: "USA", region: "CA", postalCode: "12345" ) // Accessing properties print(address.city ?? "") // Outputs: Anytown print(address.region ?? "") // Outputs: CA // Updating properties var mutableAddress = address mutableAddress.postalCode = "54321" ``` -------------------------------- ### Get Recurring Payments Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/recurring.md Retrieves a list of recurring payments based on specified parameters and filters. ```APIDOC ## GET /recurringPayments ### Description Retrieves a list of recurring payments. Supports filtering, pagination, and nested data retrieval. ### Method GET ### Endpoint /recurringPayments ### Parameters #### Query Parameters - **direction** (MoveDirection) - Optional - The direction of the pagination. Makes sure the results are returned in the correct order. - **limit** (Int) - Optional - The number of recurring payments to return. - **offset** (String) - Optional - The value of the offset item for which the list is being sorted. - **offset_id** (String) - Optional - The `recurring_id` of the offset item. - **query** (SqlQuery) - Optional - The query to filter the recurring payments with based on Pay Theory defined data. Detailed information about the query object can be found [here](query). ### Nested Queries Recurring Payments can also be filtered by passing a query_list to the metadata, payment method, or payor. This will only return Recurring Payments that have Metadata, Payment Methods, or Payors that match these queries. Detailed information about the query list can be found [here](query). ### Response #### Success Response (200) - **items** ([RecurringPayment]) - The list of recurring payments that are returned from the query. - **total_row_count** (Int) - The total number of recurring payments that match the query. Used to help with pagination. #### Response Example { "items": [ { "account_code": "ACC123", "amount_per_payment": 1000, "created_date": "2023-01-01T10:00:00Z", "currency": "USD", "fee_mode": "EACH", "fee_per_payment": 50, "is_active": true, "is_processing": true, "merchant_uid": "MERCH456", "metadata": {}, "mute_all_emails": false, "next_payment_date": "2023-02-01T10:00:00Z", "payment_interval": "MONTHLY", "payment_method": {}, "prev_payment_date": null, "payor": {}, "recurring_description": "Monthly subscription", "recurring_id": "REC789", "recurring_name": "Subscription Plan A", "reference": "REF001", "remaining_payments": 12, "status": "ACTIVE", "total_amount_per_payment": 1050 } ], "total_row_count": 100 } ``` -------------------------------- ### Build Static Website Content Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/README.md Generates static content for hosting on any static content service. ```bash yarn build ``` -------------------------------- ### Cancel Recurring Payment Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/main/recurring_payments/manage_recurring_payments/cancel_recurring_payments.mdx This mutation cancels a recurring payment by its unique identifier. After cancellation, no further installments will be processed. ```APIDOC ## POST /graphql ### Description Cancels a recurring payment by its unique identifier. ### Method POST ### Endpoint /graphql ### Parameters #### Request Body - **query** (string) - Required - The GraphQL query string. ### Request Example ```json { "query": "mutation { cancelRecurringPayment(recurring_id: \"your_recurring_id\") }" } ``` ### Response #### Success Response (200) - **data.cancelRecurringPayment** (boolean) - True if the recurring payment was successfully canceled, false otherwise. #### Response Example ```json { "data": { "cancelRecurringPayment": true } } ``` ``` -------------------------------- ### Initialize Payor Instance Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/data_models/payor.mdx Demonstrates how to create a Payor object with personal and address details. Ensure Address object is properly initialized before passing it. ```swift let payorAddress = Address(line1: "123 Main St", city: "Anytown", region: "CA", postalCode: "12345", country: "USA") let payor = Payor( firstName: "John", lastName: "Doe", email: "john.doe@example.com", phone: "1234567890", personalAddress: payorAddress ) ``` -------------------------------- ### Merchant Query Response Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/merchant.md Example response structure for a merchant query, showing paginated items and total count. ```json { "data": { "merchants": { "items": [ { "merchant_uid": "XXXXXX", }, { "merchant_uid": "XXXXXX", }, ... ], "total_row_count": 24 } } } ``` -------------------------------- ### Initialize Pay Theory Hosted Fields (JavaScript) Source: https://context7.com/pay-theory/pay-theory-documentation/llms.txt Import the SDK, set up event listeners for errors, readiness, validity, and state changes, and then initialize the hosted fields with your API key and optional styling. Use this to securely collect payment information on your webpage. ```html
``` ```javascript // Step 3: Set up event listeners before initialization paytheory.errorObserver(error => { console.error('Payment error:', error); }); paytheory.readyObserver(ready => { console.log('Fields ready:', ready); }); paytheory.validObserver(valid => { if (valid.includes("card")) { document.getElementById('payButton').disabled = false; } }); paytheory.stateObserver(state => { // Access field states and service fees console.log('Card number focused:', state['card-number'].isFocused); console.log('Service fee for card:', state.service_fee.card_fee); }); // Step 4: Initialize the hosted fields const API_KEY = 'your-api-key'; paytheory.payTheoryFields({ apiKey: API_KEY, amount: 5000, // Optional: enables service fee calculation styles: { default: { color: 'black', fontSize: '14px' }, success: { color: '#5cb85c', fontSize: '14px' }, error: { color: '#d9534f', fontSize: '14px' } } }); ``` -------------------------------- ### Basic Transaction Response Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/main.md Example response for a basic transaction query, showing the structure of returned transaction IDs. ```json { "data": { "transactions": { "items": [ { "transaction_id": "pt-start-paytheorylab-rbdg98004adg" }, { "transaction_id": "pt-start-paytheorylab-rbdgaf004adh" }, { "transaction_id": "pt-start-paytheorylab-rbdgaf004adh:R1" } ] } } } ``` -------------------------------- ### GraphQL Query for Merchant Details Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/merchant.md Example of a GraphQL query to retrieve specific details for a merchant, identified by name or UID. ```graphql { merchant(merchant_name: String, merchant_uid: String) { ach_active api_key ... } } ``` -------------------------------- ### Create a Webhook Endpoint Source: https://context7.com/pay-theory/pay-theory-documentation/llms.txt Set up a webhook endpoint to receive real-time notifications for payment events. Provide the `endpoint` URL and a descriptive `name` for the webhook. ```graphql mutation CreateWebhook { createWebhook( endpoint: "https://api.yoursite.com/webhooks/paytheory" name: "Production Payment Notifications" ) { success } } ``` -------------------------------- ### Observe Hosted Fields Ready State Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/javascript/event_listeners.md Use `readyObserver` to execute logic when hosted fields are ready for user input. It passes a boolean `true` to the callback when ready. ```javascript const cleanupFunction = window.paytheory.readyObserver(ready => { // Logic to respond when the fields are ready }) ``` -------------------------------- ### Custom Query Object Structure Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/main/after_payments/custom_query.mdx An example of a fundamental custom query object, including query list and sort list. ```APIDOC ## Custom Query Object Example ### Description This example demonstrates the structure of a custom query object, specifying filtering criteria and sorting preferences. ### Request Body Example ```json { "query_list": [ { "key": "full_name", "value": "John Doe", "operator": "EQUAL", "conjunctive_operator": "NONE_NEXT" } ], "sort_list": { "direction": "ASC", "key": "transfer_date" } } ``` ``` -------------------------------- ### Extended Transaction Response Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/main.md Example response for an extended transaction query, including fields like settlement_batch, status, and full_name. ```json { "data": { "transactions": { "items": [ { "transaction_id": "pt-start-paytheorylab-rbdg98004adg", "settlement_batch": "23", "status": "SETTLED", "full_name": "John Doe" } ] } } } ``` -------------------------------- ### Payment Button Initialization Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/javascript/payment_button.md This section details how to initialize the payment button using the `paytheory.button()` function, including required and optional parameters. ```APIDOC ## POST /paytheory/button ### Description Initializes a payment session and generates a button to open a checkout page for accepting payments. ### Method POST ### Endpoint /paytheory/button ### Parameters #### Request Body - **apiKey** (String) - Required - The API key for your Pay Theory account. - **checkoutDetails** (Object) - Required - The details for the checkout page that opens when the button is clicked. - **amount** (Number) - Required - The amount to charge in cents. - **paymentName** (String) - Required - The name of the payment. - **paymentDescription** (String) - Optional - The description of the payment. - **requirePhone** (Boolean) - Optional - Whether to require a phone number. - **callToAction** (String) - Optional - The text for the call to action button (e.g., paytheory.DONATE). - **acceptedPaymentMethods** (String) - Optional - The accepted payment methods (e.g., paytheory.CARD_ONLY). - **payorId** (String) - Optional - The ID of the payor. - **metadata** (Object) - Optional - Additional metadata to associate with the payment. - **feeMode** (String) - Optional - The fee mode (e.g., paytheory.MERCHANT_FEE). - **accountCode** (String) - Optional - The account code. - **invoiceId** (String) - Optional - The invoice ID. - **recurringId** (String) - Optional - The recurring payment ID. - **style** (Object) - Optional - The style object to customize the payment button's appearance. - **color** (String) - Optional - The color of the button (e.g., paytheory.WHITE). - **callToAction** (String) - Optional - The text for the call to action button. - **pill** (Boolean) - Optional - Whether to use a pill shape for the button. - **height** (String) - Optional - The height of the button. - **onReady** (Function) - Optional - Callback function when the button is ready. - **onClick** (Function) - Optional - Callback function when the button is clicked. - **onError** (Function) - Optional - Callback function when an error occurs. - **onCancel** (Function) - Optional - Callback function when the user cancels the payment. - **onSuccess** (Function) - Optional - Callback function when the payment is successful. - **onBarcode** (Function) - Optional - Callback function when a barcode is successfully created. ### Request Example ```javascript const OPTIONS = { apiKey: "PT_API_KEY", checkoutDetails: { amount: 1000, paymentName: "School Technology Fees", paymentDescription: "Technology Fee for the 2019-2020 school year", requirePhone: true, callToAction: paytheory.DONATE, acceptedPaymentMethods: paytheory.CARD_ONLY, payorId: "pt_pay_XXXXXXXXX", metadata: { "student-name": "Jane Doe" }, feeMode: paytheory.MERCHANT_FEE, accountCode: "code-123456789", invoiceId: "pt_inv_XXXXXXXXX", recurringId: "pt_rec_XXXXXXXXX" }, style: { color: paytheory.WHITE, callToAction: paytheory.DONATE, pill: true, height: "48px" }, onReady: () => {}, onClick: () => {}, onError: (error) => { console.error(error); }, onCancel: () => {}, onSuccess: (response) => { console.log(response); }, onBarcode: (response) => { console.log(response); } } paytheory.button(OPTIONS); ``` ### Response #### Success Response (200) - **status** (String) - Indicates the status of the operation. - **message** (String) - A message describing the result of the operation. #### Response Example ```json { "status": "success", "message": "Payment session initialized successfully." } ``` ``` -------------------------------- ### Initialize Address Object Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/data_models/address.mdx Creates a new Address instance with optional address components. All properties are optional. ```swift public init(line1: String? = nil, line2: String? = nil, city: String? = nil, country: String? = nil, region: String? = nil, postalCode: String? = nil) ``` -------------------------------- ### Specify Card Payment in Transaction Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/data_models/enums.mdx Example of how to specify a card payment method when initiating a transaction. Ensure the PaymentType enum is imported. ```swift // Example: Specifying a card payment in a transaction payTheory.transact(amount: 1000, paymentMethod: .card) { // Handle transaction response } ``` -------------------------------- ### Closure-based Transact Usage Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/functions/transact.mdx This closure-based version is suitable for older projects or when preferred. The completion handler is called asynchronously on an arbitrary thread. ```swift payTheory.transact( amount: 1000, paymentMethod: .card, metadata: ["order_id": "12345"] ) { response in switch response { case .success(let transaction): print("Transaction successful: \(transaction.transactionId)") case .failure(let failure): print("Transaction failed: \(failure.failureText)") case .error(let error): print("Error occurred: \(error.error)") case .barcode: print("Barcode generated (not applicable for card payments)") } } ``` -------------------------------- ### Configure Payment with Metadata Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/android/functions.md Sets optional metadata for tracking payments. Metadata can include custom key-value pairs. ```Kotlin val metadata: HashMap = hashMapOf( "studentId" to "student_1859034", "courseId" to "course_1859034" ) payTheoryFragment.configure( apiKey = "API_KEY", amount = 1000, metadata = metadata ) ``` -------------------------------- ### Error Response Example Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/javascript/functions.md This JSON structure represents an error response from the Pay Theory API. The 'error' field contains a code and a descriptive message. ```json { "type": "ERROR", "error": "NOT_READY: Error message" } ``` -------------------------------- ### Initialize and Configure PayTheoryFragment Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/android/main.md Set your API key and transaction amount, then find and configure the PayTheoryFragment within your activity's onCreate method. ```kotlin private val apiKey = "API_KEY" ``` ```kotlin val payTheoryFragment = this.supportFragmentManager.findFragmentById(R.id.payTheoryFragment) as PayTheoryFragment ``` ```kotlin payTheoryFragment.configure(apiKey = apiKey, amount = 1000) ``` -------------------------------- ### Process Medical Expense Transaction Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/data_models/enums.mdx Example of processing a transaction categorized as a medical expense. This requires specifying the amount, payment method, and the health expense type. ```swift // Example: Processing a medical expense transaction payTheory.transact(amount: 15000, paymentMethod: .card, healthExpenseType: .medical) { // Handle transaction response } ``` -------------------------------- ### Configure Payment with Pay Theory SDK Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/android/functions.md Use this function to set up fields for submitting a payment. Requires an API key and the payment amount in cents. ```Kotlin payTheoryFragment.configure(apiKey = apiKey, amount = 1000) ``` -------------------------------- ### Transactions with Status `SETTLED` and Reference Prefix Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/query.md Find transactions with status `SETTLED` where the `reference` field starts with 'test'. Uses `LIKE` operator for pattern matching. ```graphql { transactions(limit: 5, query: {query_list: [ { key: "reference", value: "test%", operator: LIKE, conjunctive_operator: AND_NEXT }, { key: "status", value: "SETTLED", operator: EQUAL, conjunctive_operator: NONE_NEXT } ]}) { items { transaction_id reference gross_amount } total_row_count } } ``` -------------------------------- ### Query Transactions by Status and Reference Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/main/after_payments/custom_query.mdx Use this query to find transactions with a specific status (e.g., SETTLED) and a reference that starts with a given string (e.g., 'test'). ```graphql { transactions(limit: 5, query: {query_list: [ { key: "reference", value: "test%", operator: LIKE, conjunctive_operator: AND_NEXT }, { key: "status", value: "SETTLED", operator: EQUAL, conjunctive_operator: NONE_NEXT } ]}) { items { transaction_id reference gross_amount } total_row_count } } ``` -------------------------------- ### Get Missed Recurring Payment Data API Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/api/recurring.md Retrieves data necessary to calculate and display the amount required for a customer to catch up on missed recurring payments. ```APIDOC ## Get Missed Recurring Payment Data ### Description Retrieves details needed to inform the customer about the amount required to cover missed payments for a recurring payment. ### Method QUERY ### Endpoint /graphql ### Parameters #### Request Body - **recurring_id** (String) - Required - The `recurring_id` of the recurring payment to get missed payment data for. ### Request Example ```json { "query": "{ missedRecurringPaymentData(recurring_id: \"rec_abc\") { fee number_of_payments_missed total_amount_owed } }" } ``` ### Response #### Success Response (200) - **fee** (Int) - If the recurring payment has `fee_mode` set to `SERVICE_FEE`, this will be the total amount of fees that will be charged to the customer to payoff the missed payments. If the recurring payment has `fee_mode` set to `MERCHANT_FEE`, this will be 0. - **number_of_payments_missed** (Int) - The number of payments that have been missed. - **total_amount_owed** (Int) - The total amount that the customer will owe to payoff the missed payments. ``` -------------------------------- ### Initialize Pay Theory Object Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/javascript/deprecated.md Use this to initialize the Pay Theory object. Pass in the API key and styles object. This function returns a promise that resolves to the Pay Theory object. ```javascript const API_KEY = "YOUR_API_KEY" const STYLES = { ...style_options } const myPayTheory = await window.paytheory.create(API_KEY, STYLES) ``` -------------------------------- ### Generate Payment QR Code Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/javascript/payment_qr_code.md Use this snippet to initialize a payment session and generate a QR code. Ensure all required `checkoutDetails` are provided, and consider optional parameters for customization. The `OPTIONS` object configures the API key, checkout details, QR code size, and callback functions for readiness, errors, and success. ```javascript //Amount passed in is in cents const AMOUNT = 1000 const PAYMENT_METADATA = { "student-name": "Jane Doe" }; // Parameters that you will pass in to configure the checkout page that opens when the qrCode is scanned. const CHECKOUT_DETAILS = { amount: AMOUNT, paymentName: "School Technology Fees", paymentDescription: "Technology Fee for the 2019-2020 school year", requirePhone: true, callToAction: paytheory.DONATE, acceptedPaymentMethods: paytheory.CARD_ONLY, payorId: "pt_pay_XXXXXXXXX", metadata: PAYMENT_METADATA, feeMode: paytheory.MERCHANT_FEE, accountCode: "code-123456789", invoiceId: "pt_inv_XXXXXXXXX", recurringId: "pt_rec_XXXXXXXXX", } const OPTIONS = { apiKey: "PT_API_KEY", checkoutDetails: CHECKOUT_DETAILS, size: 150, onReady: () => {}, onError: () => {}, onSuccess: () => {} } paytheory.qrCode(OPTIONS) ``` -------------------------------- ### Create and Access Level3DataSummary Instance in Swift Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/sdk/apple/data_models/level_3_summary.mdx Demonstrates how to create a Level3DataSummary instance and access its properties. Amounts are in cents. ```swift let level3Data = Level3DataSummary( taxAmt: 1050, // $10.50 in cents taxInd: .taxAmountProvided, purchIdfr: "PUR-12345", orderNum: "ORD-6789", discntAmt: 500, // $5.00 in cents frghtAmt: 1500, // $15.00 in cents destPostalCode: "12345", prodDesc: ["Widget A", "Gadget B"] ) // Accessing properties print(level3Data.taxAmt ?? 0) // Outputs: 1050 print(level3Data.taxInd?.rawValue ?? "") // Outputs: "TAX_AMOUNT_PROVIDED" ``` -------------------------------- ### Generate QR Code with Checkout Details Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/main/online_payments/qr_code.mdx Initializes a payment session with specified amount, payment name, accepted methods, and optional metadata. Ensure the amount is in cents. The API key and payor ID are required for proper integration. ```javascript //Amount passed in is in cents const AMOUNT = 1000 const PAYMENT_METADATA = { "student-name": "Jane Doe" }; // Parameters that you will pass in to configure the checkout page that opens when the qrCode is scanned. const CHECKOUT_DETAILS = { amount: AMOUNT, paymentName: "School Technology Fees", acceptedPaymentMethods: paytheory.CARD_ONLY, payorId: "pt_pay_XXXXXXXXX", metadata: PAYMENT_METADATA, recurringId: "pt_rec_XXXXXXXXX", } const OPTIONS = { apiKey: "PT_API_KEY", checkoutDetails: CHECKOUT_DETAILS, size: 150, onReady: () => {}, onError: () => {}, onSuccess: () => {} } paytheory.qrCode(OPTIONS) ``` -------------------------------- ### Query Transactions with Nested Payment Method Details Source: https://github.com/pay-theory/pay-theory-documentation/blob/premain/docs/main/after_payments/custom_query.mdx This example shows how to query transactions based on a nested object, such as filtering by 'last_four' digits of the payment method, and sorting by 'gross_amount'. ```graphql { transactions(limit: 10, query:{ query_list: [ { key: "gross_amount", value: "1000", operator: GREATER_THAN, conjunctive_operator: NONE_NEXT } ], sort_pair: [{ direction: ASC, key: "gross_amount" }] } ) { items { currency gross_amount payment_method(query_list: [{ key: "last_four", value: "1234", operator: EQUAL }]) } total_row_count } } ```