BluePosGoSDK iOS API Reference
Public Swift interface for the BluePosGoSDK module.
| Module | BluePosGoSDK |
| Language | Swift 6.3 (library evolution, Swift 6 language mode) |
| Platform | iOS 13.0+, arm64, Objective-C interop enabled |
This SDK has two layers:
- App-to-app facade —
BluePosGo.sharedlaunches the BluePos Go companion app and parses the callback URL. Payment payloads can travel by URL scheme, gzip-compressed URL, or pasteboard handoff. - 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
- Integration
- BluePosGo
- Callback handling
- Payments
- Initialization
- Transaction list
- Full refund
- Partial refund
- Capture
- Save card
- Clear data
- Reboot
- Shared value types
- Logging
- PayConex HTTP client
- PayConex models
- Enumerations
- Validation
- Typical flows
Integration
import BluePosGoSDKRegister 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 BluePosGoProcess-wide coordinator. Use the shared instance; do not construct it.
Singleton
@MainActor public static let shared: BluePosGoLogger
@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.
| Property | Operation |
|---|---|
isPaymentInProgress | startPayment |
isInitializationInProgress | initialize |
isTransactionListInProgress | getTransactionList |
isFullRefundInProgress | fullRefund |
isPartialRefundInProgress | partialRefund |
isCaptureInProgress | capture |
isClearDataInProgress | clearData |
isRebootInProgress | reboot |
isSaveInProgress | save |
Operations
| Method | Request | Result |
|---|---|---|
startPayment(request:completion:) | PaymentRequest | PaymentResult |
startPayment(request:transport:completion:) | PaymentRequest + PaymentLaunchTransport | PaymentResult |
initialize(request:completion:) | InitializationRequest | InitializationResult |
getTransactionList(request:completion:) | TransactionListRequest | TransactionListResult |
fullRefund(request:completion:) | FullRefundRequest | FullRefundResult |
partialRefund(request:completion:) | PartialRefundRequest | PartialRefundResult |
capture(request:completion:) | CaptureRequest | CaptureResult |
clearData(request:completion:) | ClearDataRequest | ClearDataResult |
reboot(request:completion:) | RebootRequest | RebootResult |
save(request:completion:) | SaveRequest | SaveResult |
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) -> BoolIdentifies 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) -> BoolInstance 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
PaymentRequestEquatable, Sendable.
| Field | Type | Default | Role |
|---|---|---|---|
requestId | String | — | Correlates the callback. Must be unique per in-flight payment. |
amount | Decimal | — | Transaction amount. |
tip | Decimal? | nil | Optional tip. |
transactionType | PaymentTransactionType | .sale | .sale, .auth, or .save. |
currency | String | — | Currency code supplied by the caller (for example "USD"). |
callbackURL | URL | — | URL the companion app opens on completion. |
customId | String? | nil | Merchant reference echoed on the response when present. |
notes | String? | nil | Free-text note sent with the request. |
credentials | PaymentCredentials? | nil | Optional per-request PayConex credentials. |
requiresReaderReady | Bool | true | Whether 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
PaymentTransactionTypeString raw value, CaseIterable, Sendable.
| Case | Raw value |
|---|---|
sale | "sale" |
auth | "auth" |
save | "save" |
.save on a payment request is distinct from the dedicated save(request:completion:) operation.
PaymentLaunchTransport
PaymentLaunchTransportEquatable, Sendable. Selects how the payment payload is handed to the companion app.
| Case | Meaning |
|---|---|
urlScheme | Payload inline in the launch URL. |
gzip | Payload gzip-compressed into the launch URL. |
pasteboard | Payload 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
PaymentCredentialsCodable, Equatable, Sendable.
| Field | Type |
|---|---|
basicToken | String |
accountId | String |
environment | String |
Also required by FullRefundRequest and PartialRefundRequest. Optional on PaymentRequest, SaveRequest, and (as separate fields) InitializationRequest.
PaymentResponse
PaymentResponseEquatable, Sendable. Attached to every payment result that parsed a callback.
| Field | Type |
|---|---|
callbackURL | URL |
requestId | String? |
status | String? |
processorMessage | String? |
approvalCode | String? |
transactionId | String? |
customId | String? |
PaymentResult
PaymentResultpublic 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
PaymentErrorError, Equatable, Sendable, LocalizedError (errorDescription).
| Case | When |
|---|---|
invalidRequest(String) | Request failed local validation. Associated value is the reason. |
paymentAppNotInstalled | Companion app is not installed. |
paymentInProgress | A payment is already in flight. |
invalidCallback | Callback URL could not be interpreted. |
requestIdMismatch(expected:received:) | Callback requestId does not match. received may be nil. |
missingStatus | Callback had no status. |
paymentFailed(status: String?) | Companion reported a non-success status that is not cancelled or declined. |
pasteboardHandoffUnavailable | Pasteboard transport could not be used. |
pasteboardHandoffMissing | Expected pasteboard payload was absent. |
pasteboardHandoffExpired | Pasteboard payload was stale. |
pasteboardHandoffInvalid | Pasteboard payload failed structural checks. |
pasteboardHandoffDecryptionFailed | Pasteboard payload could not be decrypted. |
urlPayloadTooLarge | Inline URL payload exceeded the transport limit. |
urlPayloadInvalid | Inline URL payload was malformed. |
urlPayloadDecompressionFailed | Gzip 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
InitializationRequest| Field | Type | Default |
|---|---|---|
requestId | String | — |
callbackURL | URL | — |
sourceApplication | String | Bundle.main.bundleIdentifier ?? "unknown" |
basicToken | String? | nil |
accountId | String? | nil |
environment | String? | nil |
basePath | String? | nil |
basePath overrides the companion’s API origin for this initialization. The HTTP client’s own default is https://api.payconex.net.
InitializationResponse
InitializationResponse| Field | Type |
|---|---|
callbackURL | URL |
requestId | String? |
status | String? |
message | String? |
InitializationResult
InitializationResultpublic enum InitializationResult {
case initialized(InitializationResponse)
case failure(InitializationError, response: InitializationResponse?)
public var response: InitializationResponse? { get }
}InitializationError
InitializationError| Case | Meaning |
|---|---|
invalidRequest(String) | Local validation failed. |
initializationAppNotInstalled | Companion app missing. |
initializationInProgress | An initialization is already in flight. |
invalidCallback | Callback could not be parsed. |
requestIdMismatch(expected:received:) | Request id did not match. |
missingStatus | No 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
TransactionListRequest| Field | Type | Default |
|---|---|---|
requestId | String? | nil |
callbackURL | URL | — |
requestId is optional. When supplied, a mismatch is TransactionListError.requestIdMismatch.
TransactionListResponse
TransactionListResponse| Field | Type |
|---|---|
callbackURL | URL |
requestId | String? |
status | String? |
errorCode | String? |
errorMessage | String? |
transactionCount | Int? |
transactions | [BluePosGoTransaction] |
TransactionListResult
TransactionListResultpublic enum TransactionListResult {
case success(TransactionListResponse)
case failure(TransactionListError, response: TransactionListResponse?)
public var response: TransactionListResponse? { get }
}TransactionListError
TransactionListError| Case | Meaning |
|---|---|
invalidRequest(String) | Local validation failed. |
transactionListAppNotInstalled | Companion app missing. |
transactionListInProgress | A list request is already in flight. |
invalidCallback | Callback could not be parsed. |
requestIdMismatch(expected:received:) | Request id did not match. |
missingStatus | No status on the callback. |
missingTransactionList | Status 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
BluePosGoTransactionCodable, Equatable, Identifiable, Sendable. ID is String.
| Member | Type | Notes |
|---|---|---|
amount | Decimal | |
tip | Decimal? | |
type | BluePosGoTransactionType? | |
customId | String? | camelCase field. |
customID | String? | Alternate spelling accepted by the decoder. |
notes | String? | |
transactionDetails | BluePosGoTransactionDetails | |
totalAmount | Decimal | Computed. |
id | String | Computed identity. |
Both customId and customID are stored. Treat them as decode aliases for the same merchant reference and prefer whichever the callback populated.
BluePosGoTransactionDetails
BluePosGoTransactionDetailsCodable, Equatable, Sendable.
| Field | Type |
|---|---|
status | Status? |
description | String? |
transactionId | String? |
timestamp | String? |
approvedAmount | String? |
requestedAmount | String? |
authCode | String? |
processorMessage | String? |
entryMode | ResponseEntryMode? |
cardBrand | CardBrand? |
cardLast4 | String? |
cardLabel | String (computed) |
approvedAmount and requestedAmount are strings, matching the PayConex amount convention. Status, ResponseEntryMode, and CardBrand are the shared OpenAPI enums documented below.
BluePosGoTransactionType
BluePosGoTransactionTypeString 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
FullRefundRequest| Field | Type |
|---|---|
requestId | String |
transactionId | String |
callbackURL | URL |
credentials | PaymentCredentials |
FullRefundResponse
FullRefundResponse| Field | Type |
|---|---|
callbackURL | URL |
requestId | String? |
transactionId | String? |
status | String? |
errorCode | String? |
errorMessage | String? |
FullRefundResult
FullRefundResultpublic 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
FullRefundErrorinvalidRequest(String), fullRefundAppNotInstalled, fullRefundInProgress, invalidCallback, requestIdMismatch(expected:received:), missingStatus, fullRefundFailed(code:message:).
All of these errors conform to LocalizedError.
Partial refund
PartialRefundRequest
PartialRefundRequest| Field | Type |
|---|---|
requestId | String |
transactionId | String |
amount | Decimal |
callbackURL | URL |
credentials | PaymentCredentials |
amount is Decimal here. Capture uses a String amount. Do not interchange them.
PartialRefundResponse
PartialRefundResponseSame shape as FullRefundResponse: callbackURL, requestId, transactionId, status, errorCode, errorMessage.
PartialRefundResult
PartialRefundResultpublic enum PartialRefundResult {
case success(PartialRefundResponse)
case failure(PartialRefundError, response: PartialRefundResponse?)
public var response: PartialRefundResponse? { get }
}PartialRefundError
PartialRefundErrorinvalidRequest(String), partialRefundAppNotInstalled, partialRefundInProgress, invalidCallback, requestIdMismatch(expected:received:), missingStatus, partialRefundFailed(code:message:).
Capture
Captures a prior authorization.
CaptureRequest
CaptureRequest| Field | Type |
|---|---|
requestId | String |
transactionId | String |
amount | String |
callbackURL | URL |
Amount is a string, consistent with PayConex decimal-string amounts. No credentials field on this request.
CaptureResponse
CaptureResponse| Field | Type |
|---|---|
callbackURL | URL |
requestId | String? |
status | String? |
type | String? |
transactionId | String? |
approvedAmount | String? |
originalTransactionId | String? |
errorCode | String? |
errorMessage | String? |
CaptureResult
CaptureResultpublic enum CaptureResult {
case success(CaptureResponse)
case failure(CaptureError, response: CaptureResponse?)
public var response: CaptureResponse? { get }
}CaptureError
CaptureErrorinvalidRequest(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
SaveRequest| Field | Type | Default |
|---|---|---|
requestId | String | — |
callbackURL | URL | — |
currency | String | "USD" |
customId | String? | nil |
notes | String? | nil |
credentials | PaymentCredentials? | nil |
SaveResponse
SaveResponse| Field | Type |
|---|---|
callbackURL | URL |
requestId | String? |
status | String? |
transactionId | String? |
approvalCode | String? |
processorMessage | String? |
entryMode | String? |
cardBrand | String? |
cardLast4 | String? |
errorCode | String? |
errorMessage | String? |
entryMode and cardBrand are plain strings on this response, not the ResponseEntryMode and CardBrand enums used by BluePosGoTransactionDetails.
SaveResult
SaveResultpublic enum SaveResult {
case success(SaveResponse)
case cancelled(SaveResponse)
case declined(SaveResponse)
case failure(SaveError, response: SaveResponse?)
public var response: SaveResponse? { get }
}SaveError
SaveErrorinvalidRequest(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
ClearDataRequest| Field | Type | Default |
|---|---|---|
requestId | String | — |
callbackURL | URL | — |
amount | Decimal? | nil |
timeout | Int? | nil |
ClearDataResponse
ClearDataResponse| Field | Type |
|---|---|
callbackURL | URL |
requestId | String? |
status | String? |
clearPan | String? |
clearTrack2 | String? |
errorCode | String? |
errorMessage | String? |
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
ClearDataResultpublic 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
ClearDataErrorinvalidRequest(String), clearDataAppNotInstalled, clearDataInProgress, invalidCallback, requestIdMismatch(expected:received:), missingStatus, clearDataFailed(code:message:).
Reboot
Reboots the paired reader.
RebootRequest
RebootRequest| Field | Type |
|---|---|
requestId | String |
callbackURL | URL |
RebootResponse
RebootResponse| Field | Type |
|---|---|
callbackURL | URL |
requestId | String? |
status | String? |
responseCode | Int? |
readerSerial | String? |
errorCode | String? |
errorMessage | String? |
RebootResult
RebootResultpublic enum RebootResult {
case success(RebootResponse)
case failure(RebootError, response: RebootResponse?)
public var response: RebootResponse? { get }
}RebootError
RebootErrorinvalidRequest(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 shape | Meaning |
|---|---|
invalidRequest(String) | Caller-side validation. |
…AppNotInstalled | Companion app cannot be opened. |
…InProgress | Same operation already pending. |
invalidCallback | URL was not a well-formed callback. |
requestIdMismatch(expected:received:) | Stale or foreign callback. |
missingStatus | Callback omitted status. |
…Failed(code:message:) | Companion or processor failure. Payment and initialization use paymentFailed(status:) and initializationFailed(status:) instead. |
Amount conventions
| API | Amount type |
|---|---|
PaymentRequest.amount, .tip | Decimal |
PartialRefundRequest.amount | Decimal |
ClearDataRequest.amount | Decimal? |
BluePosGoTransaction.amount, .tip, .totalAmount | Decimal |
CaptureRequest.amount | String |
PayConex Amounts.total and related fields | String |
| Transaction-list detail amounts | String? |
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
BluefinBluePosPoiModelsAPIConfigurationopen class, @unchecked Sendable. Shared instance: BluefinBluePosPoiModelsAPIConfiguration.shared.
| Member | Type | Default |
|---|---|---|
basePath | String | "https://api.payconex.net" |
customHeaders | [String: String] | [:] |
credential | URLCredential? | nil |
requestBuilderFactory | RequestBuilderFactory | URLSessionRequestBuilderFactory() |
apiResponseQueue | DispatchQueue | .main |
codableHelper | CodableHelper | CodableHelper() |
successfulStatusCodeRange | Range<Int> | 200..<300 |
interceptor | OpenAPIInterceptor | DefaultOpenAPIInterceptor() |
Mutate shared before issuing requests, or pass a dedicated configuration into a RequestBuilder.
RequestBuilder<T>
RequestBuilder<T>open class, @unchecked Sendable, Identifiable by ObjectIdentifier. T: Sendable.
| Member | Type |
|---|---|
parameters | [String: any Sendable]? |
method | String |
URLString | String |
requestTask | RequestTask |
requiresAuthentication | Bool |
apiConfiguration | BluefinBluePosPoiModelsAPIConfiguration |
credential | URLCredential? |
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) -> RequestTaskOn Swift 5.3+ with async execution attributes:
@discardableResult
@concurrent func execute() async throws(ErrorResponse) -> Response<T>RequestBuilderFactory
RequestBuilderFactoryprotocol 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
RequestTaskfinal public class RequestTask {
final public func cancel()
}Returned by execute(completion:). Cancel is cooperative at the URLSession task.
Response<T>
Response<T>| Field | Type |
|---|---|
statusCode | Int |
header | [String: String] |
body | T |
bodyData | Data? |
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
HTTPMethodoptions, 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
CodableHelperHolds 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
URLSession seamsURLSessionProtocol 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
SaleAndAuthRequestSale or authorization body.
| Field | Type | Required |
|---|---|---|
timeout | Int? | no |
transactionId | String? | no (transactionIdRule) |
amounts | AmountsExtended | yes |
mmId | Int? | no (mmIdRule) |
description | String? | no |
trace | Trace? | no |
healthcare | Healthcare? | no |
customer | Customer? | no |
shippingAddress | ShippingAddress? | no |
ebt | EBT? | no |
savePayment | Bool? | no |
RefundRequest
RefundRequest| Field | Type |
|---|---|
timeout | Int? |
amounts | Amounts? |
description | String? |
trace | Trace? |
customer | Customer? |
shippingAddress | ShippingAddress? |
CreditRequest
CreditRequest| Field | Type | Required |
|---|---|---|
timeout | Int? | no |
transactionId | String? | no |
mmId | Int? | no |
amounts | Amounts | yes |
description | String? | no |
trace | Trace? | no |
savePayment | Bool? | no |
ForceRequest
ForceRequestForce-post with a prior auth code.
| Field | Type | Required |
|---|---|---|
timeout | Int? | no |
transactionId | String? | no |
mmId | Int? | no |
authCode | String | yes |
amounts | AmountsExtended | yes |
description | String? | no |
trace | Trace? | no |
customer | Customer? | no |
shippingAddress | ShippingAddress? | no |
savePayment | Bool? | no |
CancelRequest / CancelResponse
CancelRequest / CancelResponseCancelRequest.timeout: Int?. CancelResponse.status: String? (statusRule).
ProcessPoiRebootRequest
ProcessPoiRebootRequest| Field | Type |
|---|---|
timeout | Int? |
allowOverride | Bool? |
delayInSeconds | Int? (delayInSecondsRule) |
This is the HTTP reboot body. The facade equivalent is RebootRequest.
Amounts
Amounts
Amounts| Field | Type |
|---|---|
currency | Currency? |
total | String? (totalRule) |
AmountsExtended
AmountsExtended| Field | Type | Required |
|---|---|---|
currency | Currency | yes |
total | String | yes |
gratuity | String? | no |
cashback | String? | no |
AmountsResponse
AmountsResponse| Field | Type | Required |
|---|---|---|
currency | Currency | yes |
approved | String | yes |
requested | String | yes |
gratuity | String? | no |
cashback | String? | no |
surcharge | String? | no |
additionalFee | String? | no |
balance | String? | no |
Currency is .usd or .unknownDefaultOpenApi.
Transaction response
TransactionResponse
TransactionResponse| Field | Type |
|---|---|
status | Status? |
amounts | AmountsResponse? |
customer | Customer? |
description | String? |
shippingAddress | ShippingAddress? |
trace | TraceResponse? |
reference | String? |
bfTokenReference | String? |
transactionId | String? |
shieldConexToken | ShieldConexCardToken? |
card | CardResponse? |
auth | AuthResponse? |
emv | EmvDataResponse? |
binData | BinDataResponse? |
cvm | CVM? |
tenderType | TenderType? |
AuthResponse
AuthResponse| Field | Type | Required |
|---|---|---|
code | String? | no |
message | AuthMessageEnum | yes |
processorMessage | String | yes |
networkName | String? | no |
avsResponseCode | AVSResponseCode? | no |
cvv2ResponseCode | CVV2ResponseCode? | no |
CardResponse
CardResponsename, brand: CardBrand?, bin, last4, expiry. All optional. name, last4, and expiry have string rules.
EmvDataResponse
EmvDataResponseAll optional: aid, appLabel, tvr, tsi, arc, atc, cryptogram, entryMode, contactless: Bool?.
BinDataResponse
BinDataResponseprogram: Program? (standard, unknown, healthcare, fleet, unknownDefaultOpenApi), programCard: ProgramCard? (fsa, hsa, hra, unknownDefaultOpenApi).
CVM
CVMmethod required: signature, offlinePin, onlinePin, noCvmRequired, unknownDefaultOpenApi. signature: String? optional.
ShieldConexCardToken
ShieldConexCardTokenbfid: String required. cardNumber and cardExpiration optional.
ListTransactionResponseInstance
ListTransactionResponseInstanceRow in a processor transaction list (not the facade BluePosGoTransaction).
| Field | Type |
|---|---|
status | Status? |
transactionId | String? |
authMessage | String? |
authCode | String? |
approvedAmount | String? |
transactionType | TransactionType? |
timestamp | Date? |
reference | String? |
cardType | String? |
entryMode | ResponseEntryMode? |
last4 | String? |
bfTokenReference | String? |
Nested TransactionType: sale, authorization, refund, credit, debit, store, force, reversal, balance, void, _init, unknownDefaultOpenApi.
Customer and address
Customer
Customername: String?, email: String?, phone: String?, billingAddress: Address?. name and phone have string rules.
Address
AddressRequired: address1, city, state, zip. Optional: address2, country, company.
ShippingAddress
ShippingAddressRequired: address1, city, state, zip, country, recipient. Optional: address2, company, recipientPhone, recipientEmail.
Trace
Trace (request)
Trace (request)cashier, clientIp, customId, timestamp: Date?, extTransactionId, tags: [String]?. extTransactionId and tags have rules.
TraceResponse
TraceResponseRequest fields plus sourceIp, source, gpsLocation, networkTransactionId, history: [TransactionHistoryRecord]?, clickToPayTraceData.
GpsLocation
GpsLocationlatitude and longitude required strings. accuracy optional.
TransactionHistoryRecord
TransactionHistoryRecordaction: Action? (_init, update, authorization, capture, transaction, refund, unknownDefaultOpenApi), requestId, correlationId, timestamp: Date?.
ClickToPayTraceData
ClickToPayTraceDataRequired: merchantTransactionId, correlationId, srcFlowId.
Healthcare and EBT
Healthcare
HealthcareAll optional strings: totalAmount, prescription, vision, dental, clinical, copay, transit. Each has a string rule.
EBT
EBTtype required: cash, voucher, food, unknownDefaultOpenApi. voucherNumber optional.
Reader, dialog, and receipt
StatusResponse
StatusResponseReader heartbeat. All optional: serial, modelName, osVersion, macAddress, ipAddress, linesPerScreen: Int?, charsPerLine: Int?, appVersion, timestamp: Date?.
ShowDialogRequest
ShowDialogRequesttitle required. Optional: timeout, button1…button4, body, requiresSignature, style: ShowDialogStyle?.
ShowDialogStyle
ShowDialogStylebackgroundColor: String? (backgroundColorRule), textColor (light, light2, dark, dark2), textSize (small, small2, medium, medium2, large, large2).
ShowDialogResponse
ShowDialogResponseselected: String?.
CustomReceiptRequest
CustomReceiptRequestcontent: String required. timeout: Int? optional.
ReceiptResponse
ReceiptResponseoutcome: String?.
ReprintReceiptRequest
ReprintReceiptRequesttransactionId and copy required. copy is customer or merchant. Optional: mmid: Int?, transType (auth, capture, sale, refund, reversal), additionalInfo.
CaptureSignatureResponse
CaptureSignatureResponsesignature: String?.
PoslinkRequest / PoslinkResponse
PoslinkRequest / PoslinkResponsePoslinkRequest.command: String required, timeout optional. PoslinkResponse.response: String?.
Errors from the API
ApiViolation
ApiViolationmessage, traceId: UUID?, errorType: ErrorType?, errorCode: Int?, value, source, details: [ErrorDetail]?.
ErrorDetail
ErrorDetailsource, value, message. All optional.
ModelError
ModelErrorcode: Int, message: String. Both required.
ErrorType
ErrorTypeauthentication, 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
Statusapproved, declined, failed, pending, initialized, authorized, saved, refunded, voided, captured, force, credited, unknownDefaultOpenApi.
Used by BluePosGoTransactionDetails.status and PayConex transaction bodies.
AuthMessageEnum
AuthMessageEnumapproved, force, partiallyApproved, invalidCardNumber, unknown, declined, ccvDeclined, avsDeclined, invalidTransaction, processingException, timeout, invalidPin, invalidExpiry, suspectedFraud, velocityCheckFailed, captured, pending, unknownDefaultOpenApi.
CardBrand
CardBrandvisa, mastercard, discover, americanExpress, jcb, dinersClub, unknownDefaultOpenApi.
ResponseEntryMode
ResponseEntryModecontact, contactless, nfc, swipe, keyed, fallbackSwipe, unknownDefaultOpenApi.
TenderType
TenderTypecredit, debit, ebt, fsa, unknownDefaultOpenApi.
AVSResponseCode
AVSResponseCodeSingle-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
CVV2ResponseCodem, n, p, s, u, questionMark, empty, unknownDefaultOpenApi.
Currency
Currencyusd, 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 kind | Cases |
|---|---|
StringValidationErrorKind | minLength, maxLength, pattern |
NumericValidationErrorKind | minimum, maximum, multipleOf |
ArrayValidationErrorKind | minItems, maxItems, uniqueItems |
JSONValue
JSONValueType-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>
NullEncodable<Wrapped>Three-state encoding: encodeNothing (omit), encodeNull (JSON null), encodeValue(Wrapped). Equatable / Hashable / Sendable / Codable when Wrapped is.
Typical flows
Sale
- Build a callback URL on the host app’s scheme.
- Optionally
initializewithbasicToken,accountId, andenvironment. - Build a
PaymentRequestwith a freshrequestId,Decimalamount, currency, and callback URL. - Call
startPayment. For large notes or credentials, passtransport: .automatic()or.pasteboard. - Forward the returning URL to
handleCallback(url:). - Switch on
PaymentResult. PersisttransactionIdandapprovalCodefrom the response.
Auth then capture
startPaymentwithtransactionType: .auth.- On
.success, keepresponse.transactionId. capturewith that id and the capture amount as aString.- Success yields
approvedAmountandoriginalTransactionId.
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 callcancelPending…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.gzipor.pasteboard.decodingFailed— log the associated string; the list payload did not matchBluePosGoTransaction.
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.
Updated about 1 hour ago
