BluePosGoSDK iOS API Reference

Public Swift interface for the BluePosGoSDK module.

ModuleBluePosGoSDK
LanguageSwift 6.3 (library evolution, Swift 6 language mode)
PlatformiOS 13.0+, arm64, Objective-C interop enabled

This SDK has two layers:

  1. App-to-app facade — BluePosGo.shared launches the BluePos Go companion app and parses the callback URL. Payment payloads can travel by URL scheme, gzip-compressed URL, or pasteboard handoff.
  2. Generated PayConex / POI client — OpenAPI models and an HTTP request stack whose default base path is https://api.payconex.net.

The .swiftinterface does not expose URL-scheme strings, query-parameter names, or pasteboard key formats. Those are implementation details. Callers should use the typed request/result API and handleCallback(url:).


Contents

  1. Integration
  2. BluePosGo
  3. Callback handling
  4. Payments
  5. Initialization
  6. Transaction list
  7. Full refund
  8. Partial refund
  9. Capture
  10. Save card
  11. Clear data
  12. Reboot
  13. Shared value types
  14. Logging
  15. PayConex HTTP client
  16. PayConex models
  17. Enumerations
  18. Validation
  19. Typical flows

Integration

import BluePosGoSDK

Register a custom URL scheme on the host app and forward every incoming URL to the SDK from application(_:open:options:) or the SwiftUI onOpenURL modifier:

func application(
    _ app: UIApplication,
    open url: URL,
    options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
    BluePosGo.shared.handleCallback(url: url)
}

handleCallback(url:) returns true when the URL belongs to a pending SDK operation and the matching completion handler has been invoked. It returns false for unrelated URLs.

All facade methods and in-progress flags are main-actor isolated. Call them from the main actor. Completions are not annotated @MainActor in the interface; hop back to the main actor before touching UI.

There is no documented way to run two operations of the same kind at once. Each operation has an is…InProgress flag and a …InProgress error.


BluePosGo

@MainActor
final public class BluePosGo

Process-wide coordinator. Use the shared instance; do not construct it.

Singleton

@MainActor public static let shared: BluePosGo

Logger

@MainActor public var logger: ((BluePosLogLevel, String) -> Void)?

Optional sink for SDK diagnostics. Levels are debug, info, warning, and error. The SDK does not retain logs itself.

In-progress flags

Each flag is true from a successful launch until the matching callback is delivered or the pending operation is cancelled.

PropertyOperation
isPaymentInProgressstartPayment
isInitializationInProgressinitialize
isTransactionListInProgressgetTransactionList
isFullRefundInProgressfullRefund
isPartialRefundInProgresspartialRefund
isCaptureInProgresscapture
isClearDataInProgressclearData
isRebootInProgressreboot
isSaveInProgresssave

Operations

MethodRequestResult
startPayment(request:completion:)PaymentRequestPaymentResult
startPayment(request:transport:completion:)PaymentRequest + PaymentLaunchTransportPaymentResult
initialize(request:completion:)InitializationRequestInitializationResult
getTransactionList(request:completion:)TransactionListRequestTransactionListResult
fullRefund(request:completion:)FullRefundRequestFullRefundResult
partialRefund(request:completion:)PartialRefundRequestPartialRefundResult
capture(request:completion:)CaptureRequestCaptureResult
clearData(request:completion:)ClearDataRequestClearDataResult
reboot(request:completion:)RebootRequestRebootResult
save(request:completion:)SaveRequestSaveResult

Cancellation

Cancelling drops the pending completion. It does not document a remote abort of work already running in the companion app.

func cancelPendingPayment()
func cancelPendingInitialization()
func cancelPendingTransactionList()
func cancelPendingFullRefund()
func cancelPendingPartialRefund()
func cancelPendingCapture()
func cancelPendingClearData()
func cancelPendingReboot()
func cancelPendingSave()

Deprecated entry point

@available(*, deprecated, message: "Use startPayment(request:completion:) with PaymentRequest.")
func sendRequest(
    requestId: String,
    amount: String,
    type: String,
    currency: String,
    returnUrl: String,
    customId: String,
    notes: String,
    completion: @escaping (PaymentResult) -> Void = { _ in }
)

Stringly-typed payment launch. Prefer PaymentRequest.


Callback handling

Every operation round-trips through a caller-supplied callbackURL. The companion app opens that URL; the host app must pass it to the SDK.

Dispatch

@MainActor func handleCallback(url: URL) -> Bool

Identifies the operation, parses the URL, checks requestId against the pending request when one was supplied, and invokes the stored completion. Returns false if the URL is not an SDK callback.

Predicates

These report whether a URL is shaped like the given callback. They do not complete an operation.

