使用套件
Braintree可以快速使用
但是目前還是測試階段的樣子
基本流程就是
1.先取得Token(自己的server 這裡用官方測試提供的)
2.再將Token丟給braintree server
3.取得Nonce再丟給自己的server註冊
4.然後自己server再跟
braintree server溝通
這邊提供iOS手機端方法
在Podfile加入
pod 'BraintreeDropIn'
下載套件完成後在storyboard拉個有按鈕的UI
Ex:
Braintree有提供測試用的信用卡號
可來這裡參考
https://developers.braintreepayments.com/reference/general/testing/ruby
在ViewController.swift
import UIKit
import BraintreeDropIn
import Braintree
class ViewController: UIViewController {
@IBOutlet weak var btnShow: UIButton!
@IBOutlet weak var indicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func fetchClientToken() {
self.btnShow.isEnabled = false
self.indicator.isHidden = false
// TODO: Switch this URL to your own authenticated API
// 測試用官方取得Token Url
let clientTokenURL = NSURL(string: "https://braintree-sample-merchant.herokuapp.com/client_token")!
let clientTokenRequest = NSMutableURLRequest(url: clientTokenURL as URL)
clientTokenRequest.setValue("text/plain", forHTTPHeaderField: "Accept")
URLSession.shared.dataTask(with: clientTokenRequest as URLRequest) { (data, response, error) -> Void in
// TODO: Handle errors
let clientToken = String(data: data!, encoding: String.Encoding.utf8)
print("clientToken:\(clientToken!)")
self.showDropIn(clientTokenOrTokenizationKey: clientToken!)
// As an example, you may wish to present Drop-in at this point.
// Continue to the next section to learn more...
}.resume()
}
@IBAction func jumpDropIn(_ sender: UIButton) {
fetchClientToken()
}
func showDropIn(clientTokenOrTokenizationKey: String) {
DispatchQueue.main.async {
let request = BTDropInRequest()
let dropIn = BTDropInController(authorization: clientTokenOrTokenizationKey, request: request) { (controller, result, error) in
if (error != nil) {
print("ERROR:\(error.debugDescription)")
} else if (result?.isCancelled == true) {
print("CANCELLED")
} else if let result = result {
// Use the BTDropInResult properties to update your UI
print("result paymentOptionType:\(result.paymentOptionType)")
// 取得nonce後,拿nonce去後端註冊
print("result paymentMethod.nonce:\(result.paymentMethod!.nonce)")
print("result paymentIcon:\(result.paymentIcon)")
print("result paymentDescription:\(result.paymentDescription)")
}
self.btnShow.isEnabled = true
self.indicator.isHidden = true
controller.dismiss(animated: true, completion: nil)
}
self.present(dropIn!, animated: true, completion: nil)
}
}
}