简体   繁体   中英

Stripe iOS: I'm not able to create charge using card id

I am trying create charges using the standard iOS integration described here: https://stripe.com/docs/mobile/ios/standard

to do it, I have in my CheckoutController.swift

func paymentContext(_ paymentContext: STPPaymentContext, didCreatePaymentResult paymentResult: STPPaymentResult, completion: @escaping STPErrorBlock) {

    StripeClient.shared.completeCharge(paymentResult, amount: 1000, shippingAddress: nil, shippingMethod: nil, completion: { (error: Error?) in
        if let error = error {
            completion(error)
        } else {
            completion(nil)
        }
    })
}

In my StripeClient.swift

func completeCharge(_ result: STPPaymentResult,
                    amount: Int,
                    shippingAddress: STPAddress?,
                    shippingMethod: PKShippingMethod?,
                    completion: @escaping STPErrorBlock) {
    let url = self.baseURL.appendingPathComponent("charge")

    var params: [String: Any] = [
        "source": result.source.stripeID,
        "amount": amount,
        "description": Purchase.shared.description()
    ]
    params["shipping"] = STPAddress.shippingInfoForCharge(with: shippingAddress, shippingMethod: shippingMethod)
    Alamofire.request(url, method: .post, parameters: params, headers: Credentials.headersDictionary())
        .validate(statusCode: 200..<300)
        .responseString { response in
            switch response.result {
            case .success:
                completion(nil)
            case .failure(let error):
                completion(error)
            }
    }
}

And, in my API (Ruby on Rails)

  def charge
    Stripe::Charge.create(charge_params)
    render json: { success: true }, status: :ok
  rescue Stripe::StripeError => e
    render json: { error: "Error creating charge: #{e.message}" },
           status: :payment_required
  end

  private

  def charge_params
    params
      .permit(:amount, :description, :source)
      .merge(currency: 'gbp')
  end

The problem is in completeCharge method, result.source.stripeID is returning a card id (card_xxxxxx) but I need a token (tok_xxxxxx). So,

how can I get a token from card id or STPPaymentResult object? or how can I get my Rails API works with a card id in place of a token? or any other solution?

Regards.

Go it! when you use a card_id instead a token, is necessary pass the customer id as parameter, so, I modified my api:

  def charge_params
    params
      .permit(:amount, :description, :source)
      .merge(currency: 'gbp',
             customer: current_user.stripe_customer_id)
  end

(I am storing the Stripe customer id as stripe_customer_id in my users table)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM