Flutter支付集成插件easy_ozow的使用

发布于 1周前 作者 gougou168 来自 Flutter

Flutter支付集成插件easy_ozow的使用

特性

  • 生成支付链接
  • 使用WebView的Ozow支付界面
  • 获取支付历史
在应用内支付(WebView) 选择银行 银行授权 支付完成

开始前的要求

在开始之前,你需要有一个有效的Ozow商户账户来获取以下信息:

  • SiteCode
  • ApiKey
  • PrivateKey

使用方法

步骤1 - 初始化包并连接到Ozow

[@override](/user/override)
void initState() {
  super.initState();
  
  easyOzow.init(
    apiKey: "------------------",
    privateKey: "-----------------",
    siteCode: "--------",
    isTest: true,
  );
}

步骤2 - 生成支付链接

void generatePaymentLink() async {
  await easyOzow
      .generatePaymentLink(
    amount: 0.10,  // 输入客户需要支付的金额
    successUrl: "https://dingi.icu/easyOzow/successLink.php",
    cancelUrl: "https://dingi.icu/easyOzow/cancelLink.php",
    errorUrl: "https://dingi.icu/easyOzow/errorLink.php",
    notifyUrl: "https://access.dingi.icu",
  ).then((value) {
    generatedPaymentUrl = value['url'];
  });
}

支付完成后返回的URL示例:

https://dingi.icu/easyOzow/successLink.php?SiteCode=OOOP-OP-32&TransactionId=5bd36283-d36e-47e6-acf7-67b68c0913dc&TransactionReference=RZQIA2&Amount=0.10&Status=Complete&Optional1=&Optional2=&Optional3=&Optional4=&Optional5=&CurrencyCode=ZAR&IsTest=true&StatusMessage=Test+transaction+completed&Hash=8d60f5fb15ac27c830d15140cbde47e2d808ca219a69931c526f4249560775c293af86bdeafbb58c0ae72d578ac2323d4d32f58f6d2ecb7700382122fe7a5037

步骤3 - 使用WebView的Ozow支付界面

OzowPaymentUI( 
  paymentLink: generatedPaymentUrl,
  successScreen: const Success(),
  failedScreen: const Failed(),
  cancelScreen: const Cancel(),
)

完整示例代码

import 'package:easy_ozow/easy_ozow.dart';
import 'package:example/failed.dart';
import 'package:example/success.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:onepref/onepref.dart';
import 'package:url_launcher/url_launcher.dart';
import 'cancel.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  EasyOzow easyOzow = EasyOzow();

  String url = "";
  String generatedPaymentUrl = "";
  bool paymentLinkFound = false;
  bool paymentLinkGenerated = false;
  bool payWithOzow = false;
  bool linkRequested = false;

  final _messangerKey = GlobalKey<ScaffoldMessengerState>();

  final TextEditingController _controller = TextEditingController();

  [@override](/user/override)
  void initState() {
    super.initState();
    easyOzow.init(
      apiKey: "--",
      privateKey: "--",
      siteCode: "---",
      isTest: true,
    );
  }

  void createPayment(int button) async {
    await easyOzow
        .generatePaymentLink(
      amount: double.tryParse(_controller.text) ?? 0.10, // 将字符串转换为double,如果为空则使用0.10
      successUrl: "https://dingi.icu/easyOzow/successLink.php",
      cancelUrl: "https://dingi.icu/easyOzow/cancelLink.php",
      errorUrl: "https://dingi.icu/easyOzow/errorLink.php",
      notifyUrl: "https://access.dingi.icu",
    )
        .then((value) {
      setState(() {
        if (button == 1) {
          paymentLinkGenerated = true;
          generatedPaymentUrl = value['url'];
        } else {
          paymentLinkFound = true;
          url = value['url'];
        }
      });
    });
  }

  Future<void> openUrlBrowser(String link) async {
    final Uri url = Uri.parse(link.trim());
    if (!await launchUrl(
      url,
      mode: LaunchMode.externalApplication,
    )) {
      throw Exception('Could not launch $url');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Easy Ozow',
      scaffoldMessengerKey: _messangerKey,
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.greenAccent),
        useMaterial3: true,
      ),
      home: Scaffold(
          appBar: AppBar(
            title: const Text("Easy Ozow"),
            backgroundColor: Colors.greenAccent,
          ),
          body: payWithOzow
              ? initPayment()
              : Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      const SizedBox(
                        height: 20,
                      ),
                      paymentLinkGenerated
                          ? Column(
                              children: [
                                Center(
                                    child: Padding(
                                  padding: const EdgeInsets.only(
                                      right: 20.0, left: 20.0),
                                  child: Container(
                                    decoration: BoxDecoration(
                                      color: Colors.greenAccent.withOpacity(0.2),
                                    ),
                                    child: Padding(
                                      padding: const EdgeInsets.symmetric(
                                          vertical: 8.0),
                                      child: Text(
                                        generatedPaymentUrl,
                                        textAlign: TextAlign.center,
                                      ),
                                    ),
                                  ),
                                )),
                                Container(
                                  margin: const EdgeInsets.symmetric(
                                      horizontal: 40, vertical: 15),
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceAround,
                                    children: [
                                      OnClickAnimation(
                                        onTap: () => {
                                          if (generatedPaymentUrl
                                              .contains("pay.ozow.com"))
                                            {
                                              openUrlBrowser(
                                                  generatedPaymentUrl)
                                            },
                                        },
                                        child: const Text(
                                          "Open Link",
                                          style: TextStyle(
                                            color: Colors.blue,
                                          ),
                                        ),
                                      ),
                                      OnClickAnimation(
                                        onTap: () {
                                          Clipboard.setData(ClipboardData(
                                                  text: generatedPaymentUrl))
                                              .then((_) {
                                            _messangerKey.currentState!
                                                .showSnackBar(const SnackBar(
                                                    content: Text(
                                                        "Payment Link copied to clipboard")));
                                          });
                                        },
                                        child: const Text(
                                          "Copy Link",
                                          style: TextStyle(
                                            color: Colors.blue,
                                          ),
                                        ),
                                      )
                                    ],
                                  ),
                                )
                              ],
                            )
                          : Visibility(
                              visible: linkRequested,
                              child: const CircularProgressIndicator()),
                      const SizedBox(
                        height: 20,
                      ),
                      Container(
                        margin: const EdgeInsets.all(30),
                        child: TextField(
                          controller: _controller,
                          decoration: const InputDecoration(
                            hintText: "Amount",
                            helperText: "e.g 12.00",
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: () => {
                          setState(() {
                            linkRequested = true;
                          }),
                          createPayment(1)
                        },
                        child: const Text(
                          "Generate Payment Link",
                          style: TextStyle(
                            color: Colors.blue,
                          ),
                        ),
                      ),
                      const SizedBox(
                        height: 25,
                      ),
                      GestureDetector(
                        onTap: () => {
                          setState(() {
                            payWithOzow = true;
                          }),
                          createPayment(2)
                        },
                        child: Container(
                          color: Colors.greenAccent,
                          padding: const EdgeInsets.only(
                            right: 20,
                            left: 20,
                            top: 5,
                            bottom: 5,
                          ),
                          child: const Text(
                            "Pay with Ozow",
                            style: TextStyle(
                              color: Colors.black,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                )),
    );
  }

  Widget initPayment() {
    return paymentLinkFound
        ? OzowPaymentUI(
            paymentLink: url,
            successScreen: const Success(),
            failedScreen: const Failed(),
            cancelScreen: const Cancel(),
          )
        : const Center(child: CircularProgressIndicator());
  }
}

更多关于Flutter支付集成插件easy_ozow的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter支付集成插件easy_ozow的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter项目中集成easy_ozow支付插件,可以通过以下步骤实现。easy_ozow是一个用于集成Ozow支付服务的Flutter插件。下面是一个简单的代码案例,展示如何在Flutter应用中集成并使用该插件。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加easy_ozow依赖:

dependencies:
  flutter:
    sdk: flutter
  easy_ozow: ^最新版本号  # 请替换为实际的最新版本号

然后运行flutter pub get来安装依赖。

2. 配置Android和iOS

确保你已经在Android和iOS项目中配置了必要的支付信息,如API密钥等。这通常涉及在各自的平台配置文件中添加敏感信息,比如AndroidManifest.xmlInfo.plist。但具体配置步骤依赖于easy_ozow插件的文档和Ozow服务的要求,这里不详细展开。

3. 初始化插件并发起支付请求

在你的Flutter代码中,你可以按照以下方式初始化easy_ozow插件并发起支付请求:

import 'package:flutter/material.dart';
import 'package:easy_ozow/easy_ozow.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Ozow Payment Integration'),
        ),
        body: Center(
          child: PaymentButton(),
        ),
      ),
    );
  }
}

class PaymentButton extends StatefulWidget {
  @override
  _PaymentButtonState createState() => _PaymentButtonState();
}

class _PaymentButtonState extends State<PaymentButton> {
  void _initiatePayment() async {
    try {
      // 假设你已经从后端获取了支付所需的参数
      final paymentDetails = PaymentDetails(
        merchantId: '你的商户ID',
        amount: 100.0, // 支付金额,单位通常是南非兰特(ZAR)
        currency: 'ZAR',
        returnUrl: 'https://yourapp.com/return', // 支付完成后返回的URL
        notifyUrl: 'https://yourapp.com/notify', // 支付通知的URL
        // 其他必要的支付参数...
      );

      final result = await EasyOzow.initiatePayment(paymentDetails);

      if (result.status == PaymentStatus.success) {
        // 支付成功处理逻辑
        print('Payment successful!');
      } else if (result.status == PaymentStatus.failed) {
        // 支付失败处理逻辑
        print('Payment failed: ${result.errorMessage}');
      } else if (result.status == PaymentStatus.pending) {
        // 支付待处理逻辑(可能需要用户操作)
        print('Payment pending...');
      }
    } catch (e) {
      // 错误处理
      print('Error initiating payment: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: _initiatePayment,
      child: Text('Initiate Payment'),
    );
  }
}

// 假设的PaymentDetails和PaymentResult类(根据实际插件提供的API调整)
class PaymentDetails {
  final String merchantId;
  final double amount;
  final String currency;
  final String returnUrl;
  final String notifyUrl;
  // 其他字段...

  PaymentDetails({
    required this.merchantId,
    required this.amount,
    required this.currency,
    required this.returnUrl,
    required this.notifyUrl,
    // 其他参数...
  });
}

enum PaymentStatus { success, failed, pending }

class PaymentResult {
  final PaymentStatus status;
  final String? errorMessage;

  PaymentResult({required this.status, this.errorMessage});
}

注意:上面的PaymentDetailsPaymentResultPaymentStatusEasyOzow.initiatePayment方法是假设的,实际使用时需要参考easy_ozow插件的官方文档和API。特别是EasyOzow类的具体方法和参数可能会有所不同。

4. 处理支付回调

根据你的应用需求,你可能需要在returnUrlnotifyUrl指定的页面上处理支付回调。这通常涉及验证支付状态并更新用户的应用状态。

总结

上述代码提供了一个基本的框架,展示了如何在Flutter应用中使用easy_ozow插件发起支付请求。实际使用时,请务必参考easy_ozow插件的官方文档,并根据你的具体需求进行调整。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!