AppGallery Connect場景化開發實戰—注冊訂閱通知


借助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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM