首页 > 代码库 > iOS Apple Pay
iOS Apple Pay
iOS 苹果支付
需要证书支持支付功能
targets 打开支付功能按钮
//ApplePay
#import <PassKit/PassKit.h> //用户绑定的银行卡信息
#import <PassKit/PKPaymentAuthorizationViewController.h> //Apple Pay的展示控件
#import <AddressBook/AddressBook.h> //用户联系信息相关
PKPaymentAuthorizationViewControllerDelegate
注意:设置苹果支付不能自定义按钮,需要使用苹果提供的支付样式!
- (void)setUpApplePayBtn {
//按钮类型
// PKPaymentButtonTypePlain = 0, //默认大小是{140, 30} 显示 -- ?Pay?
// PKPaymentButtonTypeBuy, //默认大小是{140, 30} 显示 -- 支付方式 ?Pay
// PKPaymentButtonTypeSetUp //默认大小是{140, 30} 显示 -- 设置 ?Pay
//按钮风格
// PKPaymentButtonStyleWhite = 0, //白色背景, 无边框
// PKPaymentButtonStyleWhiteOutline, //白色背景, 黑色边框
// PKPaymentButtonStyleBlack //黑色背景, 无边框
PKPaymentButton * payBtn = [PKPaymentButton buttonWithType:PKPaymentButtonTypeBuy style:PKPaymentButtonStyleWhiteOutline];
payBtn.center = self.view.center;
[payBtn addTarget:self action:@selector(handlePayBtn:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:payBtn];
PKPaymentButton * setUpPayBtn = [PKPaymentButton buttonWithType:PKPaymentButtonTypeSetUp style:PKPaymentButtonStyleWhiteOutline];
setUpPayBtn.center = self.view.center;
setUpPayBtn.top = self.view.height / 3.0;
[setUpPayBtn addTarget:self action:@selector(setUpAddApplePayIDCart:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:setUpPayBtn];
}
//进入苹果钱包设置界面
- (void)handlePayBtn:(PKPaymentButton *)sender {
NSLog(@"-=-=-=-=-=-=-=-==-=-==%@", NSStringFromCGRect(sender.frame));
[self setUpApplePay];
}
//进入设置,添加银行卡界面
- (void)setUpAddApplePayIDCart:(PKPaymentButton *)sender {
PKPassLibrary * passLibrary = [[PKPassLibrary alloc] init];
[passLibrary openPaymentSetup];
// [self dataSource];
}
//判断是否能够使用applePay
- (void)setUpApplePay {
//设备ApplePay权限检测
if (![PKPaymentAuthorizationViewController class]) {
//PKPaymentAuthorizationViewController需iOS8.0以上支持
NSLog(@"-=-=-=-=-=-=-=-==-=-==%@", @"操作系统不支持ApplePay,请升级至iOS9.0以上版本,且iPhone6以上设备才支持");
return;
}
//检查当前设备是否可以支付
if (![PKPaymentAuthorizationViewController canMakePayments]) {
//支付需iOS9.0以上支持
NSLog(@"-=-=-=-=-=-=-=-==-=-==%@", @"设备不支持ApplePay,请升级至9.0以上版本,且iPhone6以上设备才支持");
return;
}
//检查用户是否可进行某种卡的支付,是否支持Amex,MasterCard,Visa与银联四种卡,根据自己项目的需要进行检测
NSArray * supportedNetworks = @[PKPaymentNetworkAmex, PKPaymentNetworkMasterCard, PKPaymentNetworkVisa, PKPaymentNetworkChinaUnionPay];
if (![PKPaymentAuthorizationViewController canMakePaymentsUsingNetworks:supportedNetworks]) {
NSLog(@"-=-=-=-=-=-=-=-==-=-==%@", @"没有绑定卡");
return;
}
[self setUpApplePayRequest:supportedNetworks];
}
//配置支付信息
- (void)setUpApplePayRequest:(NSArray *)supportedNetworks {
//初始化PKPaymentRequest - 注音:RMB的币种代码是CNY
//设置币种,国家码及merchant标识符等基本信息
PKPaymentRequest * payRequest = [[PKPaymentRequest alloc] init];
payRequest.countryCode = @"CN"; //国家代码
payRequest.currencyCode = @"CNY"; //RMB的币种代码
payRequest.merchantIdentifier = @"merchant.POPOLOOKApplePay"; //申请的merchantID
payRequest.supportedNetworks = supportedNetworks; //用户可进行支付的银行卡
//设置支持的交易处理协议,3DS必须支持,EMV为可选,目前国内的话还是还是使用两者吧
payRequest.merchantCapabilities = PKMerchantCapability3DS | PKMerchantCapabilityEMV;
//设置发票送信息和货物配送地址信息,用户设置后可以通过代理回调代理获取信息的更新
payRequest.requiredBillingAddressFields = PKAddressFieldEmail;
//如果需要邮寄账单可以选择进行设置,默认PKAddressFieldNone(不邮寄账单)
//账单邮寄地址可以事先让用户选择是否需要,提高体验度
payRequest.requiredShippingAddressFields = PKAddressFieldPostalAddress | PKAddressFieldPhone | PKAddressFieldName;
//送货地址信息,这里设置需要地址和联系方式和姓名,如果需要进行设置,默认PKAddressFieldNone(没有送货地址)
//存储额外信息,使用applicationData属性来存储一些在你的应用中关于这次支付请求的唯一标识信息,比如一个购物车的标识符,在用户授权支付之后,这个属性的哈希值会出现在这次的token中
[self setUpApplePayShippingMethods:payRequest];
}
//配置配送方式 - 不必须
- (void)setUpApplePayShippingMethods:(PKPaymentRequest *)payRequest {
//设置两种配送方式
PKShippingMethod * freeShipping = [PKShippingMethod summaryItemWithLabel:@"包邮" amount:[NSDecimalNumber zero]];
freeShipping.identifier = @"freeShipping";
freeShipping.detail = @"6-8 天 送达";
PKShippingMethod * expressShipping = [PKShippingMethod summaryItemWithLabel:@"急速送达" amount:[NSDecimalNumber decimalNumberWithString:@"10.00"]];
expressShipping.identifier = @"expressShipping";
expressShipping.detail = @"1-2 天 送达";
payRequest.shippingMethods = @[freeShipping, expressShipping];
[self setUpApplePayGoodsInfo:payRequest];
}
//账单信息的设置
- (void)setUpApplePayGoodsInfo:(PKPaymentRequest *)payRequest {
//每条账单的设置
//账单列表使用PKPaymentSummaryItem添加描述和价格.价格使用NSDecimalNumber
//PKPaymentSummaryItem初始化:
//Label为商品名字或者是描述,amount为商品价格,折扣为负数,Type为该条账单为最终价格还是估算价格(比如出租车车价格预估)
// + (instancetype)summaryItemWithLabel:(NSString *)label amount:(NSDecimalNumber *)amount;
// + (instancetype)summaryItemWithLabel:(NSString *)label amount:(NSDecimalNumber *)amount type:(PKPaymentSummaryItemType)type NS_AVAILABLE(NA, 9_0);
//NSDecimalNumber初始化:
//NSDecimalNumber可以使用数字初始化,也可以使用字符串
//添加账单列表
NSDecimalNumber * subtotalAmount = [NSDecimalNumber decimalNumberWithMantissa:1275 exponent:-2 isNegative:NO];//12.75
PKPaymentSummaryItem * subtotal = [PKPaymentSummaryItem summaryItemWithLabel:@"商品价格" amount:subtotalAmount];
NSDecimalNumber *discountAmount = [NSDecimalNumber decimalNumberWithString:@"-12.74"];//-12.74
PKPaymentSummaryItem *discount = [PKPaymentSummaryItem summaryItemWithLabel:@"优惠折扣" amount:discountAmount];
NSDecimalNumber *methodsAmount = [NSDecimalNumber zero];
PKPaymentSummaryItem *methods = [PKPaymentSummaryItem summaryItemWithLabel:@"包邮" amount:methodsAmount];
NSDecimalNumber *totalAmount = [NSDecimalNumber zero];
totalAmount = [totalAmount decimalNumberByAdding:subtotalAmount];
totalAmount = [totalAmount decimalNumberByAdding:discountAmount];
totalAmount = [totalAmount decimalNumberByAdding:methodsAmount];
PKPaymentSummaryItem *total = [PKPaymentSummaryItem summaryItemWithLabel:@"Yasin" amount:totalAmount];//最后这个是支付给谁。哈哈,快支付给我
summaryItems = [NSMutableArray arrayWithArray:@[subtotal, discount, methods, total]];
//summaryItems为账单列表,类型是 NSMutableArray,这里设置成成员变量,在后续的代理回调中可以进行支付金额的调整。
payRequest.paymentSummaryItems = summaryItems;
[self setUpApplePayView:payRequest];
}
//显示购物信息视图并进行支付
- (void)setUpApplePayView:(PKPaymentRequest *)payRequest {
PKPaymentAuthorizationViewController * PayVC = [[PKPaymentAuthorizationViewController alloc] initWithPaymentRequest:payRequest];
PayVC.delegate = self;
[self presentViewController:PayVC animated:YES completion:nil];
}
#pragma mark - PKPaymentAuthorizationViewControllerDelegate
//支付成功苹果服务器返回信息回调,做服务器验证
- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller
didAuthorizePayment:(PKPayment *)payment
completion:(void (^)(PKPaymentAuthorizationStatus status))completion {
// PKPaymentToken * payToken = payment.token;
// //支付凭据,发给服务器进行验证支付是否真实有效
// PKContact * billingContact = payment.billingContact; //账单信息
// PKContact * shippingContact = payment.shippingContact; //送货信息
// PKContact * shippingMethod = payment.shippingMethod; //送货方式
// NSError *error;
// ABMultiValueRef addressMultiValue = http://www.mamicode.com/ABRecordCopyValue(payment.billingAddress, kABPersonAddressProperty);
// NSDictionary *addressDictionary = (__bridge_transfer NSDictionary *) ABMultiValueCopyValueAtIndex(addressMultiValue, 0);
// NSData *json = [NSJSONSerialization dataWithJSONObject:addressDictionary options:NSJSONWritingPrettyPrinted error: &error];
// ... Send payment token, shipping and billing address, and order information to your server ...
//在这个位置,我们开发人员需要把token值和商品的其他信息如:地址 id 这些,上传到自己公司的服务器和银行的商家接口进行接口的调用,并将接口调用返回的支付结果信息返回到这里.
//根据不同的支付结果状态,让block调用不同的交易状态;
/**
将支付令牌token,payment上传服务器端,验证。。。。
*/
// 根据返回,判断成功与否
//等待服务器返回结果后在进行系统block调用
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//模拟服务器通信
completion(PKPaymentAuthorizationStatusSuccess);
});
NSLog(@"-=-=-=-=-=-=-=-==-=-==%s", __FUNCTION__);
}
//支付完成
- (void)paymentAuthorizationViewControllerDidFinish:(PKPaymentAuthorizationViewController *)controller {
[controller dismissViewControllerAnimated:YES completion:nil];
NSLog(@"-=-=-=-=-=-=-=-==-=-==%s", __FUNCTION__);
}
//ios 8_3 - 真机使用TouchID调用
- (void)paymentAuthorizationViewControllerWillAuthorizePayment:(PKPaymentAuthorizationViewController *)controller {
NSLog(@"-=-=-=-=-=-=-=-==-=-==%s", __FUNCTION__);
}
//送货方式回调
- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller
didSelectShippingMethod:(PKShippingMethod *)shippingMethod
completion:(void (^)(PKPaymentAuthorizationStatus status, NSArray<PKPaymentSummaryItem *> *summaryItems))completion {
//配送方式回调,如果需要根据不同的送货方式进行支付金额的调整,比如包邮和付费加速配送,可以实现该代理
PKShippingMethod * oldShippingMethod = [summaryItems objectAtIndex:2];
PKPaymentSummaryItem * total = [summaryItems lastObject];
total.amount = [total.amount decimalNumberBySubtracting:oldShippingMethod.amount];
total.amount = [total.amount decimalNumberByAdding:shippingMethod.amount];
[summaryItems replaceObjectAtIndex:2 withObject:shippingMethod];
[summaryItems replaceObjectAtIndex:3 withObject:total];
completion(PKPaymentAuthorizationStatusSuccess, summaryItems);
NSLog(@"-=-=-=-=-=-=-=-==-=-==%s", __FUNCTION__);
}
//送货地址回调,已弃用
- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller
didSelectShippingAddress:(ABRecordRef)address
completion:(void (^)(PKPaymentAuthorizationStatus status, NSArray<PKShippingMethod *> *shippingMethods,
NSArray<PKPaymentSummaryItem *> *summaryItems))completion NS_DEPRECATED_IOS(8_0, 9_0, "Use the CNContact backed delegate method instead") {
NSLog(@"-=-=-=-=-=-=-=-==-=-==%s", __FUNCTION__);
}
//ios 9_0 - 送货地址回调
- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller
didSelectShippingContact:(PKContact *)contact
completion:(void (^)(PKPaymentAuthorizationStatus status, NSArray<PKShippingMethod *> *shippingMethods,
NSArray<PKPaymentSummaryItem *> *summaryItems))completion {
//contact送货地址信息,PKContact类型
// NSPersonNameComponents *name = contact.name; //联系人姓名
// CNPostalAddress *postalAddress = contact.postalAddress; //联系人地址
// NSString *emailAddress = contact.emailAddress; //联系人邮箱
// CNPhoneNumber *phoneNumber = contact.phoneNumber; //联系人手机
// NSString *supplementarySubLocality = contact.supplementarySubLocality; //补充信息,iOS9.2及以上才有
//contact送货地址信息,PKContact类型
//送货信息选择回调,如果需要根据送货地址调整送货方式,比如不同包邮+急速配送,偏远地区只有付费普通配送,进行支付金额重新计算,可以实现该代理,返回给系统:shippingMethods配送方式,summaryItems账单列表,如果不支持该送货信息返回想哟啊的PKPaymentAuthorizationStatus
completion(PKPaymentAuthorizationStatusSuccess, shippingMethods, summaryItems);
NSLog(@"-=-=-=-=-=-=-=-==-=-==%s", __FUNCTION__);
}
//ios 9_0 - 支付卡回调
- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller
didSelectPaymentMethod:(PKPaymentMethod *)paymentMethod
completion:(void (^)(NSArray<PKPaymentSummaryItem *> *summaryItems))completion {
//支付银行卡回调,如果需要根据不同的银行调整付费金额,可以实现该代理
completion(summaryItems);
NSLog(@"-=-=-=-=-=-=-=-==-=-==%s", __FUNCTION__);
}
//仿商品上拉详情
- (void)setUpGoodsDetail {
//设置UITableView 上拉加载
self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//上拉,执行对应的操作---改变底层滚动视图的滚动到对应位置
//设置动画效果
[UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{
self.backScorllView.contentOffset = CGPointMake(0, self.backScorllView.height);
} completion:^(BOOL finished) {
//结束加载
[self.tableView.mj_footer endRefreshing];
}];
}];
//设置UIWebView 有下拉操作
self.webView.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//设置动画效果
[UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{
//下拉执行对应的操作
self.backScorllView.contentOffset = CGPointMake(0, 0);
} completion:^(BOOL finished) {
//结束加载
[self.webView.scrollView.mj_header endRefreshing];
}];
}];
}
iOS Apple Pay