使用twilio快速进行电话号码验证时出错

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用twilio快速进行电话号码验证时出错相关的知识,希望对你有一定的参考价值。

我想通过获取一次密码来验证电话号码。但是我遇到了一些错误。请查看下面的代码,并帮助我解决该问题。我正在使用Twilio进行移动验证。和Alamofire提出API请求。但是我得到的错误是:-

Authentication Error - No credentials provided.
The data couldn’t be read because it isn’t in the correct format

我的代码是:-

这是我的模特教室:-

...struct SendVerificationCode: Codable {
let status: String?
let payee: String?
let dateUpdated: Date?
let sendCodeAttempts: [SendCodeAttempt]?
let accountSid, to: String?
let amount: Int?
let valid: Bool?
let lookup: Lookup?
let url: String?
let sid: String?
let dateCreated: Date?
let serviceSid, channel: String?

enum CodingKeys: String, CodingKey {
    case status, payee
    case dateUpdated = "date_updated"
    case sendCodeAttempts = "send_code_attempts"
    case accountSid = "account_sid"
    case to, amount, valid, lookup, url, sid
    case dateCreated = "date_created"
    case serviceSid = "service_sid"
    case channel
}
}


struct Lookup: Codable {
let carrier: Carrier?
}


struct Carrier: Codable {
let mobileCountryCode, type: String?
let errorCode: String?
let mobileNetworkCode, name: String?

enum CodingKeys: String, CodingKey {
    case mobileCountryCode = "mobile_country_code"
    case type
    case errorCode = "error_code"
    case mobileNetworkCode = "mobile_network_code"
    case name
}
}


 struct SendCodeAttempt: Codable {
let channel, time: String?
}...

Api请求:-

...func sendcode(mobileWithCode: String, completion: @escaping sendTwillioVerificationCodeCompletion) {

    let url = URL(string: SEND_TWILIO_VERIFICATION_CODE)
   var urlRequest = URLRequest(url: url!)
   urlRequest.httpMethod = HTTPMethod.post.rawValue
   urlRequest.addValue(userNameData, forHTTPHeaderField: "Username")
    urlRequest.addValue(PasswordData, forHTTPHeaderField: "Password")
    urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")


   Alamofire.request(urlRequest).responseJSON { (response) in
       if let error = response.result.error {
           debugPrint(error.localizedDescription)
           completion(nil)
           return
       }

       guard let data = response.data else { return completion(nil)}

       Common.sharedInstance().printRequestOutput(data: data)

       let jsonDecoder = JSONDecoder()
       do {
           let clear = try jsonDecoder.decode(SendVerificationCode.self, from: data)
           completion(clear)
       } catch {
           debugPrint(error.localizedDescription)
           completion(nil)
       }
   }
}...

但是我遇到错误:-

   {"code": 20003, "detail": "Your AccountSid or AuthToken was incorrect.", "message": "Authentication Error - No credentials provided", "more_info": "https://www.twilio.com/docs/errors/20003", "status": 401}
   "The data couldn’t be read because it isn’t in the correct format."

我也尝试过以下代码:-

semaphore = DispatchSemaphore (value: 0)

let parameters = "To=+919778882332&Channel=sms"
let postData =  parameters.data(using: .utf8)

var request = URLRequest(url: URL(string:  myUrl)!,timeoutInterval: Double.infinity)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue(requestData, forHTTPHeaderField: "Authorization")

request.httpMethod = "POST"
request.httpBody = postData

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
guard let data = data else {
print(String(describing: error))
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()
}

task.resume()
semaphore.wait()

但是我遇到了类似的错误

"Invalid parameter"
答案
似乎您的代码正试图直接从设备上调用Twilio API,而您并未在其中设置帐户SID或Auth令牌。

这里的问题是,您不应在应用程序内存储或访问身份验证令牌。这会使您的帐户sid和auth令牌容易被盗,然后用于滥用您的帐户。

相反,您应该创建一个与Twilio API对话的服务器端应用程序,然后从您的应用程序中调用它。

正如Jamil指出的那样,您可以在performing phone verification in iOS with Twilio Verify and Swift上找到一篇博客文章,我建议您仔细阅读。它包括用Python内置的an example server side application to call the Twilio Verify API,但您也可以自己构建。

另一答案
import UIKit class ViewController: UIViewController { static let path = Bundle.main.path(forResource: "Config", ofType: "plist") static let config = NSDictionary(contentsOfFile: path!) private static let baseURLString = config!["serverUrl"] as! String @IBOutlet var countryCodeField: UITextField! = UITextField() @IBOutlet var phoneNumberField: UITextField! = UITextField() @IBAction func sendVerification() { if let phoneNumber = phoneNumberField.text, let countryCode = countryCodeField.text { ViewController.sendVerificationCode(countryCode, phoneNumber) } } static func sendVerificationCode(_ countryCode: String, _ phoneNumber: String) { let parameters = [ "via": "sms", "country_code": countryCode, "phone_number": phoneNumber ] let path = "start" let method = "POST" let urlPath = "(baseURLString)/(path)" var components = URLComponents(string: urlPath)! var queryItems = [URLQueryItem]() for (key, value) in parameters { let item = URLQueryItem(name: key, value: value) queryItems.append(item) } components.queryItems = queryItems let url = components.url! var request = URLRequest(url: url) request.httpMethod = method let session: URLSession = { let config = URLSessionConfiguration.default return URLSession(configuration: config) }() let task = session.dataTask(with: request) { (data, response, error) in if let data = data { do { let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] print(jsonSerialized!) } catch let error as NSError { print(error.localizedDescription) } } else if let error = error { print(error.localizedDescription) } } task.resume() } }

有关更多信息,请检查此链接:Link

另一答案
None

以上是关于使用twilio快速进行电话号码验证时出错的主要内容,如果未能解决你的问题,请参考以下文章

执行 python 程序以从 twilio 服务器获取呼叫者参加电话会议时出错

在 Twilio 客户端快速入门中接收真正的来电

twilio.js 浏览器软件电话 - JWT 签名验证问题(Mac OSX / Chrome)

Twilio,如何将正在进行的呼叫转移到另一个号码

无法向菲律宾号码发送可编程短信 (Twilio)

未处理的异常:[firebase_auth/unknown] null:使用颤振/firebase 进行电话身份验证时出错