You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift集成PayFort问题:无法创建沙箱账户及支付参数获取咨询

Hey there, let’s break down your PayFort integration hurdles step by step— I’ve tangled with payment gateways like this before, so I get how frustrating it can be when the setup process feels opaque. Here’s what you need to know:

1. Troubleshooting Sandbox Account Access

If you submitted your info via the PayFort get-started page but still can’t create/login to your sandbox account, here are a few fixes to try:

  • Check your spam folder: PayFort’s activation emails often end up here. Look for messages from their support team with a link to set your sandbox account password.
  • Verify your submission details: Double-check that you filled out all required fields (like a valid business email, contact number) correctly. Missing info can delay account creation.
  • Reach out to PayFort support: If you still don’t hear back after 24-48 hours, use the support portal on their website to follow up— they’re usually responsive to sandbox account requests.
2. Getting Test Account Credentials (merchant_identifier, access_code, service_command)

Once your sandbox account is active, here’s how to grab the key credentials:

  • Log into your sandbox merchant dashboard: This is the admin portal you’ll get access to after activating your account.
  • Navigate to API Credentials: Look for a section like Settings > API Integration or Security > Credentials— this is where you’ll find your merchant_identifier and access_code (treat these like passwords, never hardcode them in your app!).
  • Understanding service_command: This parameter defines the action you want to perform. Common values include:
    • AUTHORIZATION: Hold a customer’s funds without charging them immediately
    • PURCHASE: Charge the customer’s card immediately
    • TOKENIZATION: Store a card token for future payments
      You’ll pick the right value based on your payment flow (check PayFort’s official docs for the full list of commands).
3. What is PayPort?

PayPort is PayFort’s hosted payment page solution. Instead of building your own credit card input form (which requires strict PCI compliance), you redirect users to PayPort’s secure, pre-built page. They enter their payment details there, and PayFort sends the result back to your app. It’s a great way to simplify integration and reduce security risks for your team.

4. Swift Integration Example

Here’s a basic example of how to initiate a PayPort payment flow in Swift using a WebView (since PayFort doesn’t have an official Swift SDK):

import UIKit
import WebKit

class PayFortPaymentViewController: UIViewController, WKNavigationDelegate {
    private var webView: WKWebView!
    private let shaRequestPhrase = "YOUR_SHA_REQUEST_PHRASE" // Grab from your sandbox dashboard
    private let merchantIdentifier = "YOUR_MERCHANT_ID"
    private let accessCode = "YOUR_ACCESS_CODE"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupWebView()
        initiatePayment()
    }
    
    private func setupWebView() {
        webView = WKWebView(frame: view.bounds)
        webView.navigationDelegate = self
        view.addSubview(webView)
    }
    
    private func initiatePayment() {
        // 1. Build core payment parameters
        var parameters: [String: String] = [
            "merchant_identifier": merchantIdentifier,
            "access_code": accessCode,
            "service_command": "PURCHASE",
            "amount": "1000", // Amount in smallest currency unit (e.g., 10.00 AED = 1000)
            "currency": "AED",
            "customer_email": "test@example.com",
            "order_description": "Test Product Purchase",
            "language": "en",
            "return_url": "your-app-scheme://payfort-callback" // Custom URL scheme for your app
        ]
        
        // 2. Generate PayFort signature (HMAC-SHA256 authentication)
        let sortedKeys = parameters.keys.sorted()
        var signatureString = shaRequestPhrase
        for key in sortedKeys {
            signatureString += "\(key)=\(parameters[key]!)"
        }
        signatureString += shaRequestPhrase
        
        if let data = signatureString.data(using: .utf8) {
            var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
            CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), shaRequestPhrase, shaRequestPhrase.count, data.bytes, data.count, &digest)
            let signature = Data(digest).map { String(format: "%02hhx", $0) }.joined()
            parameters["signature"] = signature
        }
        
        // 3. Create POST request to PayPort sandbox endpoint
        guard let url = URL(string: "https://sbpaymentservices.payfort.com/FortAPI/paymentApi") else { return }
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        
        // Encode parameters into form data
        let postString = parameters.map { "\($0.key)=\($0.value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)" }.joined(separator: "&")
        request.httpBody = postString.data(using: .utf8)
        
        // 4. Load request in WebView
        webView.load(request)
    }
    
    // Handle callback from PayPort to your app
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        guard let url = navigationAction.request.url else {
            decisionHandler(.allow)
            return
        }
        
        if url.scheme == "your-app-scheme" {
            // Parse payment result parameters
            let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
            let status = components?.queryItems?.first(where: { $0.name == "status" })?.value
            let transactionId = components?.queryItems?.first(where: { $0.name == "transaction_id" })?.value
            
            print("Payment Status: \(status ?? "Unknown")")
            print("Transaction ID: \(transactionId ?? "Unknown")")
            
            // Navigate back to your app's main flow
            dismiss(animated: true)
            decisionHandler(.cancel)
            return
        }
        
        decisionHandler(.allow)
    }
}

Key Notes:

  • Replace placeholder values (like YOUR_SHA_REQUEST_PHRASE) with credentials from your sandbox dashboard.
  • Set up a custom URL scheme (e.g., your-app-scheme) in your Xcode project so PayPort can redirect back to your app after payment.
  • Add error handling for network failures, invalid signatures, and user cancellations in production code.

内容的提问来源于stack exchange,提问作者B.Selvam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:27:50