feat: add payment

This commit is contained in:
2026-07-05 16:03:15 +03:30
parent c2356b3242
commit 5017e9a613
30 changed files with 470 additions and 65 deletions
@@ -52,7 +52,7 @@ class _MobileScreenState extends State<MobileScreen> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const GlowText('سلطان حکم', size: 40),
const GlowText('حاکم ایرانی', size: 40),
const SizedBox(height: 28),
GamePanel(
padding: const EdgeInsets.all(22),
@@ -19,12 +19,16 @@ class ShopApiProvider {
required String kind,
required String productId,
required String token,
String purchaseData = '',
String signature = '',
}) =>
_api.post('/shop/purchase', body: {
'store': store,
'kind': kind,
'product_id': productId,
'token': token,
'purchase_data': purchaseData,
'signature': signature,
});
Future<Response> adReward(String token) =>
@@ -9,6 +9,7 @@ class ShopMapper {
vipDays: (j['vip_days'] ?? 0) as int,
priceToman: (j['price_toman'] ?? 0) as int,
bonusPct: (j['bonus_pct'] ?? 0) as int,
sku: (j['sku'] ?? '') as String,
);
static TicketPackage ticket(Map<String, dynamic> j) => TicketPackage(
@@ -16,6 +17,7 @@ class ShopMapper {
title: j['title'] as String,
tickets: (j['tickets'] ?? 0) as int,
priceToman: (j['price_toman'] ?? 0) as int,
sku: (j['sku'] ?? '') as String,
);
static CardSkin card(Map<String, dynamic> j) => CardSkin(
@@ -30,6 +32,7 @@ class ShopMapper {
multiplier: (j['multiplier'] ?? 1) as int,
hours: (j['hours'] ?? 0) as int,
priceToman: (j['price_toman'] ?? 0) as int,
sku: (j['sku'] ?? '') as String,
);
static VipPackage vip(Map<String, dynamic> j) => VipPackage(
@@ -37,6 +40,7 @@ class ShopMapper {
title: j['title'] as String,
months: (j['months'] ?? 1) as int,
priceToman: (j['price_toman'] ?? 0) as int,
sku: (j['sku'] ?? '') as String,
);
static ShopData shopData(Map<String, dynamic> j) {
@@ -43,6 +43,8 @@ class ShopRepositoryImpl extends ShopRepository {
kind: params.kind,
productId: params.productId,
token: params.token,
purchaseData: params.purchaseData,
signature: params.signature,
);
if (res.statusCode == 200) return const DataSuccess('خرید با موفقیت انجام شد');
return DataError(errorConvertor(res.statusCode, _msg(res)));
@@ -6,6 +6,7 @@ class CoinPackage {
final int vipDays;
final int priceToman;
final int bonusPct;
final String sku; // شناسه‌ی محصول در پنلِ فروشگاه (برای پرداختِ native)
const CoinPackage({
required this.id,
required this.title,
@@ -13,6 +14,7 @@ class CoinPackage {
required this.vipDays,
required this.priceToman,
required this.bonusPct,
this.sku = '',
});
}
@@ -21,11 +23,13 @@ class TicketPackage {
final String title;
final int tickets;
final int priceToman;
final String sku;
const TicketPackage({
required this.id,
required this.title,
required this.tickets,
required this.priceToman,
this.sku = '',
});
}
@@ -43,12 +47,14 @@ class Booster {
final int multiplier;
final int hours;
final int priceToman;
final String sku;
const Booster({
required this.id,
required this.title,
required this.multiplier,
required this.hours,
required this.priceToman,
this.sku = '',
});
}
@@ -57,11 +63,13 @@ class VipPackage {
final String title;
final int months;
final int priceToman;
final String sku;
const VipPackage({
required this.id,
required this.title,
required this.months,
required this.priceToman,
this.sku = '',
});
}
@@ -1,5 +1,6 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/payment/payment_gateway.dart';
import '../../../../core/resources/data_state.dart';
import '../../../../core/usecase/use_case.dart';
import '../../domain/use_cases/ad_reward_usecase.dart';
@@ -17,6 +18,7 @@ class ShopBloc extends Bloc<ShopEvent, ShopBlocState> {
final SelectCardUseCase selectCardUseCase;
final PurchaseUseCase purchaseUseCase;
final AdRewardUseCase adRewardUseCase;
final PaymentGateway gateway;
ShopBloc(
this.getShopUseCase,
@@ -24,6 +26,7 @@ class ShopBloc extends Bloc<ShopEvent, ShopBlocState> {
this.selectCardUseCase,
this.purchaseUseCase,
this.adRewardUseCase,
this.gateway,
) : super(ShopBlocState.initial()) {
on<LoadShopEvent>((event, emit) => _load(emit));
@@ -33,15 +36,7 @@ class ShopBloc extends Bloc<ShopEvent, ShopBlocState> {
on<SelectCardEvent>((event, emit) =>
_action(emit, () => selectCardUseCase(event.cardId)));
on<PurchaseEvent>((event, emit) => _action(
emit,
() => purchaseUseCase(PurchaseParams(
store: 'bazaar',
kind: event.kind,
productId: event.productId,
token:
'dev-${event.kind}-${event.productId}-${DateTime.now().millisecondsSinceEpoch}',
))));
on<PurchaseEvent>((event, emit) => _action(emit, () => _purchase(event)));
on<AdRewardEvent>((event, emit) => _action(
emit,
@@ -56,6 +51,42 @@ class ShopBloc extends Bloc<ShopEvent, ShopBlocState> {
));
}
/// جریانِ خرید: ابتدا پرداختِ فروشگاهی (native) اجرا می‌شود، سپس مدرکِ خرید
/// (token/purchaseData/signature) برای اعتبارسنجی به بک‌اند فرستاده می‌شود و
/// در پایان، خرید در فروشگاه consume می‌شود.
Future<DataState<String>> _purchase(PurchaseEvent event) async {
// برای پرداختِ native به SKUِ فروشگاه نیاز است؛ اگر تنظیم نشده باشد از
// شناسه‌ی کاتالوگ استفاده می‌کنیم (حالتِ توسعه/تک‌فروشگاهی).
final sku = event.sku.isNotEmpty ? event.sku : event.productId;
final PurchaseResult result;
try {
result = await gateway.purchase(sku);
} catch (e) {
return DataError<String>('خطا در پرداخت: $e');
}
if (!result.success) {
return DataError<String>('خرید انجام نشد یا لغو شد');
}
final verify = await purchaseUseCase(PurchaseParams(
store: gateway.store,
kind: event.kind,
productId: event.productId,
token: result.token,
purchaseData: result.purchaseData,
signature: result.signature,
));
// پس از تأییدِ بک‌اند، خرید را در فروشگاه نهایی/مصرف می‌کنیم.
if (verify is DataSuccess && result.onConfirmed != null) {
try {
await result.onConfirmed!();
} catch (_) {/* consume ناموفق حیاتی نیست */}
}
return verify;
}
Future<void> _load(Emitter<ShopBlocState> emit) async {
emit(state.copyWith(loadStatus: ShopLoading()));
final res = await getShopUseCase(const NoParams());
@@ -14,8 +14,9 @@ class SelectCardEvent extends ShopEvent {
class PurchaseEvent extends ShopEvent {
final String kind;
final String productId;
PurchaseEvent(this.kind, this.productId);
final String productId; // شناسه‌ی کاتالوگ (برای اعتباردهی در بک‌اند)
final String sku; // شناسه‌ی محصول در پنلِ فروشگاه (برای پرداختِ native)
PurchaseEvent(this.kind, this.productId, {this.sku = ''});
}
class AdRewardEvent extends ShopEvent {}
@@ -211,7 +211,7 @@ class _CoinsTab extends StatelessWidget {
label: '${p.priceToman} تومان',
onTap:
() =>
context.read<ShopBloc>().add(PurchaseEvent('coin', p.id)),
context.read<ShopBloc>().add(PurchaseEvent('coin', p.id, sku: p.sku)),
),
),
],
@@ -237,7 +237,7 @@ class _TicketsTab extends StatelessWidget {
label: '${p.priceToman} تومان',
onTap:
() => context.read<ShopBloc>().add(
PurchaseEvent('ticket', p.id),
PurchaseEvent('ticket', p.id, sku: p.sku),
),
),
),
@@ -264,7 +264,7 @@ class _BoostersTab extends StatelessWidget {
label: '${b.priceToman} تومان',
onTap:
() => context.read<ShopBloc>().add(
PurchaseEvent('booster', b.id),
PurchaseEvent('booster', b.id, sku: b.sku),
),
),
),
@@ -292,7 +292,7 @@ class _VipTab extends StatelessWidget {
label: '${p.priceToman} تومان',
onTap:
() =>
context.read<ShopBloc>().add(PurchaseEvent('vip', p.id)),
context.read<ShopBloc>().add(PurchaseEvent('vip', p.id, sku: p.sku)),
),
),
],
@@ -110,7 +110,7 @@ class VipScreen extends StatelessWidget {
busy: state.busy,
onBuy: () => context
.read<ShopBloc>()
.add(PurchaseEvent('vip', p.id)),
.add(PurchaseEvent('vip', p.id, sku: p.sku)),
),
),
if (packages.isEmpty)
@@ -41,10 +41,12 @@ class _LobbyScreenState extends State<LobbyScreen> {
final d = state.dailyStatus;
if (d is DailySuccess) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('سکه روزانه دریافت شد: +${d.amount}')));
SnackBar(content: Text('سکه روزانه دریافت شد: +${d.amount}')),
);
} else if (d is DailyError) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(d.message)));
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(d.message)));
}
},
builder: (context, state) {
@@ -60,13 +62,16 @@ class _LobbyScreenState extends State<LobbyScreen> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const GlowText('سلطان حکم', size: 44),
const GlowText('حاکم ایرانی', size: 44),
const SizedBox(height: 44),
GameButton(
label: 'بازی',
icon: Icons.style,
width: double.infinity,
colors: const [Color(0xFFC2185B), Color(0xFF6A0D38)],
colors: const [
Color(0xFFC2185B),
Color(0xFF6A0D38),
],
onTap: () async {
await context.push('/game/tiers');
if (context.mounted) _reload();
@@ -77,7 +82,10 @@ class _LobbyScreenState extends State<LobbyScreen> {
label: 'دورهمی',
icon: Icons.group_add,
width: double.infinity,
colors: const [Color(0xFF1565C0), Color(0xFF0A2E57)],
colors: const [
Color(0xFF1565C0),
Color(0xFF0A2E57),
],
onTap: () async {
await context.push('/private');
if (context.mounted) _reload();
@@ -88,7 +96,10 @@ class _LobbyScreenState extends State<LobbyScreen> {
label: 'رتبه‌بندی',
icon: Icons.leaderboard,
width: double.infinity,
colors: const [Color(0xFFE9952F), Color(0xFF9C5A00)],
colors: const [
Color(0xFFE9952F),
Color(0xFF9C5A00),
],
onTap: () => context.push('/leaderboard'),
),
const SizedBox(height: 16),
@@ -96,7 +107,10 @@ class _LobbyScreenState extends State<LobbyScreen> {
label: 'فروشگاه',
icon: Icons.storefront,
width: double.infinity,
colors: const [Color(0xFF7B1FA2), Color(0xFF3E0A57)],
colors: const [
Color(0xFF7B1FA2),
Color(0xFF3E0A57),
],
onTap: () => _openShop(context),
),
const SizedBox(height: 16),
@@ -104,9 +118,14 @@ class _LobbyScreenState extends State<LobbyScreen> {
label: 'سکه روزانه',
icon: Icons.monetization_on,
width: double.infinity,
colors: const [AppColors.success, AppColors.successDark],
onTap: () =>
context.read<WalletBloc>().add(ClaimDailyEvent()),
colors: const [
AppColors.success,
AppColors.successDark,
],
onTap:
() => context.read<WalletBloc>().add(
ClaimDailyEvent(),
),
),
],
),
@@ -119,8 +138,10 @@ class _LobbyScreenState extends State<LobbyScreen> {
context.go('/login');
},
icon: const Icon(Icons.logout, color: Colors.white54),
label: const Text('خروج',
style: TextStyle(color: Colors.white54)),
label: const Text(
'خروج',
style: TextStyle(color: Colors.white54),
),
),
const SizedBox(height: 8),
],
@@ -176,9 +197,10 @@ class _TopBar extends StatelessWidget {
color: AppColors.panel,
border: Border.all(color: AppColors.gold, width: 2),
),
child: (w == null || w.avatar.isEmpty)
? const Icon(Icons.person, color: AppColors.gold)
: ClipOval(child: RandomAvatar(w.avatar)),
child:
(w == null || w.avatar.isEmpty)
? const Icon(Icons.person, color: AppColors.gold)
: ClipOval(child: RandomAvatar(w.avatar)),
),
),
const SizedBox(width: 10),
@@ -186,23 +208,35 @@ class _TopBar extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(children: [
if (w != null && w.name.isNotEmpty) ...[
Text(w.name,
Row(
children: [
if (w != null && w.name.isNotEmpty) ...[
Text(
w.name,
style: const TextStyle(
color: Colors.white, fontWeight: FontWeight.bold)),
const SizedBox(width: 6),
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
const SizedBox(width: 6),
],
if (w?.vip == true) const _VipTag(),
],
if (w?.vip == true) const _VipTag(),
]),
),
const SizedBox(height: 2),
Row(children: [
const Icon(Icons.star, color: AppColors.gold, size: 16),
const SizedBox(width: 4),
Text('سطح ${w?.level ?? '-'}',
Row(
children: [
const Icon(Icons.star, color: AppColors.gold, size: 16),
const SizedBox(width: 4),
Text(
'سطح ${w?.level ?? '-'}',
style: const TextStyle(
color: AppColors.gold, fontWeight: FontWeight.bold)),
]),
color: AppColors.gold,
fontWeight: FontWeight.bold,
),
),
],
),
const SizedBox(height: 4),
ClipRRect(
borderRadius: BorderRadius.circular(4),
@@ -210,9 +244,10 @@ class _TopBar extends StatelessWidget {
width: 96,
height: 7,
child: LinearProgressIndicator(
value: (w == null || w.xpForNext == 0)
? 0
: w.xpIntoLevel / w.xpForNext,
value:
(w == null || w.xpForNext == 0)
? 0
: w.xpIntoLevel / w.xpForNext,
backgroundColor: Colors.white10,
valueColor: const AlwaysStoppedAnimation(AppColors.gold),
),
@@ -224,13 +259,17 @@ class _TopBar extends StatelessWidget {
GestureDetector(
onTap: onCoinTap,
child: StatChip(
icon: Icons.confirmation_number, value: '${w?.tickets ?? 0}'),
icon: Icons.confirmation_number,
value: '${w?.tickets ?? 0}',
),
),
const SizedBox(width: 8),
GestureDetector(
onTap: onCoinTap,
child: StatChip(
icon: Icons.monetization_on, value: '${w?.coins ?? 0}'),
icon: Icons.monetization_on,
value: '${w?.coins ?? 0}',
),
),
],
),
@@ -246,14 +285,18 @@ class _VipTag extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFFFFD54F), AppColors.goldDark]),
colors: [Color(0xFFFFD54F), AppColors.goldDark],
),
borderRadius: BorderRadius.circular(6),
),
child: const Text('VIP',
style: TextStyle(
color: AppColors.bg,
fontWeight: FontWeight.bold,
fontSize: 10)),
child: const Text(
'VIP',
style: TextStyle(
color: AppColors.bg,
fontWeight: FontWeight.bold,
fontSize: 10,
),
),
);
}
}