swiftrestsessionurlsessionrevenuecat

Error status code 400 when trying to delete a RevenueCat customer with REST, what could be the problem?


I am trying to delete a customer from RevenueCat if the user decides to delete their account. This is the code I implemented:

private func deleteRevenueCatAccount(forUserID: String) {
    
    let headers = ["accept": "application/json", "Authorization": "Bearer \(secretApiKey)"]
    let baseURL = "https://api.revenuecat.com/v1"
    let deleteEndpoint = "/subscribers/\(forUserID)"
    let urlString = baseURL + deleteEndpoint
    
    guard let url = URL(string: urlString) else {
        // Handle invalid URL error
        return
    }
    
    // Create the request
    let request = NSMutableURLRequest(
        url: url,
        cachePolicy: .useProtocolCachePolicy,
        timeoutInterval: 10.0
    )
    
    request.httpMethod = "DELETE"
    request.allHTTPHeaderFields = headers
    
    // Create the session
    let session = URLSession.shared
    
    // Send the request
    let task = session.dataTask(with: request as URLRequest) { (data, response, error) in
        
        if let error = error {
            // Handle error
            print("Error: \(error.localizedDescription)")
            return
        }
        
        // Check the response
        if let httpResponse = response as? HTTPURLResponse {
            
            if httpResponse.statusCode == 204 {
                // Customer deleted successfully
                print("Customer deleted successfully")
            } else {
                // Handle non-successful status code
                print("Error: \(httpResponse.statusCode)")
            }
            
        } //: HTTP RESPONSE
        
    } //: DATA TASK
    
    task.resume()
    
} //: FUNC

However, it throws an error with a status code 400 in the HTTPURLResponse.

Any ideas what could be the problem?

**Note:

The user that I am trying to delete is a sandbox user since I am still in development, but after contacting the RevenueCat support, they told me that it should still work for sandbox users.


Solution

  • I work at RevenueCat,

    If I had to guess, without looking at the response body of the request, it might be that you didn't explicitly state Content-Type: application/json in the request headers, try adding it:

     let headers = ["accept": "application/json", "Content-Type": "application/json", "Authorization": "Bearer \(secretApiKey)"]
    
    

    However you shouldn't use a Secret API key inside your App, these are meant to be securely used in your server, otherwise bad actors could perform destructive actions on your account!