func isPaymentCallback(_ url: URL) -> Bool
func isInitializationCallback(_ url: URL) -> Bool
func isTransactionListCallback(_ url: URL) -> Bool
func isFullRefundCallback(_ url: URL) -> Bool
func isPartialRefundCallback(_ url: URL) -> Bool
func isCaptureCallback(_ url: URL) -> Bool
func isClearDataCallback(_ url: URL) -> Bool
func isRebootCallback(_ url: URL) -> Bool
func isSaveCallback(_ url: URL) -> Bool

Instance parsers

Parse a URL against the currently pending operation. Return nil when the URL is not a callback of that kind.

func paymentResult(from url: URL) -> PaymentResult?
func initializationResult(from url: URL) -> InitializationResult?
func transactionListResult(from url: URL) -> TransactionListResult?
func fullRefundResult(from url: URL) -> FullRefundResult?
func partialRefundResult(from url: URL) -> PartialRefundResult?
func captureResult(from url: URL) -> CaptureResult?
func clearDataResult(from url: URL) -> ClearDataResult?
func rebootResult(from url: URL) -> RebootResult?
func saveResult(from url: URL) -> SaveResult?

Static parsers

nonisolated. Useful in tests and when the caller wants to validate a callback without the singleton. Both expectation arguments default to nil (no check).

static func parsePaymentResult(from:expectedRequestId:expectedCallbackURL:) -> PaymentResult?
static func parseInitializationResult(from:expectedRequestId:expectedCallbackURL:) -> InitializationResult?
static func parseTransactionListResult(from:expectedRequestId:expectedCallbackURL:) -> TransactionListResult?
static func parseFullRefundResult(from:expectedRequestId:expectedCallbackURL:) -> FullRefundResult?
static func parsePartialRefundResult(from:expectedRequestId:expectedCallbackURL:) -> PartialRefundResult?
static func parseCaptureResult(from:expectedRequestId:expectedCallbackURL:) -> CaptureResult?
static func parseClearDataResult(from:expectedRequestId:expectedCallbackURL:) -> ClearDataResult?
static func parseRebootResult(from:expectedRequestId:expectedCallbackURL:) -> RebootResult?
static func parseSaveResult(from:expectedRequestId:expectedCallbackURL:) -> SaveResult?

A request-id mismatch surfaces as requestIdMismatch(expected:received:) on the operation’s error type rather than as nil.


Payments

PaymentRequest

Equatable, Sendable.

FieldTypeDefaultRole
requestIdString—Correlates the callback. Must be unique per in-flight payment.
amountDecimal—Transaction amount.
tipDecimal?nilOptional tip.
transactionTypePaymentTransactionType.sale.sale, .auth, or .save.
currencyString—Currency code supplied by the caller (for example "USD").
callbackURLURL—URL the companion app opens on completion.
customIdString?nilMerchant reference echoed on the response when present.
notesString?nilFree-text note sent with the request.
credentialsPaymentCredentials?nilOptional per-request PayConex credentials.
requiresReaderReadyBooltrueWhether the reader must be ready before launch.
public init(
    requestId: String,
    amount: Decimal,
    tip: Decimal? = nil,
    transactionType: PaymentTransactionType = .sale,
    currency: String,
    callbackURL: URL,
    customId: String? = nil,
    notes: String? = nil,
    credentials: PaymentCredentials? = nil,
    requiresReaderReady: Bool = true
)

PaymentTransactionType

String raw value, CaseIterable, Sendable.

CaseRaw value
sale"sale"
auth"auth"
save"save"

.save on a payment request is distinct from the dedicated save(request:completion:) operation.

PaymentLaunchTransport

Equatable, Sendable. Selects how the payment payload is handed to the companion app.

CaseMeaning
urlSchemePayload inline in the launch URL.
gzipPayload gzip-compressed into the launch URL.
pasteboardPayload via pasteboard handoff.
automatic(maxInlineURLLength: Int = 1800)SDK picks a transport. Falls back when the inline URL would exceed maxInlineURLLength.

Only startPayment exposes a transport argument. Other operations use the SDK’s default launch path.

PaymentCredentials

Codable, Equatable, Sendable.

FieldType
basicTokenString
accountIdString
environmentString

Also required by FullRefundRequest and PartialRefundRequest. Optional on PaymentRequest, SaveRequest, and (as separate fields) InitializationRequest.

PaymentResponse

Equatable, Sendable. Attached to every payment result that parsed a callback.

FieldType
callbackURLURL
requestIdString?
statusString?
processorMessageString?
approvalCodeString?
transactionIdString?
customIdString?

PaymentResult

public enum PaymentResult {
    case success(PaymentResponse)
    case cancelled(PaymentResponse)
    case declined(PaymentResponse)
    case failure(PaymentError, response: PaymentResponse?)
    public var response: PaymentResponse? { get }
}

response is present for the three terminal business outcomes and whenever a failure still carried a parseable callback.

PaymentError

Error, Equatable, Sendable, LocalizedError (errorDescription).

