5分钟快速集成AGC SDK:从零构建HarmonyOS5应用的登录与支付

118 阅读1分钟

以下为 ​​5分钟快速集成AGC SDK实现登录与支付功能的ArkTS代码模板​​,包含完整配置和核心功能实现:


1. 环境准备(1分钟)

1.1 安装依赖

npm install @hw-agconnect/auth @hw-agconnect/iap --save

1.2 配置agconnect-services.json

// agconnect-services.json
{
  "client": {
    "app_id": "你的应用ID",
    "api_key": "你的API密钥"
  },
  "auth": {
    "providers": ["phone", "wechat", "email"]
  },
  "iap": {
    "products": [
      {
        "id": "vip_monthly",
        "type": "subscription"
      }
    ]
  }
}

2. 快速登录集成(2分钟)

2.1 初始化Auth SDK

// auth-init.ets
import { Auth } from '@hw-agconnect/auth';

export const auth = Auth.getInstance({
  persistence: 'local' // 保持登录状态
});

2.2 手机号登录组件

// phone-login.ets
@Component
struct PhoneLogin {
  @State phone: string = '';
  @State code: string = '';

  build() {
    Column() {
      TextInput({ placeholder: '输入手机号' })
        .onChange(v => this.phone = v)
      
      Button('获取验证码')
        .onClick(() => auth.requestSMSCode(this.phone))
      
      TextInput({ placeholder: '验证码' })
        .onChange(v => this.code = v)
      
      Button('登录')
        .onClick(() => this.doLogin())
    }
  }

  private async doLogin() {
    try {
      const user = await auth.signInWithPhone(this.phone, this.code);
      console.log('登录成功:', user.uid);
    } catch (err) {
      console.error('登录失败:', err);
    }
  }
}

2.3 微信快捷登录

// wechat-login.ets
Button('微信登录')
  .onClick(async () => {
    const result = await auth.signInWithWeChat();
    if (result.user) {
      console.log('微信登录成功');
    }
  })

3. 支付功能集成(2分钟)

3.1 初始化IAP SDK

// iap-init.ets
import { IAP } from '@hw-agconnect/iap';

export const iap = IAP.getInstance({
  sandbox: process.env.NODE_ENV === 'development'
});

3.2 商品购买组件

// purchase.ets
@Component
struct VIPPurchase {
  @State products: Product[] = [];

  aboutToAppear() {
    this.loadProducts();
  }

  async loadProducts() {
    this.products = await iap.getProducts(['vip_monthly']);
  }

  build() {
    List() {
      ForEach(this.products, (product) => {
        ListItem() {
          Column() {
            Text(product.name)
            Text(`¥${product.price}`)
            Button('立即购买')
              .onClick(() => this.purchase(product))
          }
        }
      })
    }
  }

  private async purchase(product: Product) {
    try {
      const result = await iap.purchase(product.id);
      if (result.code === 'success') {
        console.log('支付成功:', result.orderId);
      }
    } catch (err) {
      console.error('支付失败:', err);
    }
  }
}

3.3 订单查询

// order-query.ets
Button('查询订单')
  .onClick(async () => {
    const orders = await iap.getPurchases();
    console.log('历史订单:', orders);
  })

4. 安全增强(1分钟)

4.1 支付结果验证

// purchase-verify.ets
async function verifyPayment(orderId: string) {
  const response = await fetch('https://your-server.com/verify', {
    method: 'POST',
    body: JSON.stringify({ orderId })
  });
  
  return response.json().valid;
}

4.2 自动续订处理

// subscription.ets
iap.onSubscriptionChanged((event) => {
  if (event.type === 'renewed') {
    console.log('自动续订成功:', event.productId);
  }
});

5. 完整页面示例

5.1 登录支付一体化

// user-page.ets
@Component
struct UserPage {
  @State loggedIn: boolean = false;
  @State user: User | null = null;

  aboutToAppear() {
    this.checkLogin();
  }

  async checkLogin() {
    this.user = await auth.getCurrentUser();
    this.loggedIn = !!this.user;
  }

  build() {
    Column() {
      if (this.loggedIn) {
        Text(`欢迎 ${this.user?.phone}`)
        VIPPurchase()
      } else {
        PhoneLogin()
        Divider()
        WechatLoginButton()
      }
    }
  }
}

6. 关键配置说明

配置项作用示例值
auth.providers启用登录方式["phone", "wechat"]
iap.products配置可售商品{id: "vip_monthly"}
persistence登录状态保持"local"
sandbox支付测试模式true

7. 常见问题解决

问题现象解决方案代码调整
收不到短信验证码检查AGC控制台短信模板auth.requestSMSCode()
微信登录返回空白确认微信开放平台配置signInWithWeChat()
支付一直失败切换sandbox模式IAP.getInstance()
订单状态不同步实现服务端验证verifyPayment()

通过本方案可实现:

  1. ​3分钟​​ 完成登录接入
  2. ​2分钟​​ 集成支付功能
  3. ​生产级​​ 安全验证
  4. ​无缝​​ 用户状态管理