Интеграция apple pay swift

Integrate Apple Pay with Swift

This walkthrough shows you how to integrate Apple Pay into an existing iOS app. After you integrate with Apple Pay, end users can pay for an order on their iPhones.

If you want to follow along, you need the following items:

  • An Apple Developer account.
  • A Commerce Cloud account with an existing project. At minimum, you need:
    • Configured products
    • Configured payment gateway (manual)

Feel free to skip to the end, and grab the completed example project by clicking the source code links under Further Reading, or follow the step-by-step walkthrough.

  1. Get the code from GitHub.
  2. Set up the iOS app project.
  3. Display a product.
  4. Update your store.
  5. Set up Apple Pay credentials.
  6. Set up an Apple Pay project.
  7. Add an Apple Pay button.
  8. Create an Apple Pay request.
  9. Handle shipping.
  10. Implement Apple Pay delegates.
  11. Create a checkout in Commerce Cloud.
  12. Create payment transactions.

Get the code from GitHub

Then navigate into the new directory, and install the CocoPods:

Set up the iOS app project

Open the workspace project in Xcode, and run to confirm everything is working.

Display a product

The app as it stands is a simple Master/Detail application that shows a list of products from a demo store in the master view. Tap on any product to navigate to a detail view which shows a bigger picture of the swag as well as a more detailed description.

Update your store

Update the store ID in MoltinProductsViewController to use your products:

Set up Apple Pay credentials

  1. Log in to your developer account.
  2. Go to Member Center, and click Certificates, Identifiers & Profilesstrong\Identifiers\App IDs.
  3. Click the + button to create a new App ID.
  4. Name the Apple ID with either your app name or use Apple MoltinProducts, and give it a Bundle ID in the format: com.YOURDOMAIN.MoltinProducts . If you already have a project, substitute the names accordingly.
  5. Make sure that Explicit App ID is selected, as wildcard App IDs aren’t able to make payments with Apple Pay.
  6. Under App Services, enable the Apple Pay checkbox, click Continue, and then click Submit to complete the creation of your new App ID.
  7. Under Identifiers, click Merchant IDs in the left navigation pane.
  8. Click + to create a new merchant ID, and use whatever description and merchant identifier you’d like. Generally, it’s recommended to create merchant identifiers in the reverse domain style that start with merchant , similar to bundle IDs.
  9. Click Continue, and then click Register to create your new merchant ID.

Now that your App ID and merchant ID are set up, head back to Xcode to get your project ready for Apple Pay.

Set up Apple Pay project

  1. Select the MoltinProducts project in the left navigation bar, then select the MoltinProducts target, and change the Bundle Identifier to match the one you created previously.
  2. Ensure that the Team selection box is pointing to the development team under which you created your App ID and merchant ID.
  3. Click the Capabilities tab, expand the Apple Pay section, and ensure that the switch on the right is set to ON.
  4. Push the refresh button below the merchant ID list. You should see the list populates with the merchant ID you added on the developer portal, if it wasn’t there already.
  5. Make sure that your merchant ID checkbox is selected.
Читайте также:  Когда сделали айфон 5se

At this point, you should have checkmarks next to all sections that deal with setting up a project, displaying a product, and setting up Apple Pay credentials. If any of the sections is not marked as checked, retrace your steps and correct the details to make sure you’ve satisfied Apple’s requirements.

You now have Apple Pay enabled in your app.

Add Apple Pay button

Open Main.storyboard and take a look at the Buy Product scene.

Apple has a very specific set of Apple Pay guidelines to adhere to, which extends to the buttons in your app. Take a few minutes to review these guidelines at the Apple Pay developer site.

The Apple Pay Buttons and Resources link at the Apple Pay developer site provides you with a zip file. The file contains an extensive collection of approved button resources for Apple Pay.

You can find a set of Apple Pay images ready for use in the starter project’s Image.xcassets.

Using the Buy Product Interface Builder, select the Apple Pay button, and change the image to ApplePay. Give your button an empty title instead of the default “button” title. Your scene should now look as follows:

Create Apple Pay request

Open BuyProductViewController.swift and add the following import to the top of the file:

Locate applePayPressed(sender:); you execute this when the user attempts to purchase an item. To do this, you’ll need to create a PKPaymentRequest and a PKPaymentAuthorizationViewController .

Locate applePayPressed(sender:); you execute this when the user attempts to purchase an item. To do this, you’ll need to create a PKPaymentRequest and a PKPaymentAuthorizationViewController .

Add the following code to the body of applePayPressed(sender:) :

Add the following code just under the IBOutlet properties of BuySwagViewController :

In the viewDidLoad, check to see if the user can use Apple Pay.

Now start filling out the request in applePayPressed(sender:) , under the let request = PKPaymentRequest() .

Create an array of PKPaymentSummaryItem objects that provide the user with a breakdown the items they’re purchasing. We add more detail to this array in the next step.

Run the app to confirm whether you see Apple Pay when you hit the Apple Pay button on the buy scene.

We add a static billing amount to start. Billing needs are going to differ greatly on what your store is selling.

Implement Apple Pay delegates

In BuyProductViewController.swift , add the following extension to BuyProductViewController that implements PKPaymentAuthorizationViewControllerDelegate :

To be able to use the Apple pay, delegate class you need to set in aboveBuyProductViewController class. In the applePayPressed(sender:) , set it up using the following code.

Create checkout in Commerce Cloud

In BuyProductViewControllerin the PKPaymentAuthorizationViewControllerDelegate , you are sending a successful Apple pay order to Commerce Cloud.

Get customers information. It is returned from the PKPaymentAuthorizationViewControllerDelegate in the payment object.

Set up customer .

Set up the customer address . Note that shipping and billing addresses can vary.

Process an order with Commerce Cloud.

Create payment transactions

Paying for the order can be done by various payment gateways. In this example we use the manual payment type, which allows you to complete the transaction that handles the payment processing any way you want.

In Commerce Manager, enable manual checkout. In Gateways, click Enable within the manual gateway and the click Save.

Within the checkout specified previously, complete the transaction by adding the following:

Your PKPaymentAuthorizationViewControllerDelegate should now look like the following:

Читайте также:  Почему долго синхронизируется айфон с айтюнс

If you’d like to read more in-depth information about Apple Pay, you can check out their developer site. The site also has a list of other payment platforms, other than Stripe, that support Apple Pay.

There are many other features of Apple Pay that you could challenge yourself to add to your app:

  • Calculate sales tax on the server and update the tax amount in summaryItems .
  • Change the available shipping methods based on the ZIP code.
  • Read the order information on the server, and verify that the address is valid as a shipping destination.
  • Create your own customized Apple Pay button by following the Apple Pay guidelines.

Источник

Integrating Apple Pay into your iOS App

Apple Pay is arguably the best form of payment in an iOS app. It’s easy and efficient for both the user and the developer. Long gone are the days of typing in your credit card info — users can now quickly make transactions through ApplePay and your app should support this service.

Note: To implement Apple Pay, you must have an Apple Developer’s Account. Learn more about the developer’s program .

Let’s Get Started

First, download the starter project here. Take a look at this project, in the ViewController.swift file, we have the Shoe struct:

We’ll use this along with the array of Shoes to populate our picker view and retrieve the price later on (feel free to change the shoes if you’d like to).

To get started with Apple Pay, we need to create a merchant ID in the developer portal. This ID will allow Apple to identify your app as a “merchant” for purchases. Before we create one, you’ll need a unique bundle identifier for your app. In the app settings, go to the identity and put your own bundle identifier as you would if you were making your own app (e.g. com.yourname.app-name).

Next, head over to the developer member center and select “Certificates, Identifiers, and Profiles” in the menu. Select “Merchant IDs” from the left menu. Tap the plus “+” on the top right-hand corner.

