專案裡有個需求:讓用戶掃一下銀行卡就自動帶入卡號。相比讓用戶手打十六位數字,掃描的體驗與準確率都更好。評估之後選用了 card.io——它調用手機攝像頭,藉助 OCR(光學字元識別)技術取得卡片資訊,並提供 SDK 供開發者集成。
可從 PayPal 官方倉庫取得最新版本:https://github.com/paypal/PayPal-iOS-SDK
1. 拖入 CardIO 文件夾,並在 TARGETS → Build Phases → Link Binary With Libraries 中加入依賴庫:
* AudioToolbox
* AVFoundation
* CoreGraphics
* CoreMedia
* CoreVideo
* Foundation
* MobileCoreServices
* OpenGLES
* QuartzCore
* Security
* UIKit
若使用 Xcode 5 或更新版本,只需要這幾個:
* AVFoundation
* AudioToolbox
* CoreMedia
* MobileCoreServices
2. 確認 Build Settings 中以下兩項為 YES:
* Enable Modules (C and Objective-C)
* Link Frameworks Automatically
3. 在 TARGETS → Build Settings 的 Other Linker Flags 中加入 -lc++。
我把 CardIOPaymentViewController 當作一個普通的 view controller 來用,以模態方式彈出。
#import "CardIO.h"
#import "CardIOPaymentViewControllerDelegate.h"
預先加載資源可以讓第一次打開掃描頁更快:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[CardIOUtilities preload];
}
啟動掃描:
- (IBAction)scanCard:(id)sender {
CardIOPaymentViewController *scanViewController =
[[CardIOPaymentViewController alloc] initWithPaymentDelegate:self];
[self presentViewController:scanViewController animated:YES completion:nil];
}
兩個代理方法分別處理取消與完成:
// 用戶取消掃描
- (void)userDidCancelPaymentViewController:(CardIOPaymentViewController *)scanViewController {
NSLog(@"User canceled payment info");
[scanViewController dismissViewControllerAnimated:YES completion:nil];
}
// 掃描完成
- (void)userDidProvideCreditCardInfo:(CardIOCreditCardInfo *)info
inPaymentViewController:(CardIOPaymentViewController *)scanViewController {
NSLog(@"Received card info. Number: %@, expiry: %02i/%i, cvv: %@.",
info.redactedCardNumber, info.expiryMonth, info.expiryYear, info.cvv);
// 在這裡使用 info 的資料
[scanViewController dismissViewControllerAnimated:YES completion:nil];
}
redactedCardNumber 讓你只取遮罩後的卡號;CVV 依支付產業規範通常不應由商家留存,接入前請先確認自身業務是否需要,以及是否符合相關規範。CardIOPaymentViewController 支援隱藏 CVV、有效期欄位,也能調整掃描框提示文案,依實際欄位需求調整即可。NSCameraUsageDescription 並寫清楚用途,否則會直接崩潰。