developer-huawei

借助AppGallery Connect(以下简称AGC)的认证服务,云函数,短信服务等服务,当用户注册成功后,便可以在注册的手机号或者邮箱地址中收到一条应用的欢迎短信或者欢迎邮件。以便让开发者更快地融入到应用中并第一时间知晓应用的热点内容。

实现流程

接入认证服务手机号码和邮箱认证方式

首先我们需要通过接入认证服务来打造应用的帐号系统。

启用认证服务

1、登录AppGallery Connect网站,点击“我的项目”。

2、在项目列表中点击您的项目。选择“构建 > 认证服务”,

3、进入认证服务页面,完成如下操作:

a. 开通认证服务

b. 启用手机号码和邮箱地址认证方式

开发手机号码认证方式

由于邮箱地址认证方式与手机号码认证方式的开发过程高度相似,我们这里就举手机号码认证方式为例。

1、首先我们需要调用sendVerifyCode方法获取验证码用于注册:

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、而后我们调用createUser方法进行用户注册

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、对于已注册过的用户我们就可以调用signin方法进行登录操作

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());
    });
}

在云函数中设置认证服务注册成功触发器

上述操作完成后,您需在云函数中配置认证服务触发器。

1、登录AppGallery Connect网站,点击“我的项目”。

2、在项目列表中点击您的项目。选择“构建 > 云函数”,进入云函数页面,完成如下操作:

a. 启用云函数服务

b. 创建发送欢迎短信的函数(下一章节详细介绍)

c. 将发送欢迎短信的函数上传至云函数

d. 创建认证服务触发器:事件名称选择“用户注册”。

云函数中调用短信服务接口发送短信

在用户注册成功后需要对用户发送欢迎短信,此处短信我们使用AGC提供的短信服务发送。

开通短信服务并设置短信模板

登录AppGallery Connect网站,点击“我的项目”。

1、在项目列表中点击您的项目。

2、选择“增长 > 短信服务”,进入短信服务页面,完成如下操作:

a. 开通短信服务

b. 配置短信签名

c. 配置短信模板

d. 启用API调用

云函数调用短信服务Rest Api接口发送短信

1、通过触发器获取用户的手机号码及用户信息

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

2、调用短信服务Rest Api发送短信

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();

参考文档:

认证服务手机帐号注册:

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

云函数用户注册触发器:

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

短信服务开发指南:

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

更多精彩内容,请见华为开发者官方论坛→https://developer.huawei.com/consumer/cn/forum/home?ha_source=sanfang

分类:

技术点:

相关文章: