fish 1 week ago
parent
commit
b21a7159de
2 changed files with 109 additions and 31 deletions
  1. 10 10
      lib/pages/home_page.dart
  2. 99 21
      lib/service/pay_service.dart

+ 10 - 10
lib/pages/home_page.dart

@@ -16,32 +16,32 @@ class _HomePageState extends State<HomePage> {
     return Scaffold(
     return Scaffold(
       appBar: AppBar(
       appBar: AppBar(
         actions: [],
         actions: [],
-        title: Text("主页"),
+        title: const Text("主页"),
       ),
       ),
       body: Column(
       body: Column(
         children: [
         children: [
-          Text("支付演示"),
-          Text("商品名称: 橘子"),
-          Text("数量:1斤"),
-          Text("单价:11元/斤"),
-          Text("总价:11元"),
+          const Text("支付演示"),
+          const Text("商品名称: 橘子"),
+          const Text("数量:1斤"),
+          const Text("单价:11元/斤"),
+          const Text("总价:11元"),
           Row(
           Row(
             children: [
             children: [
               ElevatedButton(
               ElevatedButton(
                 onPressed: () {},
                 onPressed: () {},
-                child: Text("微信支付"),
+                child: const Text("微信支付"),
               ),
               ),
               ElevatedButton(
               ElevatedButton(
                 onPressed: () {},
                 onPressed: () {},
-                child: Text("支付宝支付"),
+                child: const Text("支付宝支付"),
               ),
               ),
               ElevatedButton(
               ElevatedButton(
                 onPressed: () {},
                 onPressed: () {},
-                child: Text("Google支付"),
+                child: const Text("Google支付"),
               ),
               ),
               ElevatedButton(
               ElevatedButton(
                 onPressed: () {},
                 onPressed: () {},
-                child: Text("Stripe支付"),
+                child: const Text("Stripe支付"),
               ),
               ),
             ],
             ],
           ),
           ),

+ 99 - 21
lib/service/pay_service.dart

@@ -1,7 +1,9 @@
-// import 'package:fluwx/fluwx.dart' as fluwx;
+import 'package:fluwx/fluwx.dart' as fluwx;
 // import 'package:flutter_alipay/flutter_alipay.dart';
 // import 'package:flutter_alipay/flutter_alipay.dart';
 // import 'package:stripe_payment/stripe_payment.dart';
 // import 'package:stripe_payment/stripe_payment.dart';
 
 
+import 'package:flutter_paydemo/models/payment.dart';
+
 class PayService {
 class PayService {
   PayService._();
   PayService._();
 
 
@@ -22,35 +24,111 @@ class PayService {
     );
     );
   }
   }
 
 
-  void wechatPay() async {
+  void wechatPay(PaymentProduct product) async {
     bool isInstalled = await fluwx.isWeChatAppInstalled();
     bool isInstalled = await fluwx.isWeChatAppInstalled();
-    if (isInstalled) {
-      fluwx
-          .pay(fluwx.PayInfo(
-        appId: 'your_app_id',
-        partnerId: 'your_partner_id',
-        prepayId: 'your_prepay_id',
-        packageValue: 'Sign=WXPay',
-        nonceStr: 'your_nonce_str',
-        timeStamp: 'your_timestamp',
-        sign: 'your_sign',
-      ))
-          .then((response) {
-        // 处理支付结果
-      });
-    } else {
-      // alert('未安装微信');
+    try {
+      final created = await APIServer().createWechatPayment(
+        productId: product.id,
+        source: paymentSource(),
+      );
+      paymentId = created.paymentId;
+
+      if (PlatformTool.isAndroid() || PlatformTool.isIOS()) {
+        await fluwx.payWithWeChat(
+          appId: created.appId!,
+          partnerId: created.partnerId!,
+          prepayId: created.prepayId!,
+          packageValue: created.package!,
+          nonceStr: created.noncestr!,
+          timeStamp: int.parse(created.timestamp!),
+          sign: created.sign!,
+        );
+      } else {
+        openDialog(
+          // ignore: use_build_context_synchronously
+          context,
+          builder: Builder(builder: (context) {
+            return Container(
+              alignment: Alignment.center,
+              height: 250,
+              width: 220,
+              margin: const EdgeInsets.only(top: 20),
+              child: Column(
+                children: [
+                  ClipRRect(
+                    borderRadius: BorderRadius.circular(8),
+                    child: QrImageView(
+                      data: created.codeUrl!,
+                      version: QrVersions.auto,
+                      size: 200,
+                      backgroundColor: Colors.white,
+                    ),
+                  ),
+                  const SizedBox(height: 10),
+                  const Text(
+                    '请使用微信扫码支付',
+                    style: TextStyle(
+                      fontSize: 14,
+                    ),
+                  ),
+                ],
+              ),
+            );
+          }),
+          onSubmit: () {
+            _startPaymentLoading();
+            APIServer().queryPaymentStatus(created.paymentId).then((resp) {
+              if (resp.success) {
+                showSuccessMessage(resp.note ?? '支付成功');
+                _closePaymentLoading();
+              } else {
+                // 支付失败,延迟 5s 再次查询支付状态
+                Future.delayed(const Duration(seconds: 5), () async {
+                  try {
+                    final value =
+                        await APIServer().queryPaymentStatus(created.paymentId);
+
+                    if (value.success) {
+                      showSuccessMessage(value.note ?? '支付成功');
+                    } else {
+                      showErrorMessage('支付未完成,我们接收到的状态为:${value.note}');
+                    }
+                  } catch (e) {
+                    // ignore: use_build_context_synchronously
+                    showErrorMessage(resolveError(context, e));
+                  } finally {
+                    _closePaymentLoading();
+                  }
+                });
+              }
+            });
+
+            return true;
+          },
+          confirmText: '已完成支付',
+          barrierDismissible: false,
+        );
+      }
+    } on Exception catch (e) {
+      // ignore: use_build_context_synchronously
+      showErrorMessageEnhanced(context, e);
+    } finally {
+      _closePaymentLoading();
     }
     }
   }
   }
 
 
   void alipay() async {
   void alipay() async {
     String orderString = 'your_order_string'; // 从服务器获取
     String orderString = 'your_order_string'; // 从服务器获取
-    var result = await FlutterAlipay.pay(orderString);
+    // var result = await FlutterAlipay.pay(orderString);
   }
   }
 
 
   void stripe() async {
   void stripe() async {
-    var token = await StripePayment.paymentRequestWithCardForm(
-        CardFormPaymentRequest());
+    // var token = await StripePayment.paymentRequestWithCardForm(
+    //     CardFormPaymentRequest());
     // 发送 token 到服务器进行支付处理
     // 发送 token 到服务器进行支付处理
   }
   }
+
+  Future<WechatPaymentCreatedResponse> sendPostRequest(
+      String s, WechatPaymentCreatedResponse Function(dynamic resp) param1,
+      {required Map<String, String?> formData}) {}
 }
 }