Search code examples
swiftparse-platformsmstwilioparse-cloud-code

Verification code always invalid using Swift Parse and Twilio


Im using SMS verification to verify users. My problem is that when I enter a code to verify I get invalid code. I can't for the life of me figure out why.

Calling cloud code function:

@IBAction func verifyCodeButtonTapped(sender: AnyObject) {
    var verificationCode: String = verificationCodeTextField.text!
    let textFieldText = verificationCodeTextField.text ?? ""

    if verificationCode.utf16.count != 4 {
        displayAlert("Error", message: "You must entert the 4 digit verification code sent yo your phone")
    } else {
        let params = ["verifyPhoneNumber" : textFieldText]
        PFCloud.callFunctionInBackground("verifyPhoneNumber", withParameters: params, block: { (object: AnyObject?, error) -> Void in
            if error == nil {
                self.performSegueWithIdentifier("showVerifyCodeView", sender: self)
            } else {
                self.displayAlert("Sorry", message: "We couldnt verify you. Please check that you enterd the correct 4 digit code sent to your phone")
            }
        })
    }
}

Cloud code to verify code:

Parse.Cloud.define("verifyPhoneNumber", function(request, response) {
    var user = Parse.User.current();
    var verificationCode = user.get("phoneVerificationCode");
    if (verificationCode == request.params.phoneVerificationCode) {
        user.set("phoneNumber", request.params.phoneNumber);
        user.save();
        response.success("Success");
    } else {
        response.error("Invalid verification code.");
    }
});

Solution

  • Twilio developer evangelist here.

    In the Parse code, you are expecting request.params.phoneVerificationCode but when you call the cloud function from iOS you let params = ["verifyPhoneNumber" : textFieldText].

    So, either change that line to

    let params = ["phoneVerificationCode" : textFieldText]
    

    so that it matches the cloud code. Or change your cloud code to

    if (verificationCode == request.params.verifyPhoneNumber) {
    

    so that it matches the iOS code.