Commit 008466a0 by ethanlamzs

Merge branch 'feature-2607-iosbuild' into feature-2607

ios 线上 1.1.4版本内容 记录
2 parents c0cfeaad decaf318
......@@ -47,3 +47,5 @@ assets/static
pubspec.lock
assets/dist.zip
macos/Podfile.lock
macos/Flutter/GeneratedPluginRegistrant.swift
windows/flutter/generated_plugins.cmake
......@@ -21,6 +21,8 @@ android {
ndkVersion = flutter.ndkVersion
compileOptions {
// flutter_local_notifications 插件要求启用核心库脱糖
isCoreLibraryDesugaringEnabled = true
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
......@@ -91,6 +93,9 @@ flutter {
}
dependencies {
// flutter_local_notifications 插件要求启用核心库脱糖
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
// 添加 AppCompat 支持库(PrivacyActivity需要)
implementation("androidx.appcompat:appcompat:1.6.1")
......@@ -104,7 +109,7 @@ dependencies {
// OPPO
//implementation("com.tencent.timpush:oppo:8.8.7357")
// vivo
//implementation("com.tencent.timpush:vivo:8.8.7357")
implementation("com.tencent.timpush:vivo:8.8.7357")
// Honor
//implementation("com.tencent.timpush:honor:8.7.7201")
// Meizu
......
{"version":"1.0.1","cn.banxe.bxe":{"manifestPlaceholders":{"VIVO_APPKEY":"f7e37b20f48234c425d9e7f82fdd16c0","VIVO_APPID":"105993977","HONOR_APPID":""},"vivoPushBussinessId":"44580","oppoPushBussinessId":"46190","oppoPushAppKey":"922926ff488b4c2cb76bb4103ca8a93d","oppoPushAppSecret":"30636ddc19d94571aa1378db15d61ac0"}}
\ No newline at end of file
{
"version": "1.0.1",
"cn.banxe.bxe": {
"manifestPlaceholders": {
"VIVO_APPKEY": "f7e37b20f48234c425d9e7f82fdd16c0",
"VIVO_APPID": "105993977",
"HONOR_APPID": ""
},
"vivoPushBussinessId": "44580"
}
}
\ No newline at end of file
......@@ -5,8 +5,9 @@ if [ -z "$1" ]; then
fi
env=$1
_rebuild_=$2
_main_ver='1.0.'
ot=$2
_rebuild_=$3
_main_ver='1.1.'
_ver=`date +%y%m%d%H%M`
base_root='/Users/ethanlam/works/gitlab/flutter_pros/appframe.git'
......@@ -47,12 +48,27 @@ if [ ! -z "$_rebuild_" ]; then
pod install
fi
_ver_tmp=`date '+%y%m%d%H%M'`
echo 'build '
flutter build ios --build-number=$_ver_tmp
#16
#flutter run --dart-define=env=$env --dart-define=version=$_main_ver$_ver -d 00008140-001068C93AB8801C
if [ ! -z "$ot" ]; then
if [ "$ot" == '16' ]; then
flutter run --dart-define=env=$env --dart-define=version=$_main_ver$_ver -d 00008140-001068C93AB8801C
fi
#11
#flutter run --dart-define=env=$env --dart-define=version=$_main_ver$_ver -d 00008030-001C75810E42402E
if [ "$ot" == '11' ]; then
flutter run --dart-define=env=$env --dart-define=version=$_main_ver$_ver -d 00008030-001C75810E42402E
fi
flutter build ios --build-number=$_ver
if [ "$ot" == 'sim' ]; then
flutter run --debug --dart-define=env=$env --dart-define=version=$_main_ver$_ver -d 89482737-FAA1-4145-BB2D-4B1B122B5B37
fi
else
echo 'build else '
fi
#11
#flutter run --dart-define=env=$env --dart-define=version=$_main_ver$_ver -d 00008030-001C75810E42402E
#flutter build ios --build-number=$_ver
......@@ -20,7 +20,7 @@ flutter pub get
#pod deintegrate
# 4. 清理 CocoaPods 本地缓存 (这一步很重要,ffmpeg 包很大,容易缓存损坏)
pod cache clean --all
#pod cache clean --all
# 5. 重新安装 Pods 并更新仓库索引
# 注意:这一步可能比较慢,因为 ffmpeg 库非常大(几百MB),请保持网络通畅
......
......@@ -26,7 +26,7 @@ end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
# pod 'TOCropViewController', :path => '/Users/ethanlam/works/base_env/flutter_envirs/extlibs/TOCropViewController.git/2.8.0' , :podspec => '/Users/ethanlam/works/base_env/flutter_envirs/extlibs/TOCropViewController.git/2.8.0/TOCropViewController.podspec'
#pod 'TOCropViewController', :path => '/Users/ethanlam/works/base_env/flutter_envirs/extlibs/TOCropViewController.git/2.8.0' , :podspec => '/Users/ethanlam/works/base_env/flutter_envirs/extlibs/TOCropViewController.git/2.8.0/TOCropViewController.podspec'
pod 'SDWebImage', :git => 'https://gitee.com/mirrors/SDWebImage.git', :branch => '5.21.3', :modular_headers => true
......
......@@ -16,6 +16,7 @@
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
DC7B80922FF3602D0006BCCE /* StoreKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC7B80912FF3602D0006BCCE /* StoreKit.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
......@@ -70,6 +71,8 @@
DC39D7882EFB987F00D795A8 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = en; path = en.lproj/Info.plist; sourceTree = "<group>"; };
DC39D7892EFB988000D795A8 /* zh-Hans */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = "zh-Hans"; path = "zh-Hans.lproj/Info.plist"; sourceTree = "<group>"; };
DC4A6BC3E644F00288FAFDCD /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
DC7B80912FF3602D0006BCCE /* StoreKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = StoreKit.framework; path = System/Library/Frameworks/StoreKit.framework; sourceTree = SDKROOT; };
DCEFFEE63000FA7000F7B036 /* Testing.storekit */ = {isa = PBXFileReference; lastKnownFileType = text; name = Testing.storekit; path = Runner/Testing.storekit; sourceTree = "<group>"; };
E94A65B4132ADF0336017236 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
/* End PBXFileReference section */
......@@ -87,6 +90,7 @@
buildActionMask = 2147483647;
files = (
1600F8F364E182C3635C3546 /* Pods_Runner.framework in Frameworks */,
DC7B80922FF3602D0006BCCE /* StoreKit.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
......@@ -115,6 +119,7 @@
97C146E51CF9000F007C117D = {
isa = PBXGroup;
children = (
DCEFFEE63000FA7000F7B036 /* Testing.storekit */,
9740EEB11CF90186004384FC /* Flutter */,
97C146F01CF9000F007C117D /* Runner */,
97C146EF1CF9000F007C117D /* Products */,
......@@ -153,6 +158,7 @@
9F7FE946B3449150A78BC577 /* Frameworks */ = {
isa = PBXGroup;
children = (
DC7B80912FF3602D0006BCCE /* StoreKit.framework */,
B2450CB3B5E968BD7CC513E6 /* Pods_Runner.framework */,
DC4A6BC3E644F00288FAFDCD /* Pods_RunnerTests.framework */,
);
......
......@@ -52,7 +52,7 @@
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
buildConfiguration = "Profile"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit"
......
......@@ -84,7 +84,6 @@ import tencent_cloud_chat_push
return true
}
}
// 可选:防止冲突的手势识别设置
......@@ -94,3 +93,4 @@ extension AppDelegate: UIGestureRecognizerDelegate {
return true
}
}
......@@ -57,6 +57,9 @@ class WebState extends Equatable {
final int? userType;
final String? stuId;
/// 通知点击等场景需要直接打开的 URL
final String? targetUrl;
/// getOrientationCmd
final bool orientationCmdFlag;
final String orientationCmdMessage;
......@@ -99,6 +102,7 @@ class WebState extends Equatable {
this.classCode,
this.userType,
this.stuId,
this.targetUrl,
this.orientationCmdFlag = false,
this.orientationCmdMessage = '',
this.windowInfoCmdFlag = false,
......@@ -131,6 +135,7 @@ class WebState extends Equatable {
String? classCode,
int? userType,
String? stuId,
String? targetUrl,
bool? orientationCmdFlag,
String? orientationCmdMessage,
bool? windowInfoCmdFlag,
......@@ -162,6 +167,7 @@ class WebState extends Equatable {
classCode: classCode ?? this.classCode,
userType: userType ?? this.userType,
stuId: stuId ?? this.stuId,
targetUrl: targetUrl ?? this.targetUrl,
orientationCmdFlag: orientationCmdFlag ?? this.orientationCmdFlag,
orientationCmdMessage: orientationCmdMessage ?? this.orientationCmdMessage,
windowInfoCmdFlag: windowInfoCmdFlag ?? this.windowInfoCmdFlag,
......@@ -195,6 +201,7 @@ class WebState extends Equatable {
classCode,
userType,
stuId,
targetUrl,
orientationCmdFlag,
orientationCmdMessage,
windowInfoCmdFlag,
......@@ -394,6 +401,15 @@ class WebCubit extends Cubit<WebState> with WidgetsBindingObserver {
}
void _loadHtml() {
// 如果通过路由透传了 targetUrl(如通知点击场景),
// 优先在 WebView 中打开该 URL。
final targetUrl = state.targetUrl;
if (targetUrl != null && targetUrl.isNotEmpty) {
final String resolvedUrl = '${Constant.localServerUrl}/index.html#$targetUrl';
_controller.loadRequest(Uri.parse(resolvedUrl));
return;
}
var sharedPreferences = getIt.get<SharedPreferences>();
var debug = sharedPreferences.getInt('debug') ?? 0;
// 构造函数中已拦截判断未登录的情况进行了处理,所以这里不再处理未登录的情况
......@@ -452,7 +468,7 @@ class WebCubit extends Cubit<WebState> with WidgetsBindingObserver {
imService.registerPush();
// 处理加群和退群
if (state.loginOpFlag) {
// imService.joinAndLeaveGroup(state.userCode!);
imService.joinAndLeaveGroup(state.userCode!);
}
} else {
debugPrint("缓存自动登录处,IM 登录失败");
......
......@@ -125,6 +125,6 @@ class Constant {
static const String hasShownPrivacyFirstTimeKey = 'has_shown_privacy_first_time';
/// 测试阶段使用
static const bool needIM = false;
static const bool needIM = true;
static const bool needUpgrade = true;
}
......@@ -50,6 +50,7 @@ import 'package:appframe/services/api_service.dart';
import 'package:appframe/services/dispatcher.dart';
import 'package:appframe/services/im_service.dart';
import 'package:appframe/services/local_server_service.dart';
import 'package:appframe/services/notification_service.dart';
import 'package:appframe/services/player_service.dart';
import 'package:appframe/services/recorder_service.dart';
import 'package:fluwx/fluwx.dart';
......@@ -241,6 +242,9 @@ Future<void> setupLocator() async {
instanceName: "appApiService",
);
/// 通知服务
getIt.registerSingleton<NotificationService>(NotificationService());
/// imService
getIt.registerSingleton<ImService>(ImService());
......
......@@ -19,6 +19,7 @@ import 'package:appframe/ui/pages/setting_v2/account_apple_page_v2.dart';
import 'package:appframe/ui/pages/setting_v2/account_logoff_page_v2.dart';
import 'package:appframe/ui/pages/setting_v2/account_page_v2.dart';
import 'package:appframe/ui/pages/setting_v2/account_phone_page_v2.dart';
import 'package:appframe/ui/pages/subscription_page.dart';
import 'package:appframe/ui/pages/web_page.dart';
import 'package:appframe/ui/widgets/ios_edge_swipe_detector.dart';
import 'package:flutter/material.dart';
......@@ -130,6 +131,12 @@ final GoRouter router = GoRouter(
return const PreviewMediaPage();
},
),
GoRoute(
path: '/iosbuytest',
builder: (BuildContext context, GoRouterState state) {
return const SubscriptionPage();
},
),
],
);
......
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:appframe/config/constant.dart';
import 'package:appframe/config/locator.dart';
import 'package:appframe/data/repositories/user_auth_repository.dart';
import 'package:appframe/services/dispatcher.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'package:appframe/services/subscription_service_ios.dart';
import 'package:fluwx/fluwx.dart';
class XeCreateOrderHandler extends MessageHandler {
......@@ -19,6 +22,8 @@ class XeCreateOrderHandler extends MessageHandler {
// 超时定时器
Timer? _timeoutTimer;
final SubscriptionService _subService = SubscriptionService();
XeCreateOrderHandler() {
_fluwx = getIt.get<Fluwx>();
_userAuthRepository = getIt.get<UserAuthRepository>();
......@@ -26,6 +31,8 @@ class XeCreateOrderHandler extends MessageHandler {
@override
Future<dynamic> handleMessage(params) async {
print("############## handleMessage #############");
// 从 params 中提取支付参数
final String chargeCode = params['chargeCode'] as String? ?? '';
final int durationType = params['durationType'] as int? ?? 0;
......@@ -50,13 +57,28 @@ class XeCreateOrderHandler extends MessageHandler {
'phone=$phone, userCode=$userCode, tbxStuId=$tbxStuId, stuId=$stuId, '
'ext=$ext');
// 1. 检查微信是否安装
// 1. 请求后端获取预支付订单信息
final deviceType = Platform.isIOS?"ios":"andorid";
if (deviceType == 'andorid'){
return await _wx_pay_proc_(userCode, tbxStuId, chargeCode, deviceType, phone, stuId, ext, duration, durationType, totalFee, renew, useCoin);
}else if (deviceType == 'ios'){
// 暂时不支持使用学币扣减
// 执行ios支付
await _subService.initialize();
return await _ios_pay_proc_(userCode, tbxStuId, chargeCode, deviceType, phone, stuId, ext, duration, durationType, totalFee, renew, false);
}
}
// 执行微信支付
Future<dynamic> _wx_pay_proc_ (String userCode, tbxStuId, chargeCode,deviceType,phone,stuId,ext,int duration, durationType, totalFee,bool renew, useCoin) async{
// 2. 检查微信是否安装
if (!await _fluwx.isWeChatInstalled) {
throw Exception('设备上未安装微信App,不支持微信支付');
}
// 2. 请求后端获取预支付订单信息
final deviceType = 'android';
var result = await _userAuthRepository.createOrder(userCode, tbxStuId, chargeCode, duration, durationType, totalFee,
renew, phone, stuId, ext, useCoin ? 1 : 0, deviceType);
if (result == null) {
......@@ -83,14 +105,14 @@ class XeCreateOrderHandler extends MessageHandler {
final paySign = data['paySign'] as String;
final wxTradeNo = data['wxTradeNo'] as String;
debugPrint('prepayId: $prepayId');
debugPrint('nonceStr: $nonceStr');
debugPrint('timestamp: $timestamp');
debugPrint('paySign: $paySign');
debugPrint('appId: $appId');
debugPrint('partnerId: $partnerId');
debugPrint('packageValue: $packageValue');
debugPrint('wxTradeNo: $wxTradeNo');
debugPrint('_wx_pay_proc_ => prepayId: $prepayId');
debugPrint('_wx_pay_proc_ => nonceStr: $nonceStr');
debugPrint('_wx_pay_proc_ => timestamp: $timestamp');
debugPrint('_wx_pay_proc_ => paySign: $paySign');
debugPrint('_wx_pay_proc_ => appId: $appId');
debugPrint('_wx_pay_proc_ => partnerId: $partnerId');
debugPrint('_wx_pay_proc_ => packageValue: $packageValue');
debugPrint('_wx_pay_proc_ => wxTradeNo: $wxTradeNo');
if (nonceStr.isEmpty || paySign.isEmpty || wxTradeNo.isEmpty) {
throw Exception('支付参数获取失败');
......@@ -155,6 +177,8 @@ class XeCreateOrderHandler extends MessageHandler {
} finally {
_cleanup();
}
}
/// Fluwx 响应监听器
......@@ -174,4 +198,82 @@ class XeCreateOrderHandler extends MessageHandler {
_timeoutTimer = null;
_payCompleter = null;
}
// 执行ios的微信支付
Future<dynamic> _ios_pay_proc_ (String userCode, tbxStuId, chargeCode,deviceType,phone,stuId,ext,int duration, durationType, totalFee,bool renew, useCoin) async{
// 暂时用固定的价格
var result = await _userAuthRepository.createOrder(userCode, tbxStuId, chargeCode, duration, durationType, totalFee,
renew, phone, stuId, ext, useCoin ? 1 : 0, deviceType);
print(result);
// map[nonceStr:qNfHK6a95jjJkwzDkh0h3fhfUVuS0jZ9 paySign: timeStamp:1783497438 wxTradeNo:to1281644408384671744]
var data = result['data'] as Map<String, dynamic>?;
if (data == null) {
throw Exception('订单生成失败');
}
// 3. 从后端响应中提取预支付ID
final wxTradeNo = data['wxTradeNo'] as String?;
if (wxTradeNo == null || wxTradeNo.isEmpty) {
throw Exception('订单生成失败');
}
// 4. 从后端响应中提取支付参数(nonceStr、timestamp、paySign 由后端生成)
final timestamp = data['timeStamp'] as int;
//debugPrint('_ios_pay_proc_ => timestamp: $timestamp');
debugPrint('_ios_pay_proc_ => wxTradeNo: $wxTradeNo');
if (wxTradeNo.isEmpty) {
throw Exception('支付参数获取失败');
}
// 为了调试,先模拟
var product;
var packageName = "";
if (totalFee.toString()=="4990"){
packageName="月卡";
}else if (totalFee.toString()=="12900"){
packageName="季卡";
}else if (totalFee.toString()=="20900"){
packageName="半年卡";
}else if (totalFee.toString()=="29900"){
packageName="年卡";
}
for (var p in _subService.products) {
// 因为带了一个¥符号
//debugPrint('checking ==> 产品ID: ${p.id}, 标题: ${p.title}, 价格: ${p.price}');
if (p.title.toString().indexOf(packageName)>0){
product = p;
debugPrint('match =====> 产品ID: ${p.id}, 标题: ${p.title}, 价格: ${p.price}');
break;
}
//
}
if(product==null){
throw Exception('订单生成失败');
}
print("match product is "+product.price);
var isOk = await _subService.buySubscription(product, userCode, tbxStuId,wxTradeNo);
print("[info] _subService.buySubscription res is "+isOk.toString());
if (isOk==true){
return {"orderUnique": wxTradeNo, "orderState": 1};
}else{
return {"orderUnique": wxTradeNo, "orderState": 0};
}
// throw Exception('已取消支付');
}
}
......@@ -18,7 +18,7 @@ class SubsRepository {
{
"type": type,
"userid": userid,
"classCode": classCode,
"classCodes": classCode,
},
);
return resp.statusCode == HttpStatus.ok ? resp.data : null;
......
......@@ -162,4 +162,23 @@ class UserAuthRepository {
}
}
// 检查ios的订单是否已经订阅
Future<dynamic> orderCheck(String userId,String receipt,String orderid, String platform,int isSandbox ) async {
try {
Response resp = await _appService.post(
'/api/v1/comm/user/ordercheck',
{
"userId": userId,
"receipt": receipt,
"orderid":orderid,
"platform": platform,
"isSandbox":isSandbox,
},
);
return resp.statusCode == HttpStatus.ok ? resp.data : null;
} on DioException {
return null;
}
}
}
......@@ -10,7 +10,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:appframe/services/subscription_service_ios.dart';
import 'app.dart';
void main() async {
......@@ -21,6 +21,11 @@ void main() async {
await _initH5Version();
await _initIOSGesture();
if (Platform.isIOS){
SubscriptionService _subService = SubscriptionService();
_subService.initialize();
}
runApp(const App());
}
......
......@@ -6,6 +6,7 @@ import 'package:appframe/data/models/message/h5_message.dart';
import 'package:appframe/data/models/message/h5_resp.dart';
import 'package:appframe/data/repositories/message/upload_cancel_handler.dart';
import 'package:appframe/data/repositories/message/upload_start_handler.dart';
import 'package:flutter/widgets.dart';
// 消息处理器抽象类
abstract class MessageHandler {
......@@ -35,7 +36,6 @@ class MessageDispatcher {
Future<void> dispatch(String message, Function callback, {WebCubit? webCubit}) async {
final Map<String, dynamic> data = json.decode(message);
H5Message h5Message = H5Message.fromJson(data);
var handler = _handlers[h5Message.cmd];
if (handler == null) {
try {
......
......@@ -2,7 +2,9 @@ import 'package:appframe/config/constant.dart';
import 'package:appframe/config/locator.dart';
import 'package:appframe/data/repositories/subs_repository.dart';
import 'package:appframe/services/api_service.dart';
import 'package:appframe/services/notification_service.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_cloud_chat_push/common/tim_push_listener.dart';
import 'package:tencent_cloud_chat_push/common/tim_push_message.dart';
......@@ -65,120 +67,140 @@ class ImService {
},
onRecvMessageReadReceipts: (List<V2TimMessageReceipt> receiptList) {
//群聊已读回调
for (var element in receiptList) {
element.groupID; // 群id
element.msgID; // 已读回执消息 ID
element.readCount; // 群消息最新已读数
element.unreadCount; // 群消息最新未读数
element.userID; // C2C 消息对方 ID
}
// for (var element in receiptList) {
// element.groupID; // 群id
// element.msgID; // 已读回执消息 ID
// element.readCount; // 群消息最新已读数
// element.unreadCount; // 群消息最新未读数
// element.userID; // C2C 消息对方 ID
// }
},
onRecvMessageRevoked: (String messageid) {
// 在本地维护的消息中处理被对方撤回的消息
},
onRecvNewMessage: (V2TimMessage message) async {
// 处理文本消息
if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_TEXT) {
// message.textElem?.text;
// 时间戳转换
DateTime dt = DateTime.fromMillisecondsSinceEpoch(message.timestamp! * 1000);
debugPrint(
"收到IM消息—— 时间:${dt.year}-${dt.month}-${dt.day} ${dt.hour}:${dt.minute}:${dt.second} 发送者:${message.sender} 内容:${message.textElem?.text}");
// 目前只会有文本消息,所以其他消息类型暂不处理,直接return
return;
}
// 使用自定义消息
if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_CUSTOM) {
message.customElem?.data;
message.customElem?.desc;
message.customElem?.extension;
}
// 使用图片消息
if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_IMAGE) {
message.imageElem?.path; // 图片上传时的路径,消息发送者才会有这个字段,消息发送者可用这个字段将图片预先上屏,优化上屏体验。
message.imageElem?.imageList?.forEach((element) {
// 遍历大图、原图、缩略图
// 解析图片属性
element?.height;
element?.localUrl;
element?.size;
element?.type; // 大图 缩略图 原图
element?.url;
element?.uuid;
element?.width;
});
}
// 处理视频消息
if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_VIDEO) {
// 解析视频消息属性,封面、播放地址、宽高、大小等。
message.videoElem?.UUID;
message.videoElem?.duration;
message.videoElem?.localSnapshotUrl;
message.videoElem?.localVideoUrl;
message.videoElem?.snapshotHeight;
message.videoElem?.snapshotPath;
// ...
}
// 处理音频消息
if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_SOUND) {
// 解析语音消息 播放地址,本地地址,大小,时长等。
message.soundElem?.UUID;
message.soundElem?.dataSize;
message.soundElem?.duration;
message.soundElem?.localUrl;
message.soundElem?.url;
// ...
}
// 处理文件消息
if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_FILE) {
// 解析文件消息 文件名、文件大小、url等
message.fileElem?.UUID;
message.fileElem?.fileName;
message.fileElem?.fileSize;
message.fileElem?.localUrl;
message.fileElem?.path;
message.fileElem?.url;
}
// 处理位置消息
if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_LOCATION) {
// 解析地理位置消息,经纬度、描述等
message.locationElem?.desc;
message.locationElem?.latitude;
message.locationElem?.longitude;
}
// 处理表情消息
if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_FACE) {
message.faceElem?.data;
message.faceElem?.index;
}
// 处理群组tips文本消息
if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_GROUP_TIPS) {
message.groupTipsElem?.groupID; // 所属群组
message.groupTipsElem?.type; // 群Tips类型
message.groupTipsElem?.opMember; // 操作人资料
message.groupTipsElem?.memberList; // 被操作人资料
message.groupTipsElem?.groupChangeInfoList; // 群信息变更详情
message.groupTipsElem?.memberChangeInfoList; // 群成员变更信息
message.groupTipsElem?.memberCount; // 当前群在线人数
}
// 处理合并消息消息
if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_MERGER) {
message.mergerElem?.abstractList;
message.mergerElem?.isLayersOverLimit;
message.mergerElem?.title;
V2TimValueCallback<List<V2TimMessage>> download =
await TencentImSDKPlugin.v2TIMManager.getMessageManager().downloadMergerMessage(
msgID: message.msgID!,
// 标记消息为已读
if (message.userID != null && message.userID!.isNotEmpty) {
// C2C消息标记已读
var res = await TencentImSDKPlugin.v2TIMManager.getConversationManager().cleanConversationUnreadMessageCount(
conversationID: 'c2c_${message.userID}',
cleanTimestamp: 0,
cleanSequence: 0,
);
if (download.code == 0) {
//List<V2TimMessage>? messageList = download.data;
}
}
if (message.textElem?.nextElem != null) {
//通过第一个 Elem 对象的 nextElem 方法获取下一个 Elem 对象,如果下一个 Elem 对象存在,会返回 Elem 对象实例,如果不存在,会返回 null。
debugPrint("[im_service]标记C2C消息已读: userID=${message.userID}, result=${res.code}");
} else if (message.groupID != null && message.groupID!.isNotEmpty) {
// 群消息标记已读
var res = await TencentImSDKPlugin.v2TIMManager.getConversationManager().cleanConversationUnreadMessageCount(
conversationID: 'group_${message.groupID}',
cleanTimestamp: 0,
cleanSequence: 0,
);
debugPrint("[im_service]标记群消息已读: groupID=${message.groupID}, result=${res.code}");
}
// 处理文本消息
// if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_TEXT) {
// // message.textElem?.text;
//
// // 时间戳转换
// DateTime dt = DateTime.fromMillisecondsSinceEpoch(message.timestamp! * 1000);
// debugPrint("[高级消息监听器] onRecvNewMessage 时间:${dt.year}-${dt.month}-${dt.day} ${dt.hour}:${dt.minute}:${dt.second} 发送者:${message.sender} 内容:${message.textElem?.text}");
//
// Fluttertoast.showToast(msg: '[高级消息监听器] onRecvNewMessage ${message.textElem?.text ?? ""}', gravity: ToastGravity.TOP);
//
// // 目前只会有文本消息,所以其他消息类型暂不处理,直接return
// return;
// }
// 使用自定义消息
// if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_CUSTOM) {
// message.customElem?.data;
// message.customElem?.desc;
// message.customElem?.extension;
// }
// // 使用图片消息
// if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_IMAGE) {
// message.imageElem?.path; // 图片上传时的路径,消息发送者才会有这个字段,消息发送者可用这个字段将图片预先上屏,优化上屏体验。
// message.imageElem?.imageList?.forEach((element) {
// // 遍历大图、原图、缩略图
// // 解析图片属性
// element?.height;
// element?.localUrl;
// element?.size;
// element?.type; // 大图 缩略图 原图
// element?.url;
// element?.uuid;
// element?.width;
// });
// }
// // 处理视频消息
// if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_VIDEO) {
// // 解析视频消息属性,封面、播放地址、宽高、大小等。
// message.videoElem?.UUID;
// message.videoElem?.duration;
// message.videoElem?.localSnapshotUrl;
// message.videoElem?.localVideoUrl;
// message.videoElem?.snapshotHeight;
// message.videoElem?.snapshotPath;
// // ...
// }
// // 处理音频消息
// if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_SOUND) {
// // 解析语音消息 播放地址,本地地址,大小,时长等。
// message.soundElem?.UUID;
// message.soundElem?.dataSize;
// message.soundElem?.duration;
// message.soundElem?.localUrl;
// message.soundElem?.url;
// // ...
// }
// // 处理文件消息
// if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_FILE) {
// // 解析文件消息 文件名、文件大小、url等
// message.fileElem?.UUID;
// message.fileElem?.fileName;
// message.fileElem?.fileSize;
// message.fileElem?.localUrl;
// message.fileElem?.path;
// message.fileElem?.url;
// }
// // 处理位置消息
// if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_LOCATION) {
// // 解析地理位置消息,经纬度、描述等
// message.locationElem?.desc;
// message.locationElem?.latitude;
// message.locationElem?.longitude;
// }
// // 处理表情消息
// if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_FACE) {
// message.faceElem?.data;
// message.faceElem?.index;
// }
// // 处理群组tips文本消息
// if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_GROUP_TIPS) {
// message.groupTipsElem?.groupID; // 所属群组
// message.groupTipsElem?.type; // 群Tips类型
// message.groupTipsElem?.opMember; // 操作人资料
// message.groupTipsElem?.memberList; // 被操作人资料
// message.groupTipsElem?.groupChangeInfoList; // 群信息变更详情
// message.groupTipsElem?.memberChangeInfoList; // 群成员变更信息
// message.groupTipsElem?.memberCount; // 当前群在线人数
// }
// // 处理合并消息消息
// if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_MERGER) {
// message.mergerElem?.abstractList;
// message.mergerElem?.isLayersOverLimit;
// message.mergerElem?.title;
// V2TimValueCallback<List<V2TimMessage>> download =
// await TencentImSDKPlugin.v2TIMManager.getMessageManager().downloadMergerMessage(
// msgID: message.msgID!,
// );
// if (download.code == 0) {
// //List<V2TimMessage>? messageList = download.data;
// }
// }
// if (message.textElem?.nextElem != null) {
// //通过第一个 Elem 对象的 nextElem 方法获取下一个 Elem 对象,如果下一个 Elem 对象存在,会返回 Elem 对象实例,如果不存在,会返回 null。
// }
},
onSendMessageProgress: (V2TimMessage message, int progress) {
//文件上传进度回调
......@@ -349,33 +371,33 @@ class ImService {
void _onNotificationClicked({required String ext, String? userID, String? groupID}) {
debugPrint("_onNotificationClicked: $ext, userID: $userID, groupID: $groupID");
if (userID != null || groupID != null) {
// 根据 userID 或 groupID 跳转至对应 Message 页面.
} else {
// 根据 ext 字段, 自己写解析方式, 跳转至对应页面.
}
getIt.get<NotificationService>().handleNotificationClick(ext);
}
TIMPushListener timPushListener = TIMPushListener(
onRecvPushMessage: (TimPushMessage message) {
debugPrint('推送监听器 onRecvPushMessage-------------');
String messageLog = message.toLogString();
debugPrint("message: $messageLog");
// // 手机消息通知
// getIt.get<NotificationService>().showNotification(
// id: DateTime.now().millisecondsSinceEpoch % 1000000,
// title: message.title ?? '',
// body: message.desc ?? '',
// );
// debugPrint('[推送监听器] onRecvPushMessage-------------');
// String messageLog = message.toLogString();
// debugPrint("message: $messageLog");
//
// Fluttertoast.showToast(msg: "[推送监听器] onRecvPushMessage: ${message.toLogString()}", gravity: ToastGravity.TOP);
debugPrint('[im_service][推送监听器] onRecvPushMessage------------- 调起手机通知');
// 手机消息通知
getIt.get<NotificationService>().showNotification(
id: DateTime.now().millisecondsSinceEpoch % 1000000,
title: message.title ?? '',
body: message.desc ?? '',
payload: message.ext ?? '',
);
},
onRevokePushMessage: (String messageId) {
debugPrint('推送监听器 onRevokePushMessage-------------');
debugPrint('[im_service][推送监听器] onRevokePushMessage-------------');
debugPrint("message: $messageId");
},
onNotificationClicked: (String ext) {
debugPrint('推送监听器 onNotificationClicked-------------');
debugPrint('[im_service][推送监听器] onNotificationClicked-------------');
debugPrint("ext: $ext");
//Fluttertoast.showToast(msg: "[im_service][推送监听器] Notification Clicked: $ext", toastLength: Toast.LENGTH_LONG);
},
);
......
import 'dart:convert';
import 'dart:io';
import 'package:appframe/config/locator.dart';
import 'package:appframe/config/routes.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class NotificationService {
final FlutterLocalNotificationsPlugin _plugin = FlutterLocalNotificationsPlugin();
bool _isInitialized = false;
bool get isInitialized => _isInitialized;
/// 初始化通知插件
Future<void> initialize() async {
if (_isInitialized) return;
const androidSettings = AndroidInitializationSettings('@mipmap/launcher_icon');
const iosSettings = DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);
const settings = InitializationSettings(android: androidSettings, iOS: iosSettings);
final result = await _plugin.initialize(
settings,
onDidReceiveNotificationResponse: _onNotificationResponse,
);
_isInitialized = result ?? false;
if (_isInitialized) {
debugPrint('NotificationService 初始化成功');
// Android 13+ 需要请求通知权限
if (Platform.isAndroid) {
final androidPlugin = _plugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();
await androidPlugin?.requestNotificationsPermission();
}
} else {
debugPrint('NotificationService 初始化失败');
}
}
/// 处理通知点击(供外部调用,如离线推送点击)
void handleNotificationClick(String? payload) {
debugPrint('[notification_service] handleNotificationClick payload: $payload');
// 通过 /reload 中转路由跳转,确保即使当前已在 /web,
// GoRouter 也会完整重建 WebPage 并加载新的 targetUrl。
final targetUrl = _buildTargetUrl(payload);
debugPrint('[notification_service] targetUrl: $targetUrl');
if (targetUrl != null && targetUrl.isNotEmpty) {
router.go(
'/reload',
extra: {'targetUrl': targetUrl},
);
} else {
router.go('/web');
}
}
/// 前台本地通知点击回调处理
void _onNotificationResponse(NotificationResponse response) {
debugPrint('[notification_service] Notification clicked, payload: ${response.payload}');
handleNotificationClick(response.payload);
}
/// 解析通知 payload,结合 auth_roles 缓存拼接目标 URL。
/// payload 格式:{"func": "homework", "uniqueCode": "...", "classCode": "..."}
/// 返回示例:/h5/login/pages/applogin?sessionCode=xxx&userCode=xxx&classCode=xxx&userType=2&stuId=xxx&page=homeworkdetail&uniqueCode=xxx
String? _buildTargetUrl(String? payload) {
if (payload == null || payload.isEmpty) return null;
try {
final data = jsonDecode(payload) as Map<String, dynamic>;
final func = data['func'] as String?;
final uniqueCode = data['uniqueCode'] as String?;
final classCode = data['classCode'] as String?;
if (uniqueCode == null || uniqueCode.isEmpty || classCode == null || classCode.isEmpty) {
debugPrint('[notification_service] payload 缺少 uniqueCode 或 classCode');
return null;
}
final prefs = getIt.get<SharedPreferences>();
final rolesJson = prefs.getString('auth_roles') ?? '';
if (rolesJson.isEmpty) {
debugPrint('[notification_service] auth_roles 缓存为空');
return null;
}
final roles = jsonDecode(rolesJson) as List<dynamic>;
Map<String, dynamic>? matchedRole;
for (final role in roles) {
if (role is Map<String, dynamic> && role['classCode']?.toString() == classCode) {
matchedRole = role;
break;
}
}
if (matchedRole == null) {
debugPrint('[notification_service] 未找到与 classCode=$classCode 匹配的 role');
return null;
}
final stuId = matchedRole['stuId']?.toString() ?? '';
final sessionCode = prefs.getString('auth_sessionCode') ?? '';
final userCode = prefs.getString('auth_userCode') ?? '';
var funcPage = '';
if (func == 'homework') {
funcPage = 'page=homeworkdetail&uniqueCode=$uniqueCode';
} else if (func == 'clockin') {
funcPage = 'page=clockdetail&clockUnique=$uniqueCode';
} else {
debugPrint('[notification_service] 不支持功能的类型: $func');
return null;
}
return '/h5/login/pages/applogin?'
'sessionCode=$sessionCode&'
'userCode=$userCode&'
'classCode=$classCode&'
'userType=2&'
'stuId=$stuId&'
'$funcPage';
} catch (e, stackTrace) {
debugPrint('[notification_service] 解析 payload 失败: $e\n$stackTrace');
return null;
}
}
/// 显示手机通知(懒初始化:首次调用自动触发初始化)
Future<void> showNotification({
required int id,
required String title,
required String body,
String? payload,
}) async {
// 懒初始化:首次调用时自动初始化
if (!_isInitialized) {
await initialize();
}
const androidDetails = AndroidNotificationDetails(
'homework_message_channel',
'作业消息通知',
channelDescription: '接收作业消息推送通知',
importance: Importance.high,
priority: Priority.high,
);
const iosDetails = DarwinNotificationDetails();
const details = NotificationDetails(android: androidDetails, iOS: iosDetails);
await _plugin.show(id, title, body, details, payload: payload);
debugPrint('NotificationService showNotification: id=$id, title=$title, body=$body');
}
}
// subscription_service.dart
import 'dart:async';
import 'dart:convert';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/widgets.dart';
import 'package:appframe/data/repositories/user_auth_repository.dart';
import 'package:appframe/config/locator.dart';
class SubscriptionService {
// App Store Connect 中配置的订阅产品 ID(组内唯一)
// 例如月度、年度两种方案
static const String monthlySubId_1 = 'cn.banxe.appframe.membership.1m';
static const String monthlySubId_3 = 'cn.banxe.appframe.membership.3m';
static const String monthlySubId_6 = 'cn.banxe.appframe.membership.6m';
static const String monthlySubId_12 = 'cn.banxe.appframe.membership.12m';
// 纯粹的数据容器,不继承任何类
// ---------- 业务上下文映射(productID → 自定义数据) ----------
static const String _cacheKey = 'iap_products_cache';
static const String _timestampKey = 'iap_cache_timestamp';
static const Duration _cacheValidDuration = Duration(hours: 24); // 可调整
// 标记是否已从 StoreKit 获取到最新产品
bool _hasRealProducts = false;
final Map<String, Map<String, dynamic>> _pendingContexts = {};
final InAppPurchase _iap = InAppPurchase.instance;
late StreamSubscription<List<PurchaseDetails>> _purchaseUpdatedSubscription;
final UserAuthRepository _userAuthRepository = getIt.get<UserAuthRepository>();
// 可用产品列表
List<ProductDetails> _products = [];
List<ProductDetails> get products => _products;
// 当前有效订阅状态(简化版)
bool _hasActiveSubscription = false;
bool get hasActiveSubscription => _hasActiveSubscription;
// ---------- 🔁 去重措施:记录已处理过的交易 ID ----------
final Set<String> _processedTransactionIds = {};
// ---------- 回调函数,用于通知 UI 状态变化 ----------
void Function(String? errorMessage)? onError;
void Function(String message)? onSuccess;
void Function()? onStateChanged;
// 初始化
Future<void> initialize() async {
// 1. 检查是否可用
final bool available = await _iap.isAvailable();
if (!available) {
throw Exception('In-App Purchase 不可用');
}
// 2. 监听交易更新(最重要!务必在调用购买之前设置)
_purchaseUpdatedSubscription =
_iap.purchaseStream.listen(
_onPurchaseUpdate,
onError: (error) => print('purchaseStream error: $error'),
);
// // 3. 从 App Store 获取产品信息
// await _fetchProducts();
// 1. 立即从缓存加载,先展示给用户
await _loadCacheAndShow();
// 2. 后台异步拉取最新产品,不阻塞 UI
_fetchAndUpdateProducts(); // 注意:非 await,fire-and-forget
}
// ---------- 获取产品信息 ----------
Future<void> _fetchProducts() async {
const Set<String> ids = {monthlySubId_1,monthlySubId_3,monthlySubId_6,monthlySubId_12};
final ProductDetailsResponse response = await _iap.queryProductDetails(ids);
if (response.notFoundIDs.isNotEmpty) {
// 有产品未在 App Store Connect 配置或配置错误
debugPrint('未找到产品: ${response.notFoundIDs}');
}
_products = response.productDetails;
debugPrint('获取到 ${_products.length} 个产品');
for (var p in _products) {
debugPrint('x1=====> 产品ID: ${p.id}, 标题: ${p.title}, 价格: ${p.price}');
}
}
// ---------- 从缓存加载产品(仅用于展示) ----------
Future<void> _loadCacheAndShow() async {
final cached = await _loadCachedProducts();
if (cached != null && cached.isNotEmpty) {
_products = cached;
_hasRealProducts = false; // 缓存不是真实产品,仅用于展示
onStateChanged?.call(); // 通知 UI 更新
}
print("[info] ################# _loadCacheAndShow is ok ############# ");
}
// ---------- 后台获取真实产品并更新缓存 ----------
Future<void> _fetchAndUpdateProducts() async {
try {
const Set<String> ids = {monthlySubId_1,monthlySubId_3,monthlySubId_6,monthlySubId_12};
final response = await _iap.queryProductDetails(ids);
if (response.productDetails.isNotEmpty) {
_products = response.productDetails;
_hasRealProducts = true; // 已拿到真实产品
await _cacheProducts(_products);
onStateChanged?.call();
}
} catch (e) {
debugPrint('获取产品失败: $e');
// 如果获取失败且缓存为空,UI 可能空白,可在此处理
}
}
// ---------- 缓存读写(ProductDetails ↔ JSON) ----------
Future<void> _cacheProducts(List<ProductDetails> products) async {
try {
final prefs = await SharedPreferences.getInstance();
final jsonList = products.map((p) => _productToJson(p)).toList();
await prefs.setString(_cacheKey, jsonEncode(jsonList));
await prefs.setString(_timestampKey, DateTime.now().toIso8601String());
print("[debug] ######### _cacheProducts is done ##############");
} catch (e) {
debugPrint('缓存产品失败: $e');
}
}
Future<List<ProductDetails>?> _loadCachedProducts() async {
try {
final prefs = await SharedPreferences.getInstance();
final timestampStr = prefs.getString(_timestampKey);
if (timestampStr == null) return null;
final cacheTime = DateTime.parse(timestampStr);
if (DateTime.now().difference(cacheTime) > _cacheValidDuration) {
await _clearCache();
return null;
}
final jsonStr = prefs.getString(_cacheKey);
if (jsonStr == null) return null;
final List<dynamic> list = jsonDecode(jsonStr);
return list.map((item) => _productFromJson(item)).toList();
} catch (e) {
return null;
}
}
Future<void> _clearCache() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_cacheKey);
await prefs.remove(_timestampKey);
}
// ProductDetails 序列化(请确保字段名称与你的插件版本一致)
Map<String, dynamic> _productToJson(ProductDetails p) => {
'id': p.id,
'title': p.title,
'description': p.description,
'price': p.price,
'rawPrice': p.rawPrice,
'currencyCode': p.currencyCode,
'currencySymbol': p.currencySymbol,
// 'subscriptionPeriod': p,
// 'introductoryPrice': p.introductoryPrice,
};
ProductDetails _productFromJson(Map<String, dynamic> json) => ProductDetails(
id: json['id'] ?? '',
title: json['title'] ?? '',
description: json['description'] ?? '',
price: json['price'] ?? '',
rawPrice: (json['rawPrice'] as num?)?.toDouble() ?? 0.0,
currencyCode: json['currencyCode'] ?? '',
currencySymbol: json['currencySymbol'] ?? '',
// subscriptionPeriod: json['subscriptionPeriod'] ?? '',
// introductoryPrice: json['introductoryPrice'] ?? '',
);
Future<void> restoreSubscription() async {
try{
await _iap.restorePurchases();
}
catch(e){
onError?.call(e.toString());
}
}
// ---------- 购买订阅 ----------
Future<bool> buySubscription(ProductDetails product, String userId , String tbxStuId, String yWOrderId) async {
_pendingContexts[product.id] = {'userId': userId,'tbxStuId': tbxStuId,"orderId":yWOrderId};
// 订阅必须使用 PurchaseParam 并设置购买类型为订阅
final PurchaseParam purchaseParam = PurchaseParam(
productDetails: product,
applicationUserName: yWOrderId,
);
try {
// 发起购买(App Store 会弹出系统支付界面)
print("[debug] ############## buySubscription is try to run ##############");
await _iap.buyNonConsumable(purchaseParam: purchaseParam);
print("[debug] ############## buySubscription is run end ##############");
return true; // 实际结果在 _onPurchaseUpdate 处理
}catch (e){
_pendingContexts.remove(product.id); // 发起失败,清除上下文
debugPrint(e.toString());
onError?.call('购买请求失败: $e');
return false;
}
// 注意:成功或失败会通过 purchaseStream 回调返回
}
// ---------- 交易更新回调 ----------
void _onPurchaseUpdate(List<PurchaseDetails> purchaseDetailsList) {
for (final purchaseDetails in purchaseDetailsList) {
print('[debug] ############## Purchase update: ${purchaseDetails.productID} - ${purchaseDetails.status} - ${purchaseDetails.purchaseID}- ${purchaseDetails.toString()}');
// 只处理订阅类型产品
if (!_isSubscription(purchaseDetails.productID)){
continue;
}
// 🔁 去重措施 1:根据原始交易 ID 去重,防止同一笔交易被重复处理
//final transactionId = purchaseDetails.verificationData.serverVerificationData.hashCode.toString();
// 如果能获取到 purchaseID 更可靠,这里用 purchaseID 作为唯一标识
final uniqueId = purchaseDetails.purchaseID;
if (_processedTransactionIds.contains(uniqueId)) {
// 已经处理过,直接结束交易并跳过
if (purchaseDetails.status == PurchaseStatus.purchased ||
purchaseDetails.status == PurchaseStatus.restored) {
_iap.completePurchase(purchaseDetails);
}
continue;
}
// 标记为已处理
if (uniqueId != null) {
_processedTransactionIds.add(uniqueId);
}
final ctx = _pendingContexts[purchaseDetails.productID] ;
print(ctx);
if (ctx == null) {
// 打印错误日志,防止崩溃
print('错误:未找到 productID 对应的上下文缓存');
debugPrint("No purchase context: ${purchaseDetails.productID}");
continue;
}
final orderId = ctx['orderId'] as String?;
final userId = ctx['userId'] as String?;
final tbxStuId = ctx['tbxStuId'] as String?;
print("[debug] ############## orderId ==> "+orderId.toString()+" "+ userId.toString() +". "+ tbxStuId.toString()+" "+purchaseDetails.status.toString());
// 根据交易状态处理
switch (purchaseDetails.status) {
case PurchaseStatus.purchased:
// 购买成功或续期成功
// 1. 验证收据(必须!)
//_verifyReceipt(purchaseDetails,orderId??'',userId??'',"purchased");
_handlePurchaseSuccess(purchaseDetails,orderId??'',userId??'');
break;
case PurchaseStatus.error:
// 处理错误
_handlePurchaseError(purchaseDetails.error!);
break;
case PurchaseStatus.restored:
// 恢复购买成功
// 🔁 去重措施 2:恢复事件只处理最后一个有效的,或者收集后统一处理
// 这里演示:仍然逐个验证,但后端会基于 original_transaction_id 去重
//_verifyReceipt(purchaseDetails,orderId??'',userId??'',"restored");
_handleRestoreSuccess(purchaseDetails,orderId??'',userId??'');
break;
case PurchaseStatus.canceled:
// 用户取消支付
//_iap.completePurchase(purchaseDetails);
break;
case PurchaseStatus.pending:
onStateChanged?.call();
break;
}
// // ✅ 关键:只要不是 pending,都立刻完成交易,清出队列
// if (purchaseDetails.status != PurchaseStatus.pending) {
// _iap.completePurchase(purchaseDetails);
// print("[debug] _iap.completePurchase execute ");
// }
// 🔁 去重措施 3:所有恢复交易处理完后,统一刷新一次状态(防多次通知)
final hasRestored = purchaseDetailsList.any((d) => d.status == PurchaseStatus.restored);
if (hasRestored) {
// 统一通知 UI 更新,避免多次刷新
onSuccess?.call('购买已恢复');
onStateChanged?.call();
}
}
}
// ---------- 服务端验证收据 ----------
Future<bool> _verifyReceipt(PurchaseDetails purchaseDetails,String orderid,String userid,String scence) async {
debugPrint("[debug] ############## _verifyReceipt is checking 3 ["+scence+"] "+purchaseDetails.productID+" orderid:"+orderid+" userid:"+userid);
if (orderid != null && orderid.length > 6) {
debugPrint("[debug] ############## _verifyReceipt is start scence ["+scence+"] "+purchaseDetails.productID+" orderid:"+orderid);
// 将收据发送到你的后端进行验证
final String receipt = purchaseDetails.verificationData.serverVerificationData;
// 把 base64Receipt 作为 receipt-data 发给你的服务端验证
final bool isValid = await _sendReceiptToBackend(userid,receipt,orderid);
if (isValid) {
// 更新本地订阅状态
_hasActiveSubscription = true;
// 保存到期时间等信息
}
return isValid;
}
return false;
}
// 示例:发送收据到自己的服务器进行二次验证
Future<bool> _sendReceiptToBackend(String userid,String receipt,String orderid) async {
var result = await _userAuthRepository.orderCheck(userid,receipt,orderid,"ios",1);
debugPrint("[info] ############## _sendReceiptToBackend is done");
return result!=null;
}
// ---------- 辅助方法 ----------
bool _isSubscription(String productId) {
return productId == monthlySubId_1 || productId == monthlySubId_3|| productId == monthlySubId_6|| productId == monthlySubId_12;
}
void _handlePurchaseError(IAPError error) {
// 根据 error.code 显示不同提示
debugPrint('购买失败: ${error.message}');
}
// ---------- 购买成功处理 ----------
Future<void> _handlePurchaseSuccess(PurchaseDetails detail,String orderId,String userId) async {
// 发送收据到后端验证,携带 userId
final ok = await _verifyReceipt(detail,orderId??'',userId??'',"purchased");
if(ok){
_hasActiveSubscription = true;
if(detail.pendingCompletePurchase){
await _iap.completePurchase(detail);
}
}else{
// 不complete
// 等待下次重新验证
}
}
// ---------- 恢复成功处理 ----------
Future<void> _handleRestoreSuccess(PurchaseDetails detail,String orderId,String userId) async{
// 注意:这里只是处理单个 restored,但最终 UI 刷新在 _onPurchaseUpdate 统一完成
final ok = await _verifyReceipt(detail,orderId??'',userId??'',"restored");
if(ok){
if(detail.pendingCompletePurchase){
await _iap.completePurchase(detail);
}
}
}
// ---------- 错误处理 ----------
void _handleError(PurchaseDetails detail) {
_pendingContexts.remove(detail.productID);
_iap.completePurchase(detail);
onError?.call('支付失败: ${detail.error?.message}');
}
// ---------- 取消处理 ----------
void _handleCancel(PurchaseDetails detail) {
_pendingContexts.remove(detail.productID);
_iap.completePurchase(detail);
onError?.call('支付已取消');
}
// 释放资源
Future<void> dispose() async {
await _purchaseUpdatedSubscription.cancel();
}
}
import 'package:appframe/config/routes.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
///
/// 用于重新加载的中间路由
/// 通知点击等场景先跳转到此页,再转发 targetUrl 到 /web,
/// 确保 GoRouter 完整重建 WebPage 并加载目标 URL。
///
class ReloadPage extends StatefulWidget {
const ReloadPage({super.key});
......@@ -23,8 +26,13 @@ class _ReloadPageState extends State<ReloadPage> {
}
void _performPostDisplayOperations() {
final extra = GoRouterState.of(context).extra;
if (extra is Map<String, dynamic> && extra['targetUrl'] != null) {
router.go('/web', extra: extra);
} else {
router.go('/web');
}
}
@override
Widget build(BuildContext context) {
......
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:appframe/services/subscription_service_ios.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
// subscription_page.dart
class SubscriptionPage extends StatefulWidget {
const SubscriptionPage({super.key});
@override
State<SubscriptionPage> createState() => _SubscriptionPageState();
}
class _SubscriptionPageState extends State<SubscriptionPage> {
final SubscriptionService _subService = SubscriptionService();
bool _isInitialized = false;
@override
void initState() {
super.initState();
_initService();
}
Future<void> _initService() async {
await _subService.initialize();
setState(() => _isInitialized = true);
}
Future<void> _buy(ProductDetails product) async {
if (!_isInitialized) return;
try {
await _subService.buySubscription(product,"","","");
} catch (e) {
// 显示出错信息
debugPrint(e.toString());
}
}
@override
Widget build(BuildContext context) {
if (!_isInitialized) return CircularProgressIndicator();
// return ListView.builder(
// itemCount: _subService.products.length,
// itemBuilder: (context, index) {
// final product = _subService.products[index];
// return ListTile(
// title: Text(product.title),
// subtitle: Text(product.id),
// trailing: ElevatedButton(
// onPressed: () => _buy(product),
// child: Text(product.price),
// ),
// );
// },
// );
return Scaffold(
body: Center(
child: ListView.builder(
itemCount: _subService.products.length,
itemBuilder: (context, index) {
final product = _subService.products[index];
return ListTile(
title: Text(product.title),
subtitle: Text(product.description),
trailing: ElevatedButton(
onPressed: () => _buy(product),
child: Text(product.price),
),
);
},
),
),
);
}
@override
void dispose() {
// _subService.dispose();
super.dispose();
}
}
\ No newline at end of file
......@@ -25,6 +25,7 @@ class WebPage extends StatelessWidget {
var classCode = extraData?['classCode'];
var userType = extraData?['userType'];
var stuId = extraData?['stuId'];
var targetUrl = extraData?['targetUrl'];
if (sessionCode == null || sessionCode == '') {
loginOpFlag = false;
......@@ -49,6 +50,7 @@ class WebPage extends StatelessWidget {
classCode: classCode,
userType: userType,
stuId: stuId,
targetUrl: targetUrl,
),
);
return webCubit;
......
import 'dart:convert';
import 'package:appframe/config/constant.dart';
import 'package:appframe/config/locator.dart';
import 'package:appframe/config/routes.dart';
......@@ -89,6 +91,8 @@ class LoginUtil {
sharedPreferences.setString('auth_className', className);
sharedPreferences.setString('auth_stuName', stuName);
sharedPreferences.setString('auth_relation', relation);
// 用于处理点击推送通知时,获取跳转到指定页面的参数
sharedPreferences.setString('auth_roles', jsonEncode(roles));
if (loginType == 'router') {
router.go(
......
......@@ -12,9 +12,11 @@ import device_info_plus
import ffmpeg_kit_flutter_new
import file_picker
import flutter_image_compress_macos
import flutter_local_notifications
import flutter_localization
import flutter_sound
import geolocator_apple
import in_app_purchase_storekit
import mobile_scanner
import network_info_plus
import open_file_mac
......@@ -23,10 +25,12 @@ import path_provider_foundation
import photo_manager
import shared_preferences_foundation
import sign_in_with_apple
import sqflite_darwin
import tencent_cloud_chat_sdk
import url_launcher_macos
import video_player_avfoundation
import volume_controller
import wakelock_plus
import webview_flutter_wkwebview
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
......@@ -37,9 +41,11 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
FFmpegKitFlutterPlugin.register(with: registry.registrar(forPlugin: "FFmpegKitFlutterPlugin"))
FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin"))
FlutterImageCompressMacosPlugin.register(with: registry.registrar(forPlugin: "FlutterImageCompressMacosPlugin"))
FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin"))
FlutterLocalizationPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalizationPlugin"))
FlutterSoundPlugin.register(with: registry.registrar(forPlugin: "FlutterSoundPlugin"))
GeolocatorPlugin.register(with: registry.registrar(forPlugin: "GeolocatorPlugin"))
InAppPurchasePlugin.register(with: registry.registrar(forPlugin: "InAppPurchasePlugin"))
MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin"))
NetworkInfoPlusPlugin.register(with: registry.registrar(forPlugin: "NetworkInfoPlusPlugin"))
OpenFilePlugin.register(with: registry.registrar(forPlugin: "OpenFilePlugin"))
......@@ -48,9 +54,11 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
PhotoManagerPlugin.register(with: registry.registrar(forPlugin: "PhotoManagerPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
SignInWithApplePlugin.register(with: registry.registrar(forPlugin: "SignInWithApplePlugin"))
SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin"))
TencentCloudChatSdkPlugin.register(with: registry.registrar(forPlugin: "TencentCloudChatSdkPlugin"))
UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))
FVPVideoPlayerPlugin.register(with: registry.registrar(forPlugin: "FVPVideoPlayerPlugin"))
VolumeControllerPlugin.register(with: registry.registrar(forPlugin: "VolumeControllerPlugin"))
WakelockPlusMacosPlugin.register(with: registry.registrar(forPlugin: "WakelockPlusMacosPlugin"))
WebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "WebViewFlutterPlugin"))
}
......@@ -6,7 +6,7 @@ fi
env=$1
_rebuild_=$2
_main_ver='1.0.'
_main_ver='1.1.'
_ver=`date +%y%m%d%H%M`
base_root='/Users/ethanlam/works/gitlab/flutter_pros/appframe.git'
......
name: appframe
description: "app frame project."
publish_to: 'none'
version: 1.1.0+8
version: 1.1.4
environment:
sdk: ">=3.5.0 <4.0.0"
......@@ -62,6 +62,8 @@ dependencies:
# --- Apple 登录 ---
sign_in_with_apple: ^7.0.1
in_app_purchase: ^3.2.3 # 使用最新稳定版
http: ^1.2.0 # 用于服务端验证
# --- 音视频与直播 (重灾区) ---
# 确保 ffmpeg_kit 版本与你的架构兼容。
......@@ -95,6 +97,7 @@ dependencies:
cupertino_icons: ^1.0.8
fluttertoast: ^9.0.0
flutter_local_notifications: ^19.5.0
dev_dependencies:
flutter_test:
......
......@@ -14,6 +14,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
flutter_local_notifications_windows
)
set(PLUGIN_BUNDLED_LIBRARIES)
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!