开发功能

86 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第26天,点击查看活动详情

开发功能

1.开发应用布局如下。

image-20221219042349231

2.在“login.ets”文件中导入我们需要用到的包。

import agconnect from '@hw-agconnect/api-ohos';
import "@hw-agconnect/core-ohos";
import "@hw-agconnect/auth-ohos";
import { EmailAuthProvider, VerifyCodeAction, EmailUserBuilder, VerifyCodeSettingBuilder, PhoneUserBuilder,
  PhoneAuthProvider, AGConnectAuth, AGConnectAuthCredentialProvider
} from "@hw-agconnect/auth-ohos"import { Logger } from "@hw-agconnect/base-ohos"

3.接收在“MainAbility.ts”文件中实例化的auth对象。

let auth: AGConnectAuth = globalThis.auth;

4.login.ets

/*
 * Copyright (c) 2021 JianGuo Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
​
​
import {
  AGConnectAuth,
  VerifyCodeAction,
  VerifyCodeSettingBuilder,
  PhoneAuthProvider,
  EmailAuthProvider
} from '@ohos/agconnect-auth';
import { Logger } from '@ohos/agconnect-base';
import prompt from '@ohos.prompt';
​
let auth: AGConnectAuth = globalThis.auth;
let TAG: string = "坚果";
​
import router from '@system.router'
​
@Extend(Text) function text_style () {
  .width('18%')
  .fontFamily($r('sys.float.ohos_id_text_size_body2'))
  .fontSize(15)
  .maxLines(1)
}
​
@Extend(Text) function link_text_style (fontSize: number) {
  .fontSize(fontSize)
  .fontColor($r('app.color.blue_link'))
  .fontFamily($r('sys.float.ohos_id_text_size_body2'))
  .maxLines(1)
}
​
@Extend(Text) function unlink_text_style (fontSize: number) {
  .fontSize(fontSize)
  .fontColor($r('app.color.black'))
  .fontFamily($r('sys.float.ohos_id_text_size_body2'))
  .maxLines(1)
}
​
​
@Extend(TextInput) function input_style () {
  .width('50%')
  .fontFamily($r('sys.float.ohos_id_text_size_body2'))
  .fontSize(15)
  .placeholderFont({ size: 15, family: $r('sys.float.ohos_id_text_size_body2') })
  .placeholderColor($r('app.color.grey3'))
  .caretColor($r('app.color.green0'))
  .backgroundColor(Color.White)
}
​
@Extend(Divider) function divider_style () {
  .width('90%')
  .color($r('app.color.grey2'))
  .strokeWidth(0.8)
}
​
@Entry
@Component
struct Login {
  @State title: string = 'OpenHarmony集成认证服务'
  @State state: string = '未登录'
  @State verifyCode: string = ''
  @State result: string = 'Hello World'
  @State email: string = '17752170152@163.com'
  @State phone: string = '17752170152'//获取邮箱验证码
  requestEmailVerifyCode(){
    // 申请邮箱验证码配置参数
    let verifyCodeSettings = new VerifyCodeSettingBuilder()
      .setAction(VerifyCodeAction.REGISTER_LOGIN)
      .setLang('zh_CN')
      .setSendInterval(60)
      .build();
    // 发送请求获取邮箱验证码
    auth.requestEmailVerifyCode(this.email, verifyCodeSettings).then(res => {
      Logger.info(TAG, "请求邮箱验证码成功!result: " + JSON.stringify(res));
      this.result = "请求邮箱验证码成功!result: " + JSON.stringify(res);
      prompt.showToast({ message: "验证码发送成功" })
​
    }).catch(err => {
      Logger.error(TAG, "请求邮箱验证码失败!error: " + JSON.stringify(err));
      this.result = "请求邮箱验证码失败!error: " + JSON.stringify(err);
    })
  }
//获取电话验证码
  requestPhoneVerifyCode(){
    // 申请电话验证码配置参数
    let verifyCodeSettings = new VerifyCodeSettingBuilder()
      .setAction(VerifyCodeAction.REGISTER_LOGIN)
      .setLang('zh_CN')
      .setSendInterval(60)
      .build();
    // 发送请求获取电话验证码
    auth.requestPhoneVerifyCode("86", "17752170152", verifyCodeSettings).then(res => {
      Logger.info(TAG, "请求邮箱验证码成功!result: " + JSON.stringify(res));
      this.result = "请求邮箱验证码成功!result: " + JSON.stringify(res);
      prompt.showToast({ message: "验证码发送成功" })
​
    }).catch(err => {
      Logger.error(TAG, "请求邮箱验证码失败!error: " + JSON.stringify(err));
      this.result = "请求邮箱验证码失败!error: " + JSON.stringify(err);
    })
  }
​
​
  signInEmail(){
    // 通过邮箱和验证码获取凭证
    let credential = EmailAuthProvider.credentialWithVerifyCode(this.email, this.verifyCode);
    // 登录接口,通过第三方认证来登录AGConnect平台
    auth.signIn(credential).then(res => {
      Logger.info(TAG, "登录成功!result: " + JSON.stringify(res));
      this.result = "登录成功!result: " + res.getUser().getUid();
​
      router.push({ uri: 'pages/MainPage' })
      prompt.showToast({ message: "邮箱登录成功" })
    }).catch(err => {
      Logger.error(TAG, "登录失败!error: " + JSON.stringify(err));
      this.result = "登录失败!error: " + JSON.stringify(err);
    })
  }
​
  signInPhone(){
    // 通过邮箱和验证码获取凭证
    let credential = PhoneAuthProvider.credentialWithVerifyCode("86", this.phone, this.verifyCode);
    // 登录接口,通过第三方认证来登录AGConnect平台
    auth.signIn(credential).then(res => {
      Logger.info(TAG, "登录成功!result: " + JSON.stringify(res));
      this.result = "登录成功!result: " + res.getUser().getUid();
      router.push({ uri: 'pages/MainPage' })
      prompt.showToast({ message: "短信登录成功" })
    }).catch(err => {
      Logger.error(TAG, "登录失败!error: " + JSON.stringify(err));
      this.result = "登录失败!error: " + JSON.stringify(err);
    })
  }
​
  signOut(){
  //退出接口
  auth.signOut().then(res => {
  Logger.info(TAG, "退出登录!result: " + JSON.stringify(res));
  this.result = "退出登录!result: ";
}).catch(err => {
  Logger.error(TAG, "登录失败!error: " + JSON.stringify(err));
  this.result = "退出登录失败!error: " + JSON.stringify(err);
})
}
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
​
      Column() {
        Text(this.title)
          .textAlign(TextAlign.Center)
          .fontSize(22)
          .fontFamily($r('sys.float.ohos_id_text_size_body2')).margin({ bottom: 10 })
​
​
      }.width('100%').height(130).padding({ top: 55 })
​
      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
​
​
​
​
        //手机号
        Row() {
          Text($r('app.string.login_phone'))
            .text_style()
​
​
​
      TextInput({ placeholder: $r('app.string.login_phone_tips') })
            .input_style()
            .type(InputType.Number)
            .onChange((value: string) => {
              console.log("输入的数据是" + value) // 输入发生变化时,触发回调
              this.phone = value;
            })
          Button( "短信验证吗", { type: ButtonType.Normal })
            .width(130)
            .height(40)
            .backgroundColor($r("app.color.morandi2_alpha"))
            .fontSize(18)
            .fontColor($r("app.color.controlFocusFg_alpha"))
            .borderRadius(10).margin({left:10})
            .onClick(() => {
              this.requestPhoneVerifyCode()
            }
            )
​
        }.width('90%').height(60).margin({ bottom: 4 })
​
        Divider().divider_style()
        //邮箱
        Row() {
          Text($r('app.string.login_email'))
            .text_style()
          TextInput({ placeholder: $r('app.string.login_email_tips') })
            .input_style()
            .type(InputType.Number)
            .onChange((value: string) => {
              console.log("输入的数据是" + value) // 输入发生变化时,触发回调
              this.phone = value;
            })
          Button( "邮箱验证吗", { type: ButtonType.Normal })
            .width(130)
            .height(40)
            .backgroundColor($r("app.color.morandi2_alpha"))
            .fontSize(18)
            .fontColor($r("app.color.controlFocusFg_alpha"))
            .borderRadius(10).margin({left:10})
            .onClick(() => {
              this.requestEmailVerifyCode()
            }
            )
        }.width('90%').height(60).margin({ bottom: 4 })
​
        Divider().divider_style()
        //验证码
        Row() {
          Text($r('app.string.login_code'))
            .text_style()
          TextInput({ placeholder: $r('app.string.login_country_tips') })
            .input_style()
            .onChange((value: string) => {
              console.log("输入的数据是" + value) // 输入发生变化时,触发回调
              this.verifyCode = value;
            })
​
        }.width('90%').height(60).margin({ bottom: 4, top: 4 })
​
​
        Divider().divider_style()
        //随便逛逛
        Row() {
          Text($r('app.string.login_go'))
            .link_text_style(15)
        }.width('90%').height(50).margin({ left: 2, top: 10 })
      }.width('100%').height(200).padding({ top: 20 })
      /**
       * 底部登陆按钮和说明
       * 底部对齐方式
       */
      Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.End, alignItems: ItemAlign.Center }) {
​
        //登陆按钮
        Button($r('app.string.login_button'), {})
          .width("80%")
          .height(80)
          .backgroundColor($r("app.color.morandi2_alpha"))
          .fontSize(18)
          .fontColor($r("app.color.white"))
          .borderRadius(8)
          .margin({ top: 30, bottom: 100 })
          .onClick(() => {
            this.signInPhone()
            this.signInEmail()
​
            Logger.info(TAG, "登录成功!result: " + this.phone);
          })
​
        //登陆按钮
        Button("退出", {})
          .width("80%")
          .height(80)
          .backgroundColor($r("app.color.morandi2_alpha"))
          .fontSize(18)
          .fontColor($r("app.color.white"))
          .borderRadius(8)
          .margin({ top: 30, bottom: 50 })
          .onClick(() => {
            this.signOut()
​
          })
        Row() {
​
          Image($r("app.media.chat",)).width(50).height(50).objectFit(ImageFit.Contain).margin({ right: 80 })
          Image($r("app.media.qq",)).width(50).height(50).objectFit(ImageFit.Contain)
​
        }
        //底部说明页脚
        Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.End, justifyContent: FlexAlign.Center }) {
          Text($r('app.string.login_read'))
            .unlink_text_style(12)
            .margin({ right: 5 })
​
          Text($r('app.string.user_agree'))
            .link_text_style(12)
            .margin({ right: 5 })
          Text('和')
            .unlink_text_style(12)
            .margin({ right: 5 })
          Text($r('app.string.privacy_policy'))
            .link_text_style(12)
        }.width('100%').padding({ bottom: 30, top: 60 })
      }.width('100%').layoutWeight(1)
    }.width('100%').height('100%').backgroundColor($r('app.color.grey0'))
  }
}

打包测试

1.在DevEco Studio的“file > Project Structure”中选择“Project > Signing Configs”。勾选“Automatically generate signature”来进行自动签名。

2.在dayu200中安装应用。