CaseWhen
invalidRequest(String)Request failed local validation. Associated value is the reason.
paymentAppNotInstalledCompanion app is not installed.
paymentInProgressA payment is already in flight.
invalidCallbackCallback URL could not be interpreted.
requestIdMismatch(expected:received:)Callback requestId does not match. received may be nil.
missingStatusCallback had no status.
paymentFailed(status: String?)Companion reported a non-success status that is not cancelled or declined.
pasteboardHandoffUnavailablePasteboard transport could not be used.
pasteboardHandoffMissingExpected pasteboard payload was absent.
pasteboardHandoffExpiredPasteboard payload was stale.
pasteboardHandoffInvalidPasteboard payload failed structural checks.
pasteboardHandoffDecryptionFailedPasteboard payload could not be decrypted.
urlPayloadTooLargeInline URL payload exceeded the transport limit.
urlPayloadInvalidInline URL payload was malformed.
urlPayloadDecompressionFailedGzip payload could not be inflated.

Pasteboard and URL-payload errors apply to payment launch transport. They are not declared on the other operations.

Launch

BluePosGo.shared.startPayment(request: request) { result in
    switch result {
    case .success(let response):
        break // response.transactionId, response.approvalCode
    case .cancelled(let response):
        break
    case .declined(let response):
        break // response.processorMessage
    case .failure(let error, let response):
        break // error.errorDescription
    }
}

Override transport when the payload is large or the pasteboard must be forced:

BluePosGo.shared.startPayment(request: request, transport: .automatic(maxInlineURLLength: 1800)) { result in
    // ...
}

Initialization

Provisions the companion app with account context before payments.

InitializationRequest

FieldTypeDefault
requestIdString—
callbackURLURL—
sourceApplicationStringBundle.main.bundleIdentifier ?? "unknown"
basicTokenString?nil
accountIdString?nil
environmentString?nil
basePathString?nil

basePath overrides the companion’s API origin for this initialization. The HTTP client’s own default is https://api.payconex.net.

InitializationResponse

FieldType
callbackURLURL
requestIdString?
statusString?
messageString?

InitializationResult

public enum InitializationResult {
    case initialized(InitializationResponse)
    case failure(InitializationError, response: InitializationResponse?)
    public var response: InitializationResponse? { get }
}

InitializationError

CaseMeaning
invalidRequest(String)Local validation failed.
initializationAppNotInstalledCompanion app missing.
initializationInProgressAn initialization is already in flight.
invalidCallbackCallback could not be parsed.
requestIdMismatch(expected:received:)Request id did not match.
missingStatusNo status on the callback.
initializationFailed(status: String?)Companion reported failure.
let request = InitializationRequest(
    requestId: UUID().uuidString,
    callbackURL: callbackURL,
    basicToken: token,
    accountId: accountId,
    environment: "cert"
)
BluePosGo.shared.initialize(request: request) { result in
    if case .initialized(let response) = result {
        // response.status, response.message
    }
}

Transaction list

TransactionListRequest

FieldTypeDefault
requestIdString?nil
callbackURLURL—

requestId is optional. When supplied, a mismatch is TransactionListError.requestIdMismatch.

TransactionListResponse

FieldType
callbackURLURL
requestIdString?
statusString?
errorCodeString?
errorMessageString?
transactionCountInt?
transactions[BluePosGoTransaction]

TransactionListResult

public enum TransactionListResult {
    case success(TransactionListResponse)
    case failure(TransactionListError, response: TransactionListResponse?)
    public var response: TransactionListResponse? { get }
}

TransactionListError

CaseMeaning
invalidRequest(String)Local validation failed.
transactionListAppNotInstalledCompanion app missing.
transactionListInProgressA list request is already in flight.
invalidCallbackCallback could not be parsed.
requestIdMismatch(expected:received:)Request id did not match.
missingStatusNo status on the callback.
missingTransactionListStatus present but the list payload was absent.
transactionListFailed(code:message:)Companion reported failure.
decodingFailed(String)List JSON could not be decoded. Associated value is the reason.

BluePosGoTransaction

Codable, Equatable, Identifiable, Sendable. ID is String.

MemberTypeNotes
amountDecimal
tipDecimal?
typeBluePosGoTransactionType?
customIdString?camelCase field.
customIDString?Alternate spelling accepted by the decoder.
notesString?
transactionDetailsBluePosGoTransactionDetails
totalAmountDecimalComputed.
idStringComputed identity.

Both customId and customID are stored. Treat them as decode aliases for the same merchant reference and prefer whichever the callback populated.

BluePosGoTransactionDetails

Codable, Equatable, Sendable.

FieldType
statusStatus?
descriptionString?
transactionIdString?
timestampString?
approvedAmountString?
requestedAmountString?
authCodeString?
processorMessageString?
entryModeResponseEntryMode?
cardBrandCardBrand?
cardLast4String?
cardLabelString (computed)

approvedAmount and requestedAmount are strings, matching the PayConex amount convention. Status, ResponseEntryMode, and CardBrand are the shared OpenAPI enums documented below.

BluePosGoTransactionType

String raw value, Codable, CaseIterable, Sendable.

sale, authorization, refund, capture, credit, debit, store, save, force, reversal, balance, void, initialization, unknownDefaultOpenApi.

unknownDefaultOpenApi is the OpenAPI generator’s forward-compatibility case. It is not a transaction the merchant requested.


Full refund

Refunds the full remaining amount of an existing transaction. Credentials are required.

FullRefundRequest

FieldType
requestIdString
transactionIdString
callbackURLURL
credentialsPaymentCredentials

FullRefundResponse

FieldType
callbackURLURL
requestIdString?
transactionIdString?
statusString?
errorCodeString?
errorMessageString?

FullRefundResult

public enum FullRefundResult {
    case success(FullRefundResponse)
    case failure(FullRefundError, response: FullRefundResponse?)
    public var response: FullRefundResponse? { get }
}

There is no separate cancelled or declined case. Non-success comes back as failure(.fullRefundFailed(code:message:), response:).

FullRefundError

invalidRequest(String), fullRefundAppNotInstalled, fullRefundInProgress, invalidCallback, requestIdMismatch(expected:received:), missingStatus, fullRefundFailed(code:message:).

All of these errors conform to LocalizedError.


Partial refund

PartialRefundRequest

FieldType
requestIdString
transactionIdString
amountDecimal
callbackURLURL
credentialsPaymentCredentials

amount is Decimal here. Capture uses a String amount. Do not interchange them.

PartialRefundResponse

Same shape as FullRefundResponse: callbackURL, requestId, transactionId, status, errorCode, errorMessage.

PartialRefundResult

public enum PartialRefundResult {
    case success(PartialRefundResponse)
    case failure(PartialRefundError, response: PartialRefundResponse?)
    public var response: PartialRefundResponse? { get }
}

PartialRefundError

invalidRequest(String), partialRefundAppNotInstalled, partialRefundInProgress, invalidCallback, requestIdMismatch(expected:received:), missingStatus, partialRefundFailed(code:message:).


Capture

Captures a prior authorization.

CaptureRequest

FieldType
requestIdString
transactionIdString
amountString
callbackURLURL

Amount is a string, consistent with PayConex decimal-string amounts. No credentials field on this request.

CaptureResponse

FieldType
callbackURLURL
requestIdString?
statusString?
typeString?
transactionIdString?
approvedAmountString?
originalTransactionIdString?
errorCodeString?
errorMessageString?

CaptureResult

public enum CaptureResult {
    case success(CaptureResponse)
    case failure(CaptureError, response: CaptureResponse?)
    public var response: CaptureResponse? { get }
}

CaptureError

invalidRequest(String), captureAppNotInstalled, captureInProgress, invalidCallback, requestIdMismatch(expected:received:), missingStatus, captureFailed(code:message:).


Save card

Stores a payment method without charging it. Distinct from PaymentTransactionType.save passed to startPayment.

SaveRequest

FieldTypeDefault
requestIdString—
callbackURLURL—
currencyString"USD"
customIdString?nil
notesString?nil
credentialsPaymentCredentials?nil

SaveResponse

FieldType
callbackURLURL
requestIdString?
statusString?
transactionIdString?
approvalCodeString?
processorMessageString?
entryModeString?
cardBrandString?
cardLast4String?
errorCodeString?
errorMessageString?

entryMode and cardBrand are plain strings on this response, not the ResponseEntryMode and CardBrand enums used by BluePosGoTransactionDetails.

SaveResult

public enum SaveResult {
    case success(SaveResponse)
    case cancelled(SaveResponse)
    case declined(SaveResponse)
    case failure(SaveError, response: SaveResponse?)
    public var response: SaveResponse? { get }
}

SaveError

invalidRequest(String), saveAppNotInstalled, saveInProgress, invalidCallback, requestIdMismatch(expected:received:), missingStatus, saveFailed(code:message:).


Clear data

Reads card data from the reader. The result distinguishes a successful clear read, a masked read, and a cardholder cancel.

ClearDataRequest

FieldTypeDefault
requestIdString—
callbackURLURL—
amountDecimal?nil
timeoutInt?nil

ClearDataResponse

FieldType
callbackURLURL
requestIdString?
statusString?
clearPanString?
clearTrack2String?
errorCodeString?
errorMessageString?

clearPan and clearTrack2 are sensitive. Do not log, persist, or place them in analytics. Prefer the masked result path when PAN storage is not required.

ClearDataResult

public enum ClearDataResult {
    case success(ClearDataResponse)   // clear PAN / track present
    case masked(ClearDataResponse)    // masked data only
    case cancelled(ClearDataResponse)
    case failure(ClearDataError, response: ClearDataResponse?)
    public var response: ClearDataResponse? { get }
}

ClearDataError

invalidRequest(String), clearDataAppNotInstalled, clearDataInProgress, invalidCallback, requestIdMismatch(expected:received:), missingStatus, clearDataFailed(code:message:).


