With the help of AppGallery Connect (hereinafter referred to as AGC) authentication services, cloud functions, short message services and other services, after the user has successfully registered, he can receive an application welcome text message or welcome email in the registered mobile phone number or email address. In order to let developers integrate into the application faster and know the hot content of the application for the first time.

Implementation process

Access authentication service mobile phone number and email authentication method

First of all, we need to create an application account system by accessing the authentication service.

Enable authentication service

1. Log in to the AppGallery Connect website and click "My Project".

2. Click your project in the project list. Select "Build> Authentication Service",

3. Enter the authentication service page and complete the following operations:

a. Open authentication service

b. Enable mobile phone number and email address authentication

Develop mobile phone number authentication method

Since the development process of the email address authentication method is highly similar to that of the mobile phone number authentication method, we will take the mobile phone number authentication method as an example.

1. First, we need to call the sendVerifyCode method to obtain the verification code for registration:

public void sendPhoneVerify(String accountNumber) {
    String countryCode = "86";
    VerifyCodeSettings settings = VerifyCodeSettings.newBuilder()
            .action(VerifyCodeSettings.ACTION_REGISTER_LOGIN)
            .sendInterval(30)
            .locale(Locale.SIMPLIFIED_CHINESE)
            .build();
    if (notEmptyString(countryCode) && notEmptyString(accountNumber)) {
        Task<VerifyCodeResult> task = PhoneAuthProvider.requestVerifyCode(countryCode, accountNumber, settings);
        task.addOnSuccessListener(TaskExecutors.uiThread(), verifyCodeResult -> {
            mAuthReCallBack.onSendVerify(verifyCodeResult);
        }).addOnFailureListener(TaskExecutors.uiThread(), e -> {
            Log.e(TAG, "requestVerifyCode fail:" + e.getMessage());
            mAuthReCallBack.onFailed(e.getMessage());
        });
    } else {
        Log.w(TAG, "info empty");
    }
}

2. Then we call the createUser method for user registration

public void registerPhoneUser(String accountNumber, String verifyCode, String password) {
    String countryCode = "86";
    PhoneUser phoneUser = new PhoneUser.Builder()
            .setCountryCode(countryCode)
            .setPhoneNumber(accountNumber)
            .setVerifyCode(verifyCode)
            .setPassword(password)
            .build();
    AGConnectAuth.getInstance().createUser(phoneUser)
            .addOnSuccessListener(signInResult -> {
                mAuthReCallBack.onAuthSuccess(signInResult, 11);
            }).addOnFailureListener(e -> {
        mAuthReCallBack.onFailed(e.getMessage());
    });
}

3. For registered users, we can call the signin method to log in

public void phoneLogin(String phoneAccount, String photoPassword) {
    String countryCode = "86";
    AGConnectAuthCredential credential = PhoneAuthProvider.credentialWithVerifyCode(
            countryCode,
            phoneAccount,
            photoPassword,
            null);
    AGConnectAuth.getInstance().signIn(credential).addOnSuccessListener(signInResult -> {
        Log.i(TAG, "phoneLogin success");
        mAuthLoginCallBack.onAuthSuccess(signInResult, 11);
        signInResult.getUser().getToken(true).addOnSuccessListener(tokenResult -> {
            String token = tokenResult.getToken();
            Log.i(TAG, "getToken success:" + token);
            mAuthLoginCallBack.onAuthToken(token);
        });
    }).addOnFailureListener(e -> {
        Log.e(TAG, "Login failed: " + e.getMessage());
        mAuthLoginCallBack.onAuthFailed(e.getMessage());
    });
}

Set the trigger for successful registration of the authentication service in the cloud function

After the above operations are completed, you need to configure the authentication service trigger in the cloud function.

1. Log in to the AppGallery Connect website and click "My Project".

2. Click your project in the project list. Select "Build> Cloud Function" to enter the cloud function page and complete the following operations:

a. enables cloud function service .

b. Create a function to send a welcome message (detailed in the next chapter)

c. uploads the function of sending welcome message to cloud function .

d. creates an authentication service trigger : select "User Registration" for the event name.

Call the SMS service interface in the cloud function to send SMS

After the user is successfully registered, a welcome text message needs to be sent to the user. Here, we use the 1619140a12c00d short message service text message.

Activate SMS service and set up SMS template

Log in to the AppGallery Connect website and click "My Project".

1. Click your project in the project list.

2. Select "Growth> Short Message Service" to enter the short message service page and complete the following operations:

a. Open SMS service

b. Configure SMS signature

c. Configure SMS template

d. Enable API call

Cloud function calls the SMS service Rest Api interface to send SMS

1. Obtain the user's mobile phone number and user information through the trigger

var phoneNumber = event.phone.slice(4);
var userID = event.uid;
var userName = "认证用户ID" + phoneNumber.slice(11);

2. Call the SMS service Rest Api to send SMS

var requestData = {
        "account": "AGC199",
        "password":"Huawei1234567890!",
        "requestLists": [
          {
            "mobiles":["" + phoneNumber],
            "templateId":"SMS02_21090100001",
            "messageId":"12345",
            "signature":"【PhotoPlaza】"
          }
        ],
        "requestId": "" + curTime
    };
    logger.info("requestData: " + JSON.stringify(requestData));

    var options = {
      hostname: '121.37.23.38',
      port: 18312,
      path: '/common/sms/sendTemplateMessage',
      method: 'POST',
      headers: {
        'Content-Type' : 'application/json'
      },
      rejectUnauthorized: false,
      requestCert: false
    };

    var req = https.request(options, function(res) {
      res.on('data', function(data) {
        var response = JSON.parse(data.toString());
        logger.info('All resultList: ' + JSON.stringify(response.resultLists));
      });

      res.on('end', function(){
        logger.info('RequestResult: success');
        let result = {"message":"Send Message Success"};
        callback(result);
      });

      res.on('error', function(e) {
        logger.info('request error, ' + e.message);
        let result = {"message":"error:" + e.message}
        callback(result);
       });
    });

    req.on('error', function(error) {
      logger.info('request error, ' + error.message);
      let result = {"message":"error:" + e.message}
      callback(result);
    });

    req.write(JSON.stringify(requestData));
    req.end();

Reference documents:

Authentication service mobile account registration:

https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/agc-auth-android-phone-0000001053333941#section16952720551

Cloud function user registration trigger:

https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/agc-cloudfunction-authtrigger-0000001127374643

SMS Service Development Guide:

https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/agc-sms-getstarted-0000001072728865

For more exciting content, please official Huawei developer forum → 1619140a12c180 https://developer.huawei.com/consumer/cn/forum/home?ha_source=sanfang


华为开发者论坛
352 声望57 粉丝

华为开发者论坛是一个为开发者提供信息传播、开发交流、技术分享的交流空间。开发者可以在此获取技术干货、华为源码开放、HMS最新活动等信息,欢迎大家来交流分享!