In the description, enter the name of your app, such as “Shoe Store”. In the identifier, type “merchant.” + your bundle identifier. For me, that would be “merchant.com.pranavwadhwa.Shoe-Store”. Tap “Continue” and then “Register”.

For the next part, we’re going to need a certificate signing request (CSR). Open up Keychain Access, and from the top menu select “Certificate Assistance” and “Request a Certificate from a Certificate Authority” as shown in the picture.

Put your email address in the “User Email Address” field and select the “saved to disk” option for your request (you can leave the CA email address empty).

We’re almost back to coding! We just need to create a payment processing certificate, which will be used to secure transaction data . Go back to the member center and select “All Certificates” from the side menu. Tap the plus “+” button on the top right corner to create a new certificate.

Under “Production”, select “Apple Pay Payment Processing Certificate”.

Then, select the merchant ID you created earlier. Next, under “Apple Pay Payment Processing Certificate”, tap on “Create Certificate”. Apple will ask, “Will payments associated with this Merchant ID be processed exclusively in China?” Select yes. Continue through the process, and it will ask you to upload your CSR that you saved from Keychain Access.

Great job! You created your certificate. Download it and save it with your project. Then, double click on it, and it will be processed in Keychain Access.

Читайте также:  Аккумулятор 83 процента айфон 8 выключается

Let’s head back over to Xcode and enable Apple Pay there. Under “Capabilities”, turn on Apple Pay, and ensure that you have selected the correct merchant ID (If you don’t see yours, try tapping the + and enter the name of your merchant ID).

Time to Start Coding

Open the ViewController.swift file, and inside the class, add the following function:

If you’ve used alerts in the past, you’ll know that this will simply display an alert with a simple dismiss action. We’ll use this to display info to the user as they go through the Apple Pay process. Now, go to the buyShoeTapped method:

First, let’s find the current shoe that the user has picked and create a PKPaymentSummaryItem using that info. Add the following lines:

This will find the selected row in the picker (as we only have one component), get the corresponding shoe, and create a payment item using that information. We will use this item when filling out the payment request. Next, we have to declare a list of methods the user can pay with. In order to do that, we have to add

at the top of the file. Now, back in our buyShoeTapped function, let’s identify our payment methods:

With this, we have to check if the user can make payments with one of these networks and let them know if they can’t:

Now, we’re going to create a PKPaymentRequest that will contain information about the transaction. Add the following:

Let’s take a close look at this.

Lines 1 and 2 establish the currency and country code — you can change these to fit your app.

Line 3 verifies your merchant ID. Make sure to change line 3 and input the name of the merchant ID you created.

Line 4 checks the type of transaction. PKMerchantCapability.capability3DS uses the 3-D Secure protocol, a secure way of processing debit and credit cards.

Lastly, lines 5 and 6 use the payment networks and the payment item we created earlier. This is only the basic information; you can add more information in the request, such as the billing information, shipping methods, and supported countries. Check the full list of properties of the PKPaymentRequest. if needed.

Finally, let’s present the View Controller to the user.

You’ll see an error — don’t panic, we’ll fix it soon. Here, we’re using a guard statement to safely unwrap the PKPaymentAuthorizationViewController , and displaying it accordingly. The error we’re facing is that we assigned the paymentVC ’ s delegate to the ViewController , but the ViewController does not currently conform to that protocol. Let’s fix that. Below the class, let’s create an extension:

We’re almost done! We just need to add these two functions. In the first one, paymentAuthorizationViewControllerDidFinish , add the following:

This will dismiss the payment view controller after it’s done. In the second function, didAuthorizePayment , add the following to dismiss the view controller (if it hasn’t already been dismissed by the didFinish function) and display a success message to the user:

We’re finished! Run the app, and you’ll see the payment view controller.

Unfortunately, it won’t actually make the transaction yet as we haven’t added a backend to receive the payment. If you want to add that backend, look into backing Apple Pay with Stripe.

Источник

Оцените статью