Reboot

Reboots the paired reader.

RebootRequest

FieldType
requestIdString
callbackURLURL

RebootResponse

FieldType
callbackURLURL
requestIdString?
statusString?
responseCodeInt?
readerSerialString?
errorCodeString?
errorMessageString?

RebootResult

public enum RebootResult {
    case success(RebootResponse)
    case failure(RebootError, response: RebootResponse?)
    public var response: RebootResponse? { get }
}

RebootError

invalidRequest(String), rebootAppNotInstalled, rebootInProgress, invalidCallback, requestIdMismatch(expected:received:), missingStatus, rebootFailed(code:message:).


Shared value types

Operation result pattern

Business outcomes that the companion distinguishes are dedicated cases (success, cancelled, declined, initialized, masked). Transport, validation, and unmatched statuses are failure(Error, response:).

response is nil when the SDK failed before a callback existed (app not installed, invalid request, operation already in progress, pasteboard handoff failure).

Error pattern

Every operation error conforms to LocalizedError. Use errorDescription for display text. Do not match on the localized string; match on the enum case.

Common cases across operations:

Case shapeMeaning
invalidRequest(String)Caller-side validation.
…AppNotInstalledCompanion app cannot be opened.
…InProgressSame operation already pending.
invalidCallbackURL was not a well-formed callback.
requestIdMismatch(expected:received:)Stale or foreign callback.
missingStatusCallback omitted status.
…Failed(code:message:)Companion or processor failure. Payment and initialization use paymentFailed(status:) and initializationFailed(status:) instead.

Amount conventions

APIAmount type
PaymentRequest.amount, .tipDecimal
PartialRefundRequest.amountDecimal
ClearDataRequest.amountDecimal?
BluePosGoTransaction.amount, .tip, .totalAmountDecimal
CaptureRequest.amountString
PayConex Amounts.total and related fieldsString
Transaction-list detail amountsString?

Decimal-string amounts on the wire are the PayConex convention. The facade converts Decimal for the operations that accept it.


Logging

public enum BluePosLogLevel: String, Sendable {
    case debug, info, warning, error
}
BluePosGo.shared.logger = { level, message in
    // host logging
}

The closure is main-actor isolated because it lives on BluePosGo. Do not log clearPan, clearTrack2, basicToken, or other credentials from callback payloads.


PayConex HTTP client

Generated OpenAPI stack for Bluefin PayConex POI. Default origin: https://api.payconex.net. Types below are independent of the URL-scheme facade; the facade is the supported way to drive the reader.

BluefinBluePosPoiModelsAPIConfiguration

open class, @unchecked Sendable. Shared instance: BluefinBluePosPoiModelsAPIConfiguration.shared.

MemberTypeDefault
basePathString"https://api.payconex.net"
customHeaders[String: String][:]
credentialURLCredential?nil
requestBuilderFactoryRequestBuilderFactoryURLSessionRequestBuilderFactory()
apiResponseQueueDispatchQueue.main
codableHelperCodableHelperCodableHelper()
successfulStatusCodeRangeRange<Int>200..<300
interceptorOpenAPIInterceptorDefaultOpenAPIInterceptor()

Mutate shared before issuing requests, or pass a dedicated configuration into a RequestBuilder.

RequestBuilder<T>

open class, @unchecked Sendable, Identifiable by ObjectIdentifier. T: Sendable.

MemberType
parameters[String: any Sendable]?
methodString
URLStringString
requestTaskRequestTask
requiresAuthenticationBool
apiConfigurationBluefinBluePosPoiModelsAPIConfiguration
credentialURLCredential?
headers[String: String]
onProgressReady((Progress) -> Void)?
required init(
    method: String,
    URLString: String,
    parameters: [String: any Sendable]?,
    headers: [String: String] = [:],
    requiresAuthentication: Bool,
    apiConfiguration: BluefinBluePosPoiModelsAPIConfiguration = .shared
)
func addHeaders(_ aHeaders: [String: String])
func addHeader(name: String, value: String) -> Self
func addCredential()
@discardableResult
func execute(completion: @escaping @Sendable (Result<Response<T>, ErrorResponse>) -> Void) -> RequestTask

On Swift 5.3+ with async execution attributes:

@discardableResult
@concurrent func execute() async throws(ErrorResponse) -> Response<T>

RequestBuilderFactory

protocol RequestBuilderFactory: Sendable {
    func getNonDecodableBuilder<T>() -> RequestBuilder<T>.Type where T: Sendable
    func getBuilder<T>() -> RequestBuilder<T>.Type where T: Decodable, T: Sendable
}

URLSessionRequestBuilderFactory is the concrete factory. URLSessionRequestBuilder<T> and URLSessionDecodableRequestBuilder<T> are the URLSession implementations. Override createURLSession(), contentTypeForFormPart(fileURL:), createURLRequest(...), and buildHeaders() to customize transport.

RequestTask

final public class RequestTask {
    final public func cancel()
}

Returned by execute(completion:). Cancel is cooperative at the URLSession task.

Response<T>

FieldType
statusCodeInt
header[String: String]
bodyT
bodyDataData?
init(statusCode:header:body:bodyData:)
init(response: HTTPURLResponse, body: T, bodyData: Data?)

Response is Sendable when T is Sendable.

Errors

public enum ErrorResponse: Error, Sendable {
    case error(Int, Data?, URLResponse?, any Error)
}
public enum DecodableRequestBuilderError: Error, Sendable {
    case emptyDataResponse
    case nilHTTPResponse
    case unsuccessfulHTTPStatusCode
    case jsonDecoding(DecodingError)
    case generalError(any Error)
}
public enum DownloadException: Error, Sendable, Equatable, Hashable {
    case responseDataMissing
    case responseFailed
    case requestMissing
    case requestMissingPath
    case requestMissingURL
}

HTTPMethod

options, get, head, post, put, patch, delete, trace, connect. Raw values are the lowercase verb.

Encoding

JSONDataEncoding conforms to ParameterEncoding and writes a JSON body. JSONEncodingHelper.encodingParameters(forEncodableObject:codableHelper:) encodes an Encodable into the parameter dictionary the builder expects. APIHelper builds query items and header dictionaries, dropping nils and stringifying scalars.

CodableHelper

Holds the DateFormatter, JSONDecoder, and JSONEncoder used by the generated models. OpenISO8601DateFormatter is the OpenAPI date parser (date(from:) override).

Interceptor

public protocol OpenAPIInterceptor: Sendable {
    func intercept<T>(urlRequest:urlSession:requestBuilder:completion:) where T: Sendable
    func retry<T>(urlRequest:urlSession:requestBuilder:data:response:error:completion:) where T: Sendable
    func willSendRequest<T>(...)
    func didReceiveResponse<T>(...)
    func didComplete<T>(...)
}

willSendRequest, didReceiveResponse, and didComplete have empty default implementations. retry completes with OpenAPIInterceptorRetry.retry or .dontRetry. DefaultOpenAPIInterceptor is a pass-through.

URLSession seams

URLSessionProtocol and URLSessionDataTaskProtocol abstract the session for tests. URLSession and URLSessionDataTask conform.


PayConex models

All generated models are Sendable, Codable, and Hashable unless noted. Optional fields default to nil. Enums generated from OpenAPI include unknownDefaultOpenApi so unknown wire values decode instead of failing. containsUnknownDefaultOpenApiCase on those types reports whether any nested enum landed on that case.

String and numeric fields annotated with a *Rule static member are validated by Validator when the generated encoder/decoder enforces the OpenAPI constraint. Rule values themselves are not in the interface.

Transaction requests

SaleAndAuthRequest

Sale or authorization body.

FieldTypeRequired
timeoutInt?no
transactionIdString?no (transactionIdRule)
amountsAmountsExtendedyes
mmIdInt?no (mmIdRule)
descriptionString?no
traceTrace?no
healthcareHealthcare?no
customerCustomer?no
shippingAddressShippingAddress?no
ebtEBT?no
savePaymentBool?no

RefundRequest

FieldType
timeoutInt?
amountsAmounts?
descriptionString?
traceTrace?
customerCustomer?
shippingAddressShippingAddress?

CreditRequest

FieldTypeRequired
timeoutInt?no
transactionIdString?no
mmIdInt?no
amountsAmountsyes
descriptionString?no
traceTrace?no
savePaymentBool?no

ForceRequest

Force-post with a prior auth code.

FieldTypeRequired
timeoutInt?no
transactionIdString?no
mmIdInt?no
authCodeStringyes
amountsAmountsExtendedyes
descriptionString?no
traceTrace?no
customerCustomer?no
shippingAddressShippingAddress?no
savePaymentBool?no

CancelRequest / CancelResponse

CancelRequest.timeout: Int?. CancelResponse.status: String? (statusRule).

ProcessPoiRebootRequest

FieldType
timeoutInt?
allowOverrideBool?
delayInSecondsInt? (delayInSecondsRule)

This is the HTTP reboot body. The facade equivalent is RebootRequest.

Amounts

Amounts

FieldType
currencyCurrency?
totalString? (totalRule)

AmountsExtended

FieldTypeRequired
currencyCurrencyyes
totalStringyes
gratuityString?no
cashbackString?no

AmountsResponse

FieldTypeRequired
currencyCurrencyyes
approvedStringyes
requestedStringyes
gratuityString?no
cashbackString?no
surchargeString?no
additionalFeeString?no
balanceString?no

Currency is .usd or .unknownDefaultOpenApi.

Transaction response

TransactionResponse

FieldType
statusStatus?
amountsAmountsResponse?
customerCustomer?
descriptionString?
shippingAddressShippingAddress?
traceTraceResponse?
referenceString?
bfTokenReferenceString?
transactionIdString?
shieldConexTokenShieldConexCardToken?
cardCardResponse?
authAuthResponse?
emvEmvDataResponse?
binDataBinDataResponse?
cvmCVM?
tenderTypeTenderType?

AuthResponse

FieldTypeRequired
codeString?no
messageAuthMessageEnumyes
processorMessageStringyes
networkNameString?no
avsResponseCodeAVSResponseCode?no
cvv2ResponseCodeCVV2ResponseCode?no

CardResponse

name, brand: CardBrand?, bin, last4, expiry. All optional. name, last4, and expiry have string rules.

EmvDataResponse

All optional: aid, appLabel, tvr, tsi, arc, atc, cryptogram, entryMode, contactless: Bool?.

BinDataResponse

program: Program? (standard, unknown, healthcare, fleet, unknownDefaultOpenApi), programCard: ProgramCard? (fsa, hsa, hra, unknownDefaultOpenApi).

CVM

method required: signature, offlinePin, onlinePin, noCvmRequired, unknownDefaultOpenApi. signature: String? optional.

ShieldConexCardToken

bfid: String required. cardNumber and cardExpiration optional.

ListTransactionResponseInstance

Row in a processor transaction list (not the facade BluePosGoTransaction).

FieldType
statusStatus?
transactionIdString?
authMessageString?
authCodeString?
approvedAmountString?
transactionTypeTransactionType?
timestampDate?
referenceString?
cardTypeString?
entryModeResponseEntryMode?
last4String?
bfTokenReferenceString?

Nested TransactionType: sale, authorization, refund, credit, debit, store, force, reversal, balance, void, _init, unknownDefaultOpenApi.

Customer and address

Customer

name: String?, email: String?, phone: String?, billingAddress: Address?. name and phone have string rules.

Address

Required: address1, city, state, zip. Optional: address2, country, company.

ShippingAddress

Required: address1, city, state, zip, country, recipient. Optional: address2, company, recipientPhone, recipientEmail.

Trace

Trace (request)

cashier, clientIp, customId, timestamp: Date?, extTransactionId, tags: [String]?. extTransactionId and tags have rules.

TraceResponse

Request fields plus sourceIp, source, gpsLocation, networkTransactionId, history: [TransactionHistoryRecord]?, clickToPayTraceData.

GpsLocation

latitude and longitude required strings. accuracy optional.

TransactionHistoryRecord

action: Action? (_init, update, authorization, capture, transaction, refund, unknownDefaultOpenApi), requestId, correlationId, timestamp: Date?.

ClickToPayTraceData

Required: merchantTransactionId, correlationId, srcFlowId.

Healthcare and EBT

Healthcare

All optional strings: totalAmount, prescription, vision, dental, clinical, copay, transit. Each has a string rule.

EBT

type required: cash, voucher, food, unknownDefaultOpenApi. voucherNumber optional.

Reader, dialog, and receipt

StatusResponse

Reader heartbeat. All optional: serial, modelName, osVersion, macAddress, ipAddress, linesPerScreen: Int?, charsPerLine: Int?, appVersion, timestamp: Date?.

ShowDialogRequest

title required. Optional: timeout, button1…button4, body, requiresSignature, style: ShowDialogStyle?.

ShowDialogStyle

backgroundColor: String? (backgroundColorRule), textColor (light, light2, dark, dark2), textSize (small, small2, medium, medium2, large, large2).

ShowDialogResponse

selected: String?.

CustomReceiptRequest

content: String required. timeout: Int? optional.

ReceiptResponse

outcome: String?.

ReprintReceiptRequest

transactionId and copy required. copy is customer or merchant. Optional: mmid: Int?, transType (auth, capture, sale, refund, reversal), additionalInfo.

CaptureSignatureResponse

signature: String?.

PoslinkRequest / PoslinkResponse

PoslinkRequest.command: String required, timeout optional. PoslinkResponse.response: String?.

Errors from the API

ApiViolation

message, traceId: UUID?, errorType: ErrorType?, errorCode: Int?, value, source, details: [ErrorDetail]?.

ErrorDetail

source, value, message. All optional.

ModelError

code: Int, message: String. Both required.

ErrorType

authentication, authorization, decryptxError, internalServerError, invalidRequest, methodNotAllowed, notFound, poiError, serviceUnavailable, shieldconexError, timeout, transactionError, websocketGatewayError, unknownDefaultOpenApi.


Enumerations

Wire enums are String raw representable. Matching is case-sensitive against the generated raw value. Unknown values become unknownDefaultOpenApi rather than throwing.

Status

approved, declined, failed, pending, initialized, authorized, saved, refunded, voided, captured, force, credited, unknownDefaultOpenApi.

Used by BluePosGoTransactionDetails.status and PayConex transaction bodies.

AuthMessageEnum

approved, force, partiallyApproved, invalidCardNumber, unknown, declined, ccvDeclined, avsDeclined, invalidTransaction, processingException, timeout, invalidPin, invalidExpiry, suspectedFraud, velocityCheckFailed, captured, pending, unknownDefaultOpenApi.

CardBrand

visa, mastercard, discover, americanExpress, jcb, dinersClub, unknownDefaultOpenApi.

ResponseEntryMode

contact, contactless, nfc, swipe, keyed, fallbackSwipe, unknownDefaultOpenApi.

TenderType

credit, debit, ebt, fsa, unknownDefaultOpenApi.

AVSResponseCode

Single-letter codes d, f, j, m, q, v, x, y, l, w, z, a, b, o, p, k, n, u, r, s, e, c, i, g, plus questionMark, empty, and unknownDefaultOpenApi.

CVV2ResponseCode

m, n, p, s, u, questionMark, empty, unknownDefaultOpenApi.

Currency

usd, unknownDefaultOpenApi.


Validation

OpenAPI constraints are represented as rule types and applied through Validator.

public struct StringRule: Sendable {
    public var minLength: Int?
    public var maxLength: Int?
    public var pattern: String?
}

public struct NumericRule<T>: Sendable where T: Comparable, T: Numeric, T: Sendable {
    public var minimum: T?
    public var exclusiveMinimum: Bool
    public var maximum: T?
    public var exclusiveMaximum: Bool
    public var multipleOf: T?
}

public struct ArrayRule: Sendable {
    public var minItems: Int?
    public var maxItems: Int?
    public var uniqueItems: Bool
}
Validator.validate(_ string:against:) throws(ValidationError<StringValidationErrorKind>) -> String
Validator.validate<T: BinaryInteger>(_ numeric:against:) throws(ValidationError<NumericValidationErrorKind>) -> T
Validator.validate<T: FloatingPoint>(_ numeric:against:) throws(ValidationError<NumericValidationErrorKind>) -> T
Validator.validate(_ array:against:) throws(ValidationError<ArrayValidationErrorKind>) -> [AnyHashable]

ValidationError.kinds is the set of failed checks.

Error kindCases
StringValidationErrorKindminLength, maxLength, pattern
NumericValidationErrorKindminimum, maximum, multipleOf
ArrayValidationErrorKindminItems, maxItems, uniqueItems

JSONValue

Type-erased JSON used by the generator. Cases: string, int, double, bool, array, dictionary, null. Expressible by string, integer, float, boolean, array, dictionary, and nil literals. Subscript by String key or Int index. Accessors: stringValue, intValue, doubleValue, boolValue, arrayValue, dictionaryValue, and isString / isInt / isDouble / isBool / isArray / isDictionary / isNull.

init(_ codable:) throws when converting an arbitrary Codable value.

NullEncodable<Wrapped>

Three-state encoding: encodeNothing (omit), encodeNull (JSON null), encodeValue(Wrapped). Equatable / Hashable / Sendable / Codable when Wrapped is.


Typical flows

Sale

  1. Build a callback URL on the host app’s scheme.
  2. Optionally initialize with basicToken, accountId, and environment.
  3. Build a PaymentRequest with a fresh requestId, Decimal amount, currency, and callback URL.
  4. Call startPayment. For large notes or credentials, pass transport: .automatic() or .pasteboard.
  5. Forward the returning URL to handleCallback(url:).
  6. Switch on PaymentResult. Persist transactionId and approvalCode from the response.

Auth then capture

  1. startPayment with transactionType: .auth.
  2. On .success, keep response.transactionId.
  3. capture with that id and the capture amount as a String.
  4. Success yields approvedAmount and originalTransactionId.

Refund

Full refund needs transactionId and PaymentCredentials. Partial refund also needs a Decimal amount. Both return a single success case or …Failed(code:message:).

Reader maintenance

reboot reports responseCode and readerSerial. clearData must be handled as success vs masked vs cancelled; treat PAN and track data as PCI data.

Failure handling checklist

  • …AppNotInstalled — prompt the user to install the companion app.
  • …InProgress — ignore the second tap or call cancelPending… first.
  • requestIdMismatch — drop the callback; it belongs to an older request.
  • pasteboardHandoffExpired / pasteboardHandoffMissing — retry the payment; do not reuse a stale pasteboard payload.
  • urlPayloadTooLarge — retry with .gzip or .pasteboard.
  • decodingFailed — log the associated string; the list payload did not match BluePosGoTransaction.

See also

Facade types to start from: BluePosGo, PaymentRequest, PaymentResult, InitializationRequest, TransactionListRequest, FullRefundRequest, PartialRefundRequest, CaptureRequest, SaveRequest, ClearDataRequest, RebootRequest.

Processor models to start from: SaleAndAuthRequest, TransactionResponse, AmountsExtended, AuthResponse, BluefinBluePosPoiModelsAPIConfiguration.


Did this page help you?