Search code examples
iosswiftauthorizationtokenbraintree

Authorization required error during braintree integration in swift


I am trying to integrate braintree payment method in my swift code, but I am stuck in here, it is breaking with an error

{"error":{"statusCode":401,"name":"Error","message":"Authorization Required","code":"AUTHORIZATION_REQUIRED"}}

I have doing exactly the same as mentioned in braintree documentation. I don't know which authorization it is demanding, I do have a authorization token assigned to user when he/she logins, I am wondering if it is demanding that authorization token, but there is no such parameter in this code where I should place that token to generate client's token for payment method. Here the print statement when exeuted gives me this in log, "client Token is :

{"error":{"statusCode":401,"name":"Error","message":"Authorization Required","code":"AUTHORIZATION_REQUIRED"}}", I am bit confused in its calling also. I have just started these thing so I am very sorry I have done any obvious mistake. Thanks.

        // TODO: Switch this URL to your own authenticated API

        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
            if let error = error {
                print("Error: \(error.localizedDescription)")

            } else {
                print("in Session")
                let clientToken = String(data: data!, encoding: 
              String.Encoding.utf8)!
                print("Client Token is : \(clientToken)")

            }

            }.resume()
         }

Solution

  • One have to give authorization token in headers to avoid this error. Rather than that, this version of code will work fine.

           completionHandler:@escaping (_ response: NSDictionary?, _ error: Error?) - 
             > ()) {
    
    
    
            var headers: HTTPHeaders
    
            // pass the authToken when you get when user login
            let authToken = getAuthorizationToken()
    
            if(self.isValidString(object: authToken as AnyObject)) {
                headers = ["Authorization": authToken,
                           "Content-Type": "application/json",
                           "Accept": "application/json"]
    
             } else {
                 headers = ["Content-Type": "application/json"]
             }
    
            AF.request(apiURL, method: .get, parameters: params as? Parameters, 
            encoding: JSONEncoding.default, headers: headers).validate().responseJSON 
        { 
               response in
                self.handleResposne(response: response) { (response, error) in
                    completionHandler(response, error)
                }
            }
         }