Applies to: Mobile Payments SDK - iOS | Payments API | Orders API
Learn how to use the Mobile Payments SDK for iOS to take a payment with a Square Reader or Square Stand.
Applies to: Mobile Payments SDK - iOS | Payments API | Orders API
Learn how to use the Mobile Payments SDK for iOS to take a payment with a Square Reader or Square Stand.
Payments in the Mobile Payments SDK are handled by the PaymentManager
and must conform to the PaymentManagerDelegate
protocol. The PaymentManagerDelegate
is called when a payment starts and finishes successfully, fails, or is canceled. Your application should include logic to handle each of these scenarios. To learn about error messages produced by the Mobile Payments SDK and ways to resolve them, see Handling Errors. If the payment completes successfully, a Payment
object is returned, describing details of the payment.
extension <#YourViewController#>: PaymentManagerDelegate {
func paymentManager(_ paymentManager: PaymentManager, didFinish payment: Payment) {
// You can further inspect each payment once cast
if let onlinePayment = payment as? OnlinePayment {
print("Online Payment - ID: \(onlinePayment.id!), status: \(onlinePayment.status.description)")
} else if let offlinePayment = payment as? OfflinePayment {
print("Offline Payment - ID: \(offlinePayment.localID), status: \(offlinePayment.status.description)")
}
}
func paymentManager(_ paymentManager: PaymentManager, didFail payment: Payment, withError error: Error) {
// Handle this the same way as `didFinish`
}
func paymentManager(_ paymentManager: PaymentManager, didCancel payment: Payment) {
// Handle this the same way as `didFinish`
}
}
Before taking a payment with the SDK in a production environment, ensure that you've done the following:
To begin a payment with the Mobile Payments SDK, you create a PaymentParameters
object, which includes the payment amount, idempotency key, optional tip, application fee (if applicable), and the processing mode, which is used if you want to take payments while offline. For the complete list of payment parameter values and details, see the iOS technical reference.
The PaymentParameters
must also include an idempotency key. An idempotency key is a unique string identifier that accompanies an API operation, allowing Square to recognize potential duplicate calls. Using an idempotency key ensures that an operation can only occur once, protecting against unintended outcomes like charging a customer twice for the same transaction.
If a payment creation request doesn't receive a response due to network failure or any other error, you might be unsure whether the payment was processed. By providing a unique idempotency key in your PaymentParameters
, you can recover by using that idempotency key in a call to CancelPaymentByIdempotencyKey to cancel an incomplete payment and continue with a new payment using a new idempotency key.
The Mobile Payments SDK requires that you create and manage idempotency keys for each payment created with your application. An idempotency key can be any unique string value. Don't reuse an idempotency key for a new payment. Doing so results in an error.
Along with an idempotency key, include a unique referenceID
value in your PaymentParameters
for each payment. This persists with the payment and can be used to identify the payment if you need to reference it later. You shouldn't use the referenceId
as the idempotency key, because sometimes a payment requires multiple attempts (for example, when the first attempt is declined for expiration or insufficient funds or for any other reason).
If you don't receive a server response from a payment made with the Mobile Payments SDK, you should check the status of the payment to determine whether to retry. Use the ListPayments endpoint and query by location ID, total payment amount, or other fields to filter the list. You can use your unique referenceID
to identify the correct payment and check its status. You might need to retry the payment with a new idempotency key if the prior payment exists, but cannot be completed.
The following is an example of payment parameters created for a payment of $1 USD. The parameters include a unique idempotencyKey
, referenceID
for that key, and an optional orderID
that allows you to associate a payment with an itemized Square order.
import UIKit
import SquareMobilePaymentsSDK
extension <#YourViewController#> {
func makePaymentParameters() -> PaymentParameters {
let amount = Money(amount: 100, currency: .USD)
// This is your own, reference ID that will be referenced by Square
let referenceID = "MY_REFERENCE_ID_1234"
// `idempotencyKeyStorage` is a simple key-value store that is persisted to
// disk and associates a unique idempotency key with your reference ID.
let idempotencyKey = idempotencyKeyStorage.get(id: referenceID) ?? {
let newKey = UUID().uuidString
idempotencyKeyStorage.store(id: referenceID, idempotencyKey: newKey)
return newKey
}()
// Create the payment parameters
let paymentParams = PaymentParameters(
idempotencyKey: idempotencyKey,
amountMoney: amount
)
// An optional note to add to the payment.
paymentParams.note = "My Note"
// Optional parameter to associate this payment with a previously created Square order.
paymentParams.orderID = "CAISENgvlJ6jLWAzERDzjyHVybY"
// A user-defined ID to associate with the payment. You can use this field
// to associate the payment to an entity in an external system.
paymentParams.referenceID = referenceID
return paymentParams
}
}
Each payment must also have a set of PromptParameters
configured. The PromptParameters
contain a promptMode
and a set of AdditionalPaymentMethods
. PromptParameters.mode
determines whether your application uses the default
Square-provided payment prompt UI or a custom payment prompt where you build your own UI. The default UI provided by Square is presented on top of the viewController
passed to PaymentManager.startPayment
and presents buyers with the payment options available from PaymentManager.availableCardInputMethods
.
PromptParameters.additionalMethods
specifies a set of additional payment methods available to use for this payment. The current option is keyed
(a manually entered credit card payment). When used with the default
promptMode
, the Square payment prompt includes these alternative payment methods as options presented to buyers. If you create your own custom
promptMode
, you should use the additionalPaymentMethods
available from the PaymentHandle
to render these options for buyers in your own payment prompt UI.
To begin processing a payment, call PaymentManager.startPayment()
with the PaymentParameters
and PromptParameters
you previously created. During the payment, Square takes control of the screen display to ensure that buyer information is handled securely and that the final confirmation of the payment is correctly shown to the buyer. You must conform to the PaymentManagerDelegate
to handle results and errors from the payment flow.
When the payment begins, the Payment Manager provides a PaymentHandle
as a way for you to interact with the ongoing payment (for example, if you need to cancel the payment). When the payment completes, regardless of whether it completed successfully, control is returned to the user interface and your application is notified of the result using PaymentManagerDelegate
. Your application can display receipt or error information to the user and continue other processing.
Only one payment can be in process at a given moment. If you make a second call to startPayment
before the first has completed, triggering the PaymentManagerDelegate
, the second call fails immediately with a paymentAlreadyInProgress
error. The first payment call continues.
import SquareMobilePaymentsSDK
class <#YourViewController#>: UIViewController {
private var paymentHandle: PaymentHandle?
func startPayment() {
paymentHandle = MobilePaymentsSDK.shared.paymentManager.startPayment(
makePaymentParameters(),
promptParameters: PromptParameters(
mode: .default,
additionalMethods: .all
),
from: self,
delegate: self
)
}
func makePaymentParameters() -> PaymentParameters {
PaymentParameters(
idempotencyKey: UUID().uuidString,
amountMoney: Money(amount: 100, currency: .USD)
)
}
}
As part of your application's workflow, you might want to authorize a customer's transaction but delay the capture of the payment (the transfer of funds from customer to seller) for a period of time. For example, in a restaurant with a kiosk ordering system, you might want to authorize a customer's credit card when they order, but not complete the payment until they receive their food.
While creating PaymentParameters
for a payment, set the autocomplete
value to false
if you want to delay the capture of a payment. By default, autocomplete
is true
, meaning the payment is authorized and captured immediately.
By default, card reader payments that don't autocomplete are canceled after 36 hours and manually entered credit card payments are canceled after 7 days. While the payment is delayed, use the Payments API to complete or cancel the payment. You can also update the payment to add a tip using the tip_money
parameter.
For more information about delayed payment capture using the Payments API, see Delayed Capture of a Card Payment.
The PaymentHandle
provided by the Mobile Payments SDK during a payment can be used to cancel that payment. Note that only a payment where autocomplete
is set to false
can be canceled during processing. You can first check the value of PaymentHandle.isPaymentCancelable
. If it's set to true
, the payment can be canceled by calling paymentHandle.cancelPayment()
. For example, if your code dismisses the view controller passed to PaymentManager.startPayment
and the payment was not successful, you must call cancelPayment
.
During any payment flow, if the application is sent to the background of the device or the application activity is interrupted, the payment in progress is canceled.
Your application must provide buyers with the option to receive a digital or printed receipt. These receipts aren't sent directly by Square. Therefore, to remain compliant with EMV-certification requirements, you must generate receipts including the following fields from the payment response cardDetails
object, when available:
cardholderName
(example: James Smith)brand
and last4digits
(example: Visa 0094)authorizationCode
(example: Authorization 262921)emvApplicationName
(example: AMERICAN EXPRESS)emvApplicationId
(example: AID: A0 00 00 00 25 01 09 01)entryMethod
(example: Contactless)If you need more assistance, contact Developer and App Marketplace Support or ask for help in the Developer Forums.