简体   繁体   English

如何在 firebase.auth (js, ts) 中更新用户电话号码

[英]how to update user phone number in firebase.auth (js, ts)

How can i update user phone number which it use for auth in firebase.auth??如何在 firebase.auth 中更新用于身份验证的用户电话号码?

Firebase give as method: Firebase 给出方法:

updatePhoneNumber(phoneCredential)

But we need give phoneCredential .但是我们需要给phoneCredential This credential takes object:此凭据需要对象:

  interface AuthCredential {
    providerId: string;
    signInMethod: string;
  }

What must be in this phoneCredential , i try to send这个手机凭据中必须有什么,我尝试发送

providerId: 'phone';
signInMethod: 'phone';

and this is not work ;(这是行不通的;(

The solution to updatePhoneNumber with a current user / logged-in account.使用当前用户/登录帐户更新电话号码的解决方案。 In case this helps anyone.万一这对任何人都有帮助。

problem: Say you have a current logged in account with any number of single/merged accounts and they want to update their number.问题:假设您有一个当前登录的帐户,其中包含任意数量的单个/合并帐户,并且他们想要更新其编号。 How would they do it.他们会怎么做。

solution: The below is Auth for Web/JS method, the equivalent will exist for your target platform.解决方案:以下是 Web/JS 的 Auth 方法,您的目标平台将存在等效的方法。

function updateProfilePhoneNumber() {
    //country code plus your phone number excluding leading 0 if exists.
    var phoneNumber = "+447xxxxxxxxx"; //you could provide a prompt/modal or other field in your UX to replace this phone number.

    // let phoneNumber = "+441234567890"; //testing number, ideally you should set this in your firebase auth settings
    // var verificationCode = "123456";

    // Turn off phone auth app verification.
    // firebase.auth().settings.appVerificationDisabledForTesting = true;

    // This will render a fake reCAPTCHA as appVerificationDisabledForTesting is true.
    // This will resolve after rendering without app verification.
    var appVerifier = new firebase.auth.RecaptchaVerifier(
        "recaptcha-container",
        {
            size: "invisible"
        }
    );

    var provider = new firebase.auth.PhoneAuthProvider();
    provider.verifyPhoneNumber(phoneNumber, appVerifier)
        .then(function (verificationId) {
            var verificationCode = window.prompt('Please enter the verification ' +
                'code that was sent to your mobile device.');
            phoneCredential = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
            user.currentUser.updatePhoneNumber(phoneCredential);
        })
        .then((result) => {
            // Phone credential now linked to current user.
            // User now can sign in with new phone upon logging out.
            console.log(result);
        })
        .catch((error) => {
            // Error occurred.
            console.log(error);
        });
}

Happy to be corrected here.很高兴在这里得到纠正。

You need to get the credential from firebase.auth.PhoneAuthProvider.credential .您需要从firebase.auth.PhoneAuthProvider.credential获取凭证。

    // Send verification code to user's phone
    firebase.auth.PhoneAuthProvider.verifyPhoneNumber(phoneNumber, recaptchVerifier).then(function(verificationId) {
      // verification code from user
      var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
    });

Edited : I edited my previous answer as I now think it was far from being right.编辑:我编辑了我以前的答案,因为我现在认为它远非正确。 After researching a bit more, I believe you need to use the built in PhoneAuthProvider to update the user phone number, like below:经过多研究,我相信您需要使用内置的PhoneAuthProvider来更新用户电话号码,如下所示:

const credential = firebase.auth.PhoneAuthProvider.credential( verificationId, verificationCode);

user.updatePhoneNumber(credential);

Original (wrong) : According to the documentation , you need to pass an object with the methods that will return the providerId, signInMethod (which should be phone, as in your code) and smsCode (the sms verification code that was sent to the user mobile as explained here ).原始(错误) :根据文档,您需要传递一个对象,该对象的方法将返回 providerId、signInMethod( 应该是电话,如您的代码)和 smsCode(发送给用户的短信验证码)移动作为解释这里)。 Give it a try like that:试试这样:

updatePhoneNumber({
  getProvider: () => { return providerStringCode; },
  getSignInMethod: () => { return signInMethodStringCode; },
  getSmsCode: () => { return smsStringCode; },
});

I'm also having the same problem, In my html page(using ionic 4 modal), I have 2 button send OTP & verify.我也有同样的问题,在我的 html 页面(使用 ionic 4 modal),我有 2 个按钮发送 OTP 和验证。 So this is my solution所以这是我的解决方案

 <ion-header> <ion-toolbar> <ion-title>Edit Phone</ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-card> <form [formGroup]="phoneForm"> <ion-item> <ion-label position="stacked" >Phone :</ion-label> <ion-input formControlName="phoneNumber" type="tel" required="true" [class.invalid]="!phoneForm.controls['phoneNumber'].valid && phoneForm.controls['phoneNumber'].touched"> </ion-input> </ion-item> <ion-item class="error-message" *ngIf="!phoneForm.controls['phoneNumber'].valid && phoneForm.controls['phoneNumber'].touched"> <ion-label>Phone Number.</ion-label> </ion-item> <div id="recaptcha-container" visibility="hidden"></div> <ion-button id="sign-in-button" *ngIf="!btnSend" (click)="editPhone(phoneForm)" expand="block" [disabled]="!phoneForm.valid" data-badge="inline">SMS OTP</ion-button> <ion-button id="sign-in-button" *ngIf="btnSend" expand="block" [disabled]="btnSend" data-badge="inline">{{timeLeft}}</ion-button> </form> </ion-card> <ion-card> <form [formGroup]="verificationForm"> <ion-item> <ion-label position="stacked"> OTP : </ion-label> <ion-input formControlName="verificationCode" type="tel" > </ion-input> </ion-item> <ion-button (click)="verifyPhoneCode()" expand="block" [disabled]="!verificationForm.valid||!verificationSend"> Verifikasi </ion-button> </form> </ion-card> </ion-content>

sendOTP(){
firebase.auth().currentUser.reauthenticateWithPhoneNumber(this.telepon,this.recaptchaVerifier)
    .then(result=>{

      this.confirmationResult = result;//firebase.auth.ConfirmationResult


    })
    .catch(error=>{
      this.presentErrorMessage(error.message);
    });
}

verifyPhoneNumber(){
    let phoneProvider = new firebase.auth.PhoneAuthProvider();
            phoneProvider.verifyPhoneNumber(this.telepon, this.recaptchaVerifier)//this.telepon is your new phone number
                 .then(verificationId=>{
                    let phoneCredential = firebase.auth.PhoneAuthProvider.credential(verificationId, this.verificationForm.value.verificationCode);
                    firebase.auth().currentUser.updatePhoneNumber(phoneCredential)
                    .then(()=>{
                      console.log("Success update phone");
                      this.authService.updatePhone(this.telepon).then(()=>{ //update my user database
                          this.dismiss(); //I'm using modal dialog for input
                        });
                    });
                  })
}

How to add a phone number to an existing, logged-in user ( verifyPhoneNumber ):如何将电话号码添加到现有的登录用户 ( verifyPhoneNumber ):

const appVerifier = new firebase.auth.RecaptchaVerifier('save-user-button', { size: 'invisible' }) // An element with id="save-user-button" must exist
const authProvider = new firebase.auth.PhoneAuthProvider()
const verificationId = await authProvider.verifyPhoneNumber(phoneNumber, appVerifier)
const verificationCode = window.prompt('Please enter the verification code that was sent to your phone.')
const phoneCredential = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode)
myFirebaseUser.updatePhoneNumber(phoneCredential)

Sign up/create new user from phone number ( signInWithPhoneNumber ):从电话号码注册/创建新用户( signInWithPhoneNumber ):

const appVerifier = new firebase.auth.RecaptchaVerifier('create-new-user-button', { size: 'invisible' }) // An element with id="create-new-user-button" must exist
const confirmationResult = await firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
const verificationCode = window.prompt('Please enter the verification code that was sent to your phone.')
const { user } = await confirmationResult.confirm(verificationCode)

https://firebase.google.com/docs/auth/web/phone-auth https://firebase.google.com/docs/auth/web/phone-auth

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将用户设置为在firebase.auth(node.js)上登录? - How to set the user as logged in on firebase.auth(node.js)? 如何使用从 firebase 存储的 Auth uid 并更新 Auth 用户信息,例如更改密码、email 和电话号码? - How to use Auth uid that store from firebase and update Auth user information such as change password, email and phone number? 如何在 Firebase Auth 中添加或更新电话号码 - How to add or update phone_number in Firebase Auth firebase.auth()。createUserWithEmailAndPassword()如何工作? - How does firebase.auth().createUserWithEmailAndPassword() works? firebase.auth().signInAnonymously() 如何维护会话? - firebase.auth().signInAnonymously() how to maintain session? firebase.auth 不是函数 - firebase.auth is not a function Firebase:如何从 firebase.auth().onAuthStateChanged 异步绑定用户到 Angular 模板? - Firebase: How to asynchronously bind User from firebase.auth().onAuthStateChanged to Angular template? JS,firebase.auth() 在全局上下文中不起作用,但在函数内部起作用? - firebase.Auth 不是函数 - JS, firebase.auth() doesn't work in global context but works inside the functions? - firebase.Auth is not a function Firebase.auth() 已弃用? - Firebase.auth() deprecated? firebase 工作,但 firebase.auth() 在 Vue.js 中不工作 - firebase working but firebase.auth() not working in Vue.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM