Google Pay API สำหรับ Flutter ใน Android

1. บทนำ

สิ่งที่คุณจะสร้าง

เมื่อทำ Codelab นี้เสร็จแล้ว คุณจะมีแอป Flutter ที่นำเสนอเพียงคุณสมบัติหลักๆ พร้อมการผสานรวม Google Pay ที่ใช้งานได้สำหรับ Android โปรเจ็กต์นี้จะดึงโทเค็นการชำระเงินซึ่งอาจส่งไปยังผู้ให้บริการชำระเงินเพื่อประมวลผล

สิ่งที่คุณจะได้เรียนรู้

  • วิธีติดตั้งและกำหนดค่าไลบรารี Flutter ของ Google Pay
  • วิธีแสดงปุ่ม Google Pay และจัดการการคลิก
  • วิธีขอโทเค็นการชำระเงินจาก Google Pay

สิ่งที่คุณต้องมี

  • โปรแกรมแก้ไขข้อความที่คุณเลือกเพื่อแก้ไขไฟล์ Dart
  • สภาพแวดล้อมในการพัฒนา Flutter ที่ตั้งค่าไว้สำหรับ Android
  • สำหรับเวอร์ชันที่ใช้งานจริง คุณจะต้องมี Google Pay merchantId การลงทะเบียนใน Google Pay และ Wallet Console ใช้เวลาเพียง 1 นาที ดังนั้นคุณควรดำเนินการให้เรียบร้อยในตอนนี้

2. สร้างโปรเจ็กต์ Flutter

สร้างไฟล์โปรเจ็กต์

  1. สร้างโปรเจ็กต์ Flutter ใหม่ชื่อ googlepay_flutter
    flutter create googlepay_flutter
    
  2. ติดตั้งไลบรารี Flutter ของ Google Pay
    cd googlepay_flutter
    flutter pub add pay
    
  3. เปิด lib/main.dart ใน IDE ที่คุณเลือก แล้วแทนที่เนื้อหาด้วยโค้ดต่อไปนี้
    import 'package:flutter/material.dart';
    
    void main() => runApp(const MyApp());
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          home: PaySampleApp(),
        );
      }
    }
    
    class PaySampleApp extends StatefulWidget {
      const PaySampleApp({super.key});
    
      @override
      State<PaySampleApp> createState() => _PaySampleAppState();
    }
    
    class _PaySampleAppState extends State<PaySampleApp> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Google Pay Codelab'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text('Transaction info and errors will be logged to the console.'),
              ],
            ),
          ),
        );
      }
    }
    

3. กำหนดค่า Google Pay

คำขอการชำระเงินด้วย Google Pay ต้องมีออบเจ็กต์คำขอ ออบเจ็กต์ที่กำหนดไว้ที่นี่เป็น _paymentItems มีการตั้งค่าทั่วไปขั้นต่ำสำหรับคำขอทั้งหมด ระบบจะเพิ่มการตั้งค่าเพิ่มเติมตามคำขอที่ส่งมา ซึ่งเราจะตรวจสอบใน Codelab นี้

  1. เพิ่มค่าคงที่ของการกำหนดค่า Google Pay ลงใน lib/main.dart ดังนี้
import 'package:pay/pay.dart';

const _paymentItems = [
  PaymentItem(
    label: 'Total',
    amount: '14.95',
    status: PaymentItemStatus.final_price,
  )
];
  1. เพิ่ม JSON การกำหนดค่าการชำระเงินเริ่มต้นไปยังเส้นทาง assets/google_pay_config.json
  {
    "provider": "google_pay",
    "data": {
      "environment": "TEST",
      "apiVersion": 2,
      "apiVersionMinor": 0,
      "allowedPaymentMethods": [
        {
          "type": "CARD",
          "tokenizationSpecification": {
            "type": "PAYMENT_GATEWAY",
            "parameters": {
              "gateway": "example",
              "gatewayMerchantId": "exampleGatewayMerchantId"
            }
          },
          "parameters": {
            "allowedCardNetworks": ["VISA", "MASTERCARD"],
            "allowedAuthMethods": ["PAN_ONLY", "CRYPTOGRAM_3DS"],
            "billingAddressRequired": true,
            "billingAddressParameters": {
              "format": "FULL",
              "phoneNumberRequired": true
            }
          }
        }
      ],
      "merchantInfo": {
        "merchantName": "Example Merchant Name"
      },
      "transactionInfo": {
        "countryCode": "US",
        "currencyCode": "USD"
      }
    }
  }

แหล่งข้อมูล

  • เอกสารอ้างอิง API: เอกสารประกอบเกี่ยวกับออบเจ็กต์คำขอของ Google Pay API
  • ข้อมูลอ้างอิง API: ดูข้อมูลเพิ่มเติมเกี่ยวกับวิธีการให้สิทธิ์ที่อนุญาต เครือข่ายบัตรที่อนุญาต และข้อกำหนดการแปลงโทเค็น รวมถึงค่าเกตเวย์ที่เหมาะสมได้ที่ PaymentMethod

4. เพิ่มปุ่ม Google Pay

ไลบรารี pay มีคอมโพเนนต์ปุ่ม Google Pay แบบเนทีฟ

อัปเดตคลาส _PaySampleAppState ใน lib/main.dart ด้วยโค้ดต่อไปนี้

class _PaySampleAppState extends State<PaySampleApp> {
  late final Future<PaymentConfiguration> _gpayConfig;

  void onGooglePayResult(paymentResult) {
    // Send 'token' to your payment service provider (PSP)
    print(paymentResult);
  }

  @override
  void initState() {
    super.initState();
    _gpayConfig = PaymentConfiguration.fromAsset('google_pay_config.json');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Google Pay Codelab')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FutureBuilder<PaymentConfiguration>(
              future: _gpayConfig,
              builder: (context, snapshot) {
                if (snapshot.connectionState != ConnectionState.done) {
                  return const Center(child: CircularProgressIndicator());
                }
                if (snapshot.hasError || !snapshot.hasData) {
                  return const Text('Error loading Google Pay config');
                }
                return GooglePayButton(
                  paymentConfiguration: snapshot.data!,
                  onPaymentResult: onGooglePayResult,
                  paymentItems: _paymentItems,
                  height: 48,
                  type: GooglePayButtonType.buy,
                  theme: GooglePayButtonTheme.dark,
                  margin: const EdgeInsets.only(top: 15.0),
                  loadingIndicator: const Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              },
            ),
            const Text('Transaction info and errors will be logged to the console.'),
          ],
        ),
      ),
    );
  }
}

คำอธิบายโค้ด

  1. _paymentItems อธิบายธุรกรรมที่ควรประมวลผลเมื่อคลิกปุ่มนี้
  2. paymentConfigurationAsset ในวิดเจ็ต GooglePayButton จะโหลดการกำหนดค่าจากไฟล์ assets/google_pay_config.json
  3. เมื่อกด GooglePayButton ระบบจะเรียกใช้ฟังก์ชัน onGooglePayResult ฟังก์ชันนี้จะรับผลการชำระเงิน
  4. เมื่อได้รับโทเค็นการชำระเงินจากคำตอบแล้ว คุณจะต้องส่งโทเค็นดังกล่าวไปยังเกตเวย์การชำระเงินเพื่อประมวลผลธุรกรรม

5. ทริกเกอร์การชำระเงินเมื่อมีการคลิก

การแตะ GooglePayButton จะเปิดชีต Google Pay และแสดงผลลัพธ์ โดยไม่ต้องเรียกใช้ "ชำระเงิน" แยกต่างหาก เพิ่มตัวแฮนเดิลเพื่อบันทึกโทเค็น แสดงข้อผิดพลาด และบันทึกการกดปุ่ม (ไม่บังคับ)

  1. เพิ่มหรืออัปเดตตัวแฮนเดิลผลลัพธ์ภายใน _PaySampleAppState ดังนี้
void onGooglePayResult(dynamic paymentResult) {
  try {
    final token = paymentResult['paymentMethodData']['tokenizationData']['token'];
    debugPrint('Google Pay payment token: $token');
  } catch (e) {
    debugPrint('Unexpected payment result: $e');
  }
}
  1. อัปเดต GooglePayButton ให้รวมตัวแฮนเดิลการกดและข้อผิดพลาด
GooglePayButton(
  paymentConfiguration: snapshot.data!,
  paymentItems: _paymentItems,
  onPaymentResult: onGooglePayResult,
  onError: (Object err) => debugPrint('Google Pay error: $err'),
  onPressed: () => debugPrint('Google Pay button pressed'),
  height: 48,
  type: GooglePayButtonType.buy,
  theme: GooglePayButtonTheme.dark,
  margin: const EdgeInsets.only(top: 15.0),
  loadingIndicator: const Center(child: CircularProgressIndicator()),
)

หมายเหตุ

  • การแตะจะทริกเกอร์ชีตการชำระเงิน และ onPaymentResult จะได้รับเพย์โหลด
  • ในเวอร์ชันที่ใช้งานจริง ให้ส่งโทเค็นไปยังผู้ให้บริการชำระเงินเพื่อเรียกเก็บเงินให้เสร็จสมบูรณ์

6. บทสรุป

ขอแสดงความยินดีที่ทำ Codelab นี้เสร็จสมบูรณ์ คุณได้เรียนรู้วิธีผสานรวม Google Pay API เข้ากับแอป Flutter สำหรับ Android แล้ว

เรียกใช้โปรเจ็กต์

เรียกใช้คำสั่งต่อไปนี้เพื่อเริ่มแอป

flutter run

ขั้นตอนถัดไป

แหล่งข้อมูลเพิ่มเติม