apple_pay_method_channel.dart 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import 'package:flutter/foundation.dart';
  2. import 'package:flutter/services.dart';
  3. import 'apple_pay_platform_interface.dart';
  4. /// An implementation of [ApplePayPlatform] that uses method channels.
  5. class MethodChannelApplePay extends ApplePayPlatform {
  6. /// The method channel used to interact with the native platform.
  7. @visibleForTesting
  8. final methodChannel = const MethodChannel('apple_pay');
  9. @override
  10. Future<String?> getPlatformVersion() async {
  11. final version = await methodChannel.invokeMethod<String>('getPlatformVersion');
  12. return version;
  13. }
  14. @override
  15. Future<Map<String, dynamic>> purchase({
  16. required String productId,
  17. String? appAccountToken,
  18. }) async {
  19. try {
  20. final result = await methodChannel.invokeMethod<Map<dynamic, dynamic>>(
  21. 'purchase',
  22. {
  23. 'appleId': productId,
  24. 'appAccountToken': appAccountToken,
  25. },
  26. );
  27. return result?.cast<String, dynamic>() ?? {
  28. 'success': false,
  29. 'error': 'No result returned',
  30. };
  31. } catch (e) {
  32. return {
  33. 'success': false,
  34. 'error': e.toString(),
  35. };
  36. }
  37. }
  38. @override
  39. Future<Map<String, dynamic>> restore() async {
  40. try {
  41. final result = await methodChannel.invokeMethod<Map<dynamic, dynamic>>(
  42. 'restore',
  43. );
  44. return result?.cast<String, dynamic>() ?? {
  45. 'success': false,
  46. 'error': 'No result returned',
  47. };
  48. } catch (e) {
  49. return {
  50. 'success': false,
  51. 'error': e.toString(),
  52. };
  53. }
  54. }
  55. @override
  56. Future<bool> check(String appleId) async {
  57. try {
  58. // 调用原生方法并处理可能的空值
  59. final result = await methodChannel.invokeMethod<bool>('check',
  60. {'appleId': appleId},
  61. );
  62. return result ?? false; // 如果结果为 null,返回 false
  63. } on PlatformException catch (e) {
  64. print('检查试用资格失败: ${e.message}');
  65. return false; // 发生错误时返回 false
  66. } catch (e) {
  67. print('未知错误: $e');
  68. return false;
  69. }
  70. }
  71. }