Search code examples
swiftswift3stripe-payments

Pass an uploaded image directly from json file


I am trying to upload an image from my app to my heroku backend and then pass that to Stripe for verification. Here is my swift code to upload and pass the image:

@IBAction func registerAccountButtonWasPressed(sender: UIButton) {
    let dob = self.dobTextField.text!.components(separatedBy: "/")
    let URL = "https://splitterstripeservertest.herokuapp.com/account/create"
    var imageData = UIImageJPEGRepresentation(photoID,1)
    let params = ["year": UInt(dob[2])! as UInt] as [String : Any]

    let manager = AFHTTPSessionManager()
    let operation = manager.post(URL, parameters: params, constructingBodyWith: { (formData: AFMultipartFormData!) -> Void in
        formData.appendPart(withFileData: imageData!, name: "file", fileName: "photoID.jpg", mimeType: "image/jpeg")
    }, success: { (operation, responseObject) -> Void in
        print(responseObject!)
    }) { (operation, error) -> Void in
        self.handleError(error as NSError)
    }
}

I've deleted the list of params above out and left one for readability.

Is there a way to then receive this file and upload it to stripe without having to save it by passing the file parameter? like so:

Stripe::FileUpload.create(
  {
    :purpose => 'identity_document',
    :file => params[file]
  },
  {:stripe_account => params[stripe_account]}
)

Also in the stripe docs it says to upload the file to 'https://uploads.stripe.com/v1/files' but then shows code to put in your backend, does Stripe::FileUpload.create do the uploading to stripe for me?

Any insight on either would be great thanks.


Solution

  • You need to first upload the file to Stripe's API using the "create file upload" call. You can then use the file upload's ID (file_...) to update the account's legal_entity.verification.document attribute.

    (This process is explained here:

    Since the file is provided by the user, you have two choices for creating the file upload:

    • have your app upload the file to your backend server, then on your backend, use the file to create the file upload

    • create the file upload directly from the app (using your publishable API key), and send the resulting file_upload's ID (file_...) to your backend

    Here's an example for creating file uploads client-side, using jQuery: https://jsfiddle.net/captainapollo/d8yd3761/.

    You could do the same thing from your iOS app's code. Basically all you need to do is send a POST request to https://uploads.stripe.com/v1/files with an Authorization header with value Bearer pk_... (where pk_... is your publishable API key) and type multipart/form-data, with the file's contents as the request's body. This blog post should be helpful for sending multipart/form-data requests using Swift: http://www.kaleidosblog.com/how-to-upload-images-using-swift-2-send-multipart-post-request