Play turn Apple bring your own payment

Source: Internet
Author: User

When you decide to buy something online, there may be a feeling of modern anxiety coming up. There is no precise word to express this anxiety, but if you want to simply describe it, it can be: "Where is my credit card?" What's the number of it? Do I really need to buy this thing? ”

This maddening feeling is magnified when you're shopping on an iOS device: You're probably not carrying your credit card with you, and you're going to have to enter information on your phone with a credit card in your hand. This is a very difficult operation, and I think it should be left to gymnasts and astronauts to demonstrate their skill (I'm joking, of course.) , but I would also like to bet that Apple has already done it in a lab.

If you are a developer and your app accepts credit card payments, this negative factor will directly affect your income.

Apple pay has changed all this. While many offline stores focus most of their attention on physical payments (such as customers can use their iphone to pay for NFC-enabled terminals), iOS developers also have an excellent opportunity to improve the payment experience in their apps.

提醒:如果你在你的APP中销售的是电子产品或者虚拟货币,你应该使用内购方式而不是App Pay去销售你的东西(见的App Store Review Guidelines 11.2节)。你可以使用Apple Pay销售你的实体商品和服务。
Get Apple Merchant ID (Merchant ID)

Before doing any tests, you must first register an Apple merchant ID. And before you do this, you need to choose a payment provider to handle your credit card process. Apple has provided a list of recommended companies on their Apple Pay developer page (Note: I work for Stripe and this company is one of the recommended lists, but the code in this article does not depend on any particular vendor you choose). Your provider should have a detailed guide to tell you how to set up and use Apple Pay on their platform, and the whole process will look like this:

1.前往苹果开发者中心的Certificates, Identifiers, and Profiles部分并且创建一个新的商家ID。2.接下来,前往选择证书菜单,并创建一个新的苹果支付证书。这需要向苹果公司上传证书签名请求(CSR)。当你注册一个支付处理,他们通常会为你提供一个CSR使用。你可以使用CSR通过这个指导生成自己私有的证书,但你的付款处理程序将无法解密它,你需要在以后重新生成。3.在Xcode中,打开你的项目设置中的“Capabilities”部分,然后将“Apple Pay”选项打开。你可能需要从提供的列表中选择之前创建的商家ID。
Create first trade

Apple Pay only supports iOS devices that can use Apple Pay (such as Iphone6/6+,ipad Mini 3,ipad Air 2). In addition, you'll need to add an Apple payment authorization before you can test it in your app (described in "Get Apple Merchant ID"). If you want to simulate its behavior on a simulator, you can find a test library on GitHub that mimics its functionality (testing the details of the credit card).

Once you have your merchant account ready, it's easy to start using Apple Pay. When your verification times out, you first need to see if your running device supports Apple Pay, and then see if your customer has added the credit card to Passbook:

let paymentNetworks = [PKPaymentNetworkAmex, PKPaymentNetworkMasterCard, PKPaymentNetworkVisa]if PKPaymentAuthorizationViewController.canMakePaymentsUsingNetworks(paymentNetworks) {    // ?Pay is available!else {    // Show your own credit card form.}

Assuming that Apple Pay is available, the next step is to call pkpaymentrequest. It is a description of the fees you request from your customers. If your payment request takes place in the United States, here you need to set some default options that you don't need to change in the future:

letrequest = PKPaymentRequest()request.supportedNetworks = [PKPaymentNetworkAmex, PKPaymentNetworkMasterCard, PKPaymentNetworkVisa]request"US"request"USD"request"#Replace me with your Apple Merchant ID#"request.merchantCapabilities = .Capability3DS

Next, use the Paymentsummaryitem property to describe what the user is actually buying. This requires an array of pkpaymentsummaryitem that consists of a number of tags and numbers. They are similar to the line items on the receipt (this is what we can see right away).

let  wax = Pkpaymentsummaryitem (Label:  "mustache Wax" , Amount:nsdecimalnumber (string : " 10.00 ")) let  Discount = pkpaymentsummaryitem (Label:  "discount" , Amount:nsdecimalnumber (string :  " -1.00" ) let  TotalAmount = wax.amount.decimalNumberByAdding (discount.amount). Decimalnumberbyadding ( Shipping.amount) let  total = pkpaymentsummaryitem (Label:  "Nshipster" , Amount:totalamount) request . Paymentsummaryitems = [Wax, discount, shipping, total]  

Please note that you can specify a 0 or negative price to use as a coupon or other information. However, the aggregate requirement must be greater than 0. You will notice that we use the Pkshippingmethod method (inherited from Pkpaymentsummaryitem) to describe our shipping methods. We will explain in more detail below.

Next, we'll combine pkpaymentrequest to create a pkpaymentauthorizationviewcontroller example to show the customer the payment list (in this case, All of this code is hidden in the uiviewcontroller behind the payment.

let viewController = PKPaymentAuthorizationViewController(paymentRequest: request)viewController.delegateselftruenil)

Some areas to note:

1.视图控制器不完全占据屏幕(在这种情况下,蓝色的背景是我们应用程序的一部分)。你可以通过更新后台视图控制器让PKPaymentAuthorizationViewController可见。2.所有的文本自动大写。3.把最后一行从剩余部分分离出来的目的是显示你的总收入。标签将自动在前面加上“PAY”,所以这里通常使用公司名称。4.整个UI是通过Remote View Controller来展现的。这意味着,在你给的PKPaymentRequest之外,以其他的方式展现或修改这个视图的内容是不可能的。
PKPaymentAuthorizationViewControllerDelegate实际上为了处理由PKPaymentAuthorizationViewController返回的付款信息,您需要实现PKPaymentAuthorizationViewControllerDelegate这个协议。它有两个必须实现的方法,分别如下:-(void)paymentAuthorizationViewController:didAuthorizePayment:completion:-(void)paymentAuthorizationViewControllerDidFinish:

To understand how these methods work, we need to look at how an Apple Pay transaction works:

1.写一个如上所述的PKPaymentAuthorizationViewController。2.客户同意使用Touch ID购买(或者在失败了3次之后通过输入自己的密码购买)。3.指纹图标变成一个带有“Processing”的旋转标签4.你的代理将接收paymentAuthorizationViewController:didAuthorizePayment:completion: callback回调。5.你的应用程序与付款进程进行异步通信,网站后台实际上是对这些付款细节的代办。一旦付款结束,你根据返回的结果调用PKPaymentAuthorizationStatus.Success或PKPaymentAuthorizationStatus.Failure以完成处理。6.把PKPaymentAuthorizationViewController旋转动画到成功或失败图标。如果成功的话,用户将会收到一个从PassBook发出的表明从用户信用卡消费的通知。7.你的代理会接收paymentAuthorizationViewControllerDidFinish:方法的回调。它是负责调用用来切换支付页面的dismissViewControllerAnimated:这个方法的。

// MARK:-Pkpaymentauthorizationviewcontrollerdelegatefunc Paymentauthorizationviewcontroller(controller:pkpaymentauthorizationviewcontroller!, Didauthorizepayment payment:pkpayment!, Completion: (( Pkpaymentauthorizationstatus, Void)!){    // Use your Payment Processor‘s SDK  to Finish Charging your Customer. // when  This  is  Done,Pager Completion(pkpaymentauthorizationstatus.success)}func Paymentauthorizationviewcontrollerdidfinish(controller:pkpaymentauthorizationviewcontroller!){dismissviewcontrolleranimated(true, Completion:nil)}

Here, Processpayment:payment completion: This method is your own code and will use the SDK in your payment handler to complete the transaction.

Dynamic Shipping methods and prices

If your customers use Apple Pay to buy physical items, you may want to provide them with different shipping options. You can do this in Pkpaymentrequest this method to set the Shippingmethods option. You can then execute the optional method Paymentauthorizationviewcontroller in the Pkpaymentauthorizationviewcontrollerdelegate agent: Didselectshippingmethod:completion: Responds to the user's choice. This method follows the pattern described by the Didauthorizepayment method above, where you can update the Pkpaymentsummaryitem array with this asynchronous callback, which contains the shipping methods required by the customer. (Remember the Pkshippingmethod method that inherits from Pkpaymentsummaryitem?) It's very useful here! )

Here is a modified version of our previous example, implemented as a computed property for view controllers and auxiliary functions:

var paymentrequest: pkpaymentrequest { LetRequest = ...//Initialize as before LetFreeshipping = Pkshippingmethod (label:"Free Shipping",Amount: Nsdecimalnumber (string:"0")) Freeshipping.identifier ="Freeshipping"Freeshipping.detail ="arrives in 6-8 weeks"     Letexpressshipping = Pkshippingmethod (label:"Express Shipping",Amount: Nsdecimalnumber (string:"10.00")) Expressshipping.identifier ="Expressshipping"Expressshipping.detail ="arrives in 2-3 days"Request.shippingmethods = [Freeshipping, expressshipping] Request.paymentsummaryitems = Paymentsummaryitemsforshippingmethod (freeshipping)returnRequest}func Paymentsummaryitemsforshippingmethod (shipping:pkshippingmethod) ([Pkpaymentsummaryitem]) { LetWax = Pkpaymentsummaryitem (label:"Mustache Wax",Amount: Nsdecimalnumber (string:"10.00")) LetDiscount = Pkpaymentsummaryitem (label:"Discount",Amount: Nsdecimalnumber (string:" -1.00")) LetTotalAmount = wax.amount.decimalNumberByAdding (discount.amount). Decimalnumberbyadding (ship Ping.amount) LetTotal = Pkpaymentsummaryitem (label:"Nshipster",Amount: TotalAmount)return[Wax, discount, shipping, total]}// MARK:-Pkpaymentauthorizationviewcontrollerdelegatefunc Paymentauthorizationviewcontroller (controller:pkpaymentauthorizationviewcontroller!, Didselectshippingmethod ShippingMethod: pkshippingmethod!, Completion: ((Pkpaymentauthorizationstatus, [anyobject]!)-Void)!) { completion(pkpaymentauthorizationstatus.success, Paymentsummaryitemsforshippingmethod ( ShippingMethod))}

In this example, the customer will choose to free delivery or courier, as they choose to change, the price will be adjusted accordingly.

Don't worry, there's more behind!

Instead of offering some fixed-rate shipping options, you can let users choose their own shipping address and dynamically calculate shipping charges based on them. To achieve this goal, first you need to set the required Requiredshippingaddressfields attribute in your Pkpaymentrequest method. This can be any combination of email, phone number, and address.

In addition, this is a good way to do this if you do not need a user's detailed mailing address but need to collect some contact information (such as sending the email address of the receipt).

When the shipping Address field is set, a new "shipping address" appears in the payment user interface to allow the customer to select the previously saved address. Each time the user chooses, paymentAuthorizationViewController:didSelectShippingAddress:completion: Send the message to your pkpaymentauthorizationviewcontrollerdelegate agent.

Here, you should calculate the appropriate cost for the selected address, and then call the completion callback with 3 parameters:

The result of the callback

1.如果成功调用PKPaymentAuthorizationStatus.Success2.如果出现连接错误调用PKPaymentAuthorizationStatus.Failure3.如果API返回一个空的数组调用InvalidShippingPostalAddress (即该收货地址是不可用的)4.数组PKShippingMethods代表用户可用的收货地址。5.新数组PKPaymentSummaryItems包含一个送货方法。

I've built a very simple Web backend to query the Easypost API for a given address freight. Source Access.
Here is a function to query this API, using the Alamofire:

Import Addressbookimport passkitimport alamofirefunc Addressesforrecord (Record:abrecord)[[string:string]]{var addresses:[[string:string]]= [] Let Values:abmultivalue = Abrecordcopyvalue (record, Kabpersonaddressproperty). Takeretainedvalue () forIndexinch 0.. Void) {Let parameters = ["Street": Address[kabpersonaddressstreetkey]??"","City": Address[kabpersonaddresscitykey]??"","State": Address[kabpersonaddressstatekey]??"","Zip": Address[kabpersonaddresszipkey]??"","Country": Address[kabpersonaddresscountrykey]??""] Alamofire.request (. GET,"http://example.com", parameters:parameters). Responsejson {(_, _, JSON, _)inch                ifLet rates = JSON as?[[string:string]]{Let Shippingmethods = map (rates) {(rate), PkshippingmethodinchLet identifier = rate["id"] Let carrier = rate["Carrier"] ??"Unknown Carrier"Let service = rate["Service"] ??"Unknown Service"Let amount = Nsdecimalnumber (string: rate["Amount"]) Let arrival = rate["Formatted_arrival_date"] ??"Unknown Arrival"Let ShippingMethod = Pkshippingmethod (Label:"\ (carrier) \ (service)", amount:amount) Shippingmethod.identifier = identifier Shippingmethod.deta Il = arrivalreturnShippingMethod}}}}

With this, you can simply implement pkpaymentauthorizationviewcontrollerdelegate this agent:

Func Paymentauthorizationviewcontroller(controller:pkpaymentauthorizationviewcontroller!, didselectshippingaddress record:abrecord!, Completion: (( Pkpaymentauthorizationstatus, [anyobject]!, [anyobject]!] Void)!){if  Let Address=Addressesforrecord(record). First{fetchshippingmethodsforaddress(address){(shippingmethods) inch            Switch Shippingmethods?.Count{ Case.None:Completion(pkpaymentauthorizationstatus.failure, nil, nil)             Case.Some(0):Completion(pkpaymentauthorizationstatus.invalidshippingpostaladdress, nil, nil)            default:Completion(pkpaymentauthorizationstatus.success, Shippingmethods, Self.paymentsummaryitemsforshippingmethod ( Shippingmethods!. first!))}        }    }Else{Completion(pkpaymentauthorizationstatus.failure, nil, nil)}}

Now, users can choose the delivery address and method according to their residence address. Their final choice of shippingaddress and ShippingMethod will be in paymentAuthorizationViewController:didAuthorizePayment:completion: method as the Pkpayment property.

All source code in this article is published in Https://github.com/jflinter/ApplePayExample.

Although Apple Pay only exposes a small amount of APIs, it is available in a wide range of applications, and you can customize the appropriate checkout process in your app. It even allows you to create new processes, such as allowing users to buy things without having to create an account.

As more and more apps start using Apple Pay (and more and more people have devices that support it), I believe it will be a very common payment method in iOS apps.

What technical questions can I add:

Play turn Apple bring your own payment

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.