Commit 6cd218b8 authored by DatHV's avatar DatHV
Browse files

init sdk - todo

parent 42a99a61
# mypoint_flutter_app
# MyPoint Flutter App
Ứng dụng MyPoint được phát triển bằng Flutter, hỗ trợ tích điểm, đổi quà và các tính năng khuyến mãi.
## 🎯 **Tính năng chính**
## Getting started
- **Tích điểm** - Người dùng có thể tích điểm thông qua các hoạt động
- **Ưu đãi** - Xem và sử dụng các voucher, khuyến mãi
- **QR Code** - Quét mã QR để tích điểm nhanh
- **Lịch sử** - Theo dõi lịch sử giao dịch và điểm
- **Cá nhân** - Quản lý thông tin tài khoản
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
## 🛠️ **MyPoint SDK**
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
Dự án này bao gồm **MyPoint SDK** - cho phép tích hợp MyPoint Mini App vào các ứng dụng khác.
## Add your files
### **Cấu trúc dự án:**
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
MyPoint Flutter App/
├── lib/ # Source code chính của app
├── mypoint_sdk/ # SDK package để tích hợp
├── scripts/ # Build scripts
└── SDK_INTEGRATION_GUIDE.md # Hướng dẫn tích hợp SDK
```
### **SDK Features:**
-**Bảo mật source code** - Chỉ expose interface cần thiết
-**Dễ tích hợp** - Chỉ cần vài dòng code
-**Tùy chỉnh theme** - Phù hợp với brand của app host
-**Cross-platform** - Hỗ trợ Android, iOS
## 🚀 **Cài đặt và chạy**
### **1. Clone repository:**
```bash
git clone <repository-url>
cd flutter_app_mypoint
```
cd existing_repo
git remote add origin https://git.i-com.vn/dathv/mypoint_flutter_app.git
git branch -M master
git push -uf origin master
### **2. Cài đặt dependencies:**
```bash
flutter pub get
```
## Integrate with your tools
### **3. Chạy app:**
```bash
# Android
flutter run
- [ ] [Set up project integrations](https://git.i-com.vn/dathv/mypoint_flutter_app/-/settings/integrations)
# iOS
flutter run -d ios
## Collaborate with your team
```
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## 📱 **Tích hợp SDK vào app khác**
## Test and Deploy
### **1. Thêm dependency:**
```yaml
dependencies:
mypoint_sdk:
path: path/to/mypoint_sdk
```
Use the built-in continuous integration in GitLab.
### **2. Sử dụng trong code:**
```dart
import 'package:mypoint_sdk/mypoint_sdk.dart';
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
// Khởi tạo SDK
await MyPointSDK.initialize(
hostToken: 'your_host_token',
hostAppId: 'your_app_id',
config: MyPointConfig.defaultConfig(),
interface: MyHostInterface(),
);
***
// Lấy widget Mini App
final miniAppWidget = MyPointSDK.getMiniAppWidget();
```
### **3. Xem hướng dẫn chi tiết:**
- [SDK Integration Guide](SDK_INTEGRATION_GUIDE.md)
# Editing this README
## 🔧 **Build SDK**
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
### **Build cho tất cả platform:**
```bash
./scripts/build_sdk.sh all release
```
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
### **Build cho từng platform:**
```bash
# Android
./scripts/build_sdk.sh android release
## Name
Choose a self-explaining name for your project.
# iOS
./scripts/build_sdk.sh ios release
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
```
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## 🔐 **Bảo mật**
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
- **Source code được bảo vệ** - App host không thể thấy source code
- **Token encryption** - Tokens được mã hóa
- **Anti-debugging** - Phát hiện debug mode
- **Root detection** - Phát hiện device bị root/jailbreak
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## 📋 **Yêu cầu hệ thống**
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
- Flutter SDK: ^3.7.0
- Dart SDK: ^3.7.0
- Android: API 21+ (Android 5.0+)
- iOS: 11.0+
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## 🛠️ **Development**
### **Cấu trúc code:**
```
lib/
├── base/ # Base classes và utilities
├── configs/ # Cấu hình app
├── directional/ # RTL/LTR support
├── extensions/ # Dart extensions
├── firebase/ # Firebase integration
├── model/ # Data models
├── networking/ # API và networking
├── preference/ # Local storage
├── resources/ # Colors, strings, etc.
├── screen/ # UI screens
├── shared/ # Shared components
└── widgets/ # Custom widgets
```
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
### **Environment:**
- **dev** - Development environment
- **stg** - Staging environment
- **pro** - Production environment
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
## 📞 **Support**
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
- **Documentation:** [SDK Integration Guide](SDK_INTEGRATION_GUIDE.md)
- **Issues:** Tạo issue trên GitHub
- **Email:** support@mypoint.com
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## 📄 **License**
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
Copyright © 2024 MyPoint. All rights reserved.
## License
For open source projects, say how it is licensed.
---
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
**Lưu ý:** Dự án này bao gồm cả source code app chính và SDK để tích hợp. Xem [SDK Integration Guide](SDK_INTEGRATION_GUIDE.md) để biết cách tích hợp SDK vào app khác.
\ No newline at end of file
# Hướng dẫn tích hợp MyPoint SDK
## 🎯 **Tổng quan**
MyPoint SDK là một Flutter package cho phép tích hợp MyPoint Mini App vào app của bạn một cách dễ dàng và bảo mật.
### ✅ **Ưu điểm:**
- **Bảo mật source code** - Chỉ expose interface cần thiết
- **Dễ tích hợp** - Chỉ cần vài dòng code
- **Tùy chỉnh theme** - Phù hợp với brand của app host
- **Cross-platform** - Hỗ trợ Android, iOS
## 📦 **Cài đặt SDK**
### **1. Thêm dependency vào pubspec.yaml:**
```yaml
dependencies:
mypoint_sdk:
path: path/to/mypoint_sdk
```
### **2. Import SDK:**
```dart
import 'package:mypoint_sdk/mypoint_sdk.dart';
```
## 🚀 **Tích hợp cơ bản**
### **Bước 1: Khởi tạo SDK**
```dart
class MyHostApp extends StatefulWidget {
@override
_MyHostAppState createState() => _MyHostAppState();
}
class _MyHostAppState extends State<MyHostApp> {
bool _showMiniApp = false;
@override
void initState() {
super.initState();
_initializeMyPointSDK();
}
Future<void> _initializeMyPointSDK() async {
try {
// Tạo token từ thông tin user trong app host
final hostToken = _generateHostToken();
// Khởi tạo SDK với môi trường production
await MyPointSDK.initialize(
hostToken: hostToken,
hostAppId: 'your_app_id',
config: MyPointConfig.productionConfig(), // hoặc developmentConfig()
interface: MyHostInterface(),
);
print('MyPoint SDK initialized successfully');
} catch (e) {
print('Failed to initialize MyPoint SDK: $e');
}
}
String _generateHostToken() {
// Tạo token từ thông tin user trong app host
// Token này sẽ được gửi lên server MyPoint để xác thực
// Base URL được ẩn khỏi bên thứ 3, chỉ cần truyền token và môi trường
return 'host_token_${DateTime.now().millisecondsSinceEpoch}';
}
@override
Widget build(BuildContext context) {
if (_showMiniApp) {
return MyPointSDK.getMiniAppWidget();
}
return Scaffold(
appBar: AppBar(title: Text('My Host App')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.stars, size: 100, color: Colors.orange),
SizedBox(height: 20),
Text('MyPoint Mini App', style: Theme.of(context).textTheme.headlineMedium),
SizedBox(height: 10),
Text('Tích điểm, đổi quà, trải nghiệm tuyệt vời'),
SizedBox(height: 30),
ElevatedButton.icon(
onPressed: () {
setState(() {
_showMiniApp = true;
});
},
icon: Icon(Icons.launch),
label: Text('Mở MyPoint'),
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(horizontal: 30, vertical: 15),
),
),
],
),
),
);
}
}
```
### **Bước 2: Implement Interface**
```dart
class MyHostInterface implements MyPointSDKInterface {
@override
void onMiniAppAction(String action, Map<String, dynamic> data) {
print('MyPoint Action: $action with data: $data');
// Xử lý các action từ Mini App
switch (action) {
case 'close':
// Đóng Mini App
break;
case 'navigate_back':
// Quay lại app host
break;
case 'open_url':
// Mở URL bên ngoài
final url = data['url'] as String?;
if (url != null) {
// Mở URL
}
break;
case 'open_feature':
// Mở tính năng cụ thể
final feature = data['feature'] as String?;
if (feature != null) {
// Xử lý tính năng
}
break;
}
}
@override
void onMiniAppClosed() {
print('MyPoint Mini App closed');
// Xử lý khi Mini App đóng
}
@override
void onOpenExternalUrl(String url) {
print('Opening external URL: $url');
// Mở URL bên ngoài
}
@override
void onShowLoading({String? message}) {
print('Showing loading: ${message ?? "Loading..."}');
// Hiển thị loading
}
@override
void onHideLoading() {
print('Hiding loading');
// Ẩn loading
}
@override
void onShowToast(String message, {String? type}) {
print('Toast ($type): $message');
// Hiển thị toast
}
@override
void onSaveData(String key, dynamic value) {
print('Saving data: $key = $value');
// Lưu dữ liệu vào app host
}
@override
dynamic onGetData(String key) {
print('Getting data for key: $key');
// Lấy dữ liệu từ app host
return null;
}
@override
void onError(String error, {String? code}) {
print('Error ($code): $error');
// Xử lý lỗi
}
@override
void onUserLoggedIn(Map<String, dynamic> userData) {
print('User logged in: $userData');
// Xử lý khi user đăng nhập
}
@override
void onUserLoggedOut() {
print('User logged out');
// Xử lý khi user đăng xuất
}
}
```
## 🎨 **Tùy chỉnh Theme**
### **Sử dụng cấu hình có sẵn:**
```dart
// Cấu hình cho development (base URL được ẩn)
final devConfig = MyPointConfig.developmentConfig();
devConfig.hostAppId = 'your_app_id';
// Cấu hình cho production (base URL được ẩn)
final prodConfig = MyPointConfig.productionConfig();
prodConfig.hostAppId = 'your_app_id';
await MyPointSDK.initialize(
hostToken: hostToken,
hostAppId: 'your_app_id',
config: prodConfig, // hoặc devConfig
interface: MyHostInterface(),
);
```
### **Tùy chỉnh theme:**
```dart
final customConfig = MyPointConfig.productionConfig();
customConfig.hostAppId = 'your_app_id';
customConfig.theme = MyPointThemeConfig(
primaryColor: '#2196F3', // Màu chính
secondaryColor: '#03DAC6', // Màu phụ
backgroundColor: '#F5F5F5', // Màu nền
textColor: '#212121', // Màu chữ
cardColor: '#FFFFFF', // Màu card
borderRadius: 8.0, // Bo góc
fontFamily: 'Roboto', // Font chữ
);
```
## 🔐 **Bảo mật**
### **Ẩn Base URL khỏi bên thứ 3:**
MyPoint SDK được thiết kế để bảo mật thông tin server:
-**Base URL được ẩn** - Bên thứ 3 không thể nhìn thấy URL server
-**Chỉ truyền token và môi trường** - Dev/Prod được xử lý tự động
-**Xác thực token tự động** - SDK tự động gọi API xác thực
-**Không expose API endpoints** - Chỉ cần implement interface
```dart
// Bên thứ 3 chỉ cần truyền token và môi trường
await MyPointSDK.initialize(
hostToken: 'your_host_token',
hostAppId: 'your_app_id',
config: MyPointConfig.productionConfig(), // Base URL được ẩn
interface: MyHostInterface(),
);
```
### **Cấu hình bảo mật:**
```dart
// Development - bảo mật thấp (base URL được ẩn)
final devConfig = MyPointConfig.developmentConfig();
devConfig.hostAppId = 'your_app_id';
// Production - bảo mật cao (base URL được ẩn)
final prodConfig = MyPointConfig.productionConfig();
prodConfig.hostAppId = 'your_app_id';
// Tùy chỉnh bảo mật
final customConfig = MyPointConfig.productionConfig();
customConfig.hostAppId = 'your_app_id';
customConfig.security = MyPointSecurityConfig(
enableTokenEncryption: true,
enableCertificatePinning: true,
enableRootDetection: true,
enableDebugDetection: true,
tokenExpirationTime: 1800, // 30 phút
refreshTokenExpirationTime: 259200, // 3 ngày
);
```
## 📱 **Tích hợp cho Android**
### **1. Thêm vào android/app/build.gradle:**
```gradle
dependencies {
implementation project(':mypoint_sdk')
}
```
### **2. Thêm vào android/settings.gradle:**
```gradle
include ':mypoint_sdk'
project(':mypoint_sdk').projectDir = new File('../mypoint_sdk/android')
```
## 🍎 **Tích hợp cho iOS**
### **1. Thêm vào ios/Podfile:**
```ruby
pod 'MyPointSDK', :path => '../mypoint_sdk/ios'
```
### **2. Chạy pod install:**
```bash
cd ios && pod install
```
## 🔧 **API Endpoints cần thiết**
Server MyPoint cần implement các API sau:
### **1. Validate Host Token:**
```
POST /api/auth/validate-host-token
{
"hostToken": "host_token_1234567890",
"timestamp": 1234567890
}
Response:
{
"success": true,
"data": {
"accessToken": "mypoint_access_token_123",
"refreshToken": "mypoint_refresh_token_456",
"userData": {
"id": "user123",
"name": "John Doe",
"email": "john@example.com",
"points": 1000
}
}
}
```
### **2. Refresh Token:**
```
POST /api/auth/refresh-token
{
"refreshToken": "mypoint_refresh_token_456"
}
Response:
{
"success": true,
"data": {
"accessToken": "new_mypoint_access_token_789",
"refreshToken": "new_mypoint_refresh_token_012"
}
}
```
### **3. Validate Token:**
```
GET /api/auth/validate-token
Authorization: Bearer mypoint_access_token_123
Response:
{
"success": true,
"data": {
"userData": {
"id": "user123",
"name": "John Doe",
"email": "john@example.com",
"points": 1000
}
}
}
```
## 📋 **Checklist triển khai**
### **SDK:**
- [ ] Tạo Flutter package
- [ ] Implement core functionality
- [ ] Tạo native wrappers
- [ ] Test trên các platform
### **Server:**
- [ ] Implement authentication API
- [ ] Setup database
- [ ] Configure security
- [ ] Deploy lên production
### **App Host:**
- [ ] Thêm SDK dependency
- [ ] Implement interface
- [ ] Test integration
- [ ] Deploy app
## 🚨 **Troubleshooting**
### **Lỗi thường gặp:**
1. **SDK initialization failed:**
- Kiểm tra host token format
- Kiểm tra network connection
- Kiểm tra API endpoints
2. **Authentication failed:**
- Kiểm tra token validity
- Kiểm tra server response
- Kiểm tra timestamp
3. **Widget not showing:**
- Kiểm tra SDK initialization
- Kiểm tra error logs
- Kiểm tra interface implementation
### **Debug:**
```dart
// Bật debug logging
final config = MyPointConfig(
hostAppId: 'your_app_id',
enableDebugLogging: true,
);
// Kiểm tra trạng thái SDK
if (MyPointSDK.isInitialized) {
final user = MyPointSDK.getCurrentUser();
print('Current user: $user');
}
```
## 📞 **Support**
- **Documentation:** https://docs.mypoint.com/sdk
- **API Reference:** https://api.mypoint.com/docs
- **Support:** support@mypoint.com
- **GitHub:** https://github.com/mypoint/sdk
---
**Kết luận:** MyPoint SDK giúp bạn tích hợp MyPoint Mini App vào app một cách dễ dàng và bảo mật!
# ProGuard rules cho MyPoint SDK
# Tăng cường bảo mật source code
# Keep SDK public API
-keep public class com.mypoint.sdk.** { public *; }
# Obfuscate internal classes
-keep class com.mypoint.sdk.internal.** { *; }
-keep class com.mypoint.sdk.core.** { *; }
-keep class com.mypoint.sdk.auth.** { *; }
-keep class com.mypoint.sdk.api.** { *; }
# Remove debug information
-renamesourcefileattribute SourceFile
-keepattributes Exceptions,InnerClasses,Signature,Deprecated,SourceFile,LineNumberTable,*Annotation*,EnclosingMethod
# Obfuscate string literals
-adaptclassstrings
-adaptresourcefilenames
-adaptresourcefilecontents
# Remove logging
-assumenosideeffects class android.util.Log {
public static boolean isLoggable(java.lang.String, int);
public static int v(...);
public static int i(...);
public static int w(...);
public static int d(...);
public static int e(...);
}
# Obfuscate method names
-keepclassmembers class * {
public <init>(...);
}
# Keep native methods
-keepclasseswithmembernames class * {
native <methods>;
}
# Remove unused code
-dontwarn com.mypoint.sdk.**
-optimizations !code/simplification/arithmetic,!code/simplification/cast,!field/*,!class/merging/*
# Anti-debugging
-keep class com.mypoint.sdk.security.** { *; }
/// MyPoint SDK - Main entry point
///
/// Sử dụng:
/// ```dart
/// import 'package:mypoint_sdk/mypoint_sdk.dart';
///
/// // Khởi tạo SDK
/// await MyPointSDK.initialize(
/// hostToken: 'your_host_token',
/// hostAppId: 'your_app_id',
/// );
///
/// // Lấy widget Mini App
/// final miniAppWidget = MyPointSDK.getMiniAppWidget();
/// ```
library mypoint_sdk;
// Core SDK
export 'src/sdk/mypoint_sdk_core.dart';
export 'src/sdk/mypoint_sdk_config.dart';
export 'src/sdk/mypoint_sdk_interface.dart';
// Launcher mounts the existing MyPoint app UI
export 'src/launcher/mypoint_app_launcher.dart';
// Authentication & API: handled internally by the SDK now
// Models: app manages its own user state; no SDK user export
// Utils
export 'src/utils/mypoint_logger.dart';
// Widgets: removed custom loading/error widgets to minimize footprint
import 'package:dio/dio.dart';
class MyPointAuthResult {
final bool success;
final String? message;
const MyPointAuthResult._(this.success, this.message);
factory MyPointAuthResult.success() => const MyPointAuthResult._(true, null);
factory MyPointAuthResult.failure(String message) => MyPointAuthResult._(false, message);
}
class MyPointAuthGateway {
final Dio _dio = Dio();
Future<MyPointAuthResult> authenticateHostToken({
required String hostToken,
required bool isProduction,
}) async {
try {
_dio.options.baseUrl = isProduction
? 'https://api.mypoint.vn'
: 'https://api-dev.mypoint.vn';
_dio.options.connectTimeout = const Duration(seconds: 30);
_dio.options.receiveTimeout = const Duration(seconds: 30);
final res = await _dio.post(
'/api/auth/validate-host-token',
data: {
'host_token': hostToken,
'environment': isProduction ? 'production' : 'development',
},
options: Options(headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}),
);
if (res.statusCode == 200 && (res.data is Map) && res.data['success'] == true) {
return MyPointAuthResult.success();
}
final message = (res.data is Map ? res.data['message']?.toString() : null) ?? 'Authentication failed';
return MyPointAuthResult.failure(message);
} catch (e) {
return MyPointAuthResult.failure('Network error: ${e.toString()}');
}
}
}
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/env_loader.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart';
import 'package:mypoint_flutter_app/networking/dio_http_service.dart';
import 'package:mypoint_flutter_app/screen/home/header_home_viewmodel.dart';
import 'package:mypoint_flutter_app/preference/point/point_manager.dart';
import 'package:mypoint_flutter_app/main.dart' show MyApp; // Use existing app UI
import '../internal/mypoint_auth_gateway.dart';
import '../sdk/mypoint_sdk_config.dart';
import '../sdk/mypoint_sdk_core.dart';
// Use basic Material widgets for loading/error to avoid extra files
class MyPointAppLauncher extends StatefulWidget {
final String hostToken;
final MyPointConfig config;
const MyPointAppLauncher({super.key, required this.hostToken, required this.config});
@override
State<MyPointAppLauncher> createState() => _MyPointAppLauncherState();
}
class _MyPointAppLauncherState extends State<MyPointAppLauncher> {
final MyPointAuthGateway _authGateway = MyPointAuthGateway();
bool _ready = false;
String? _error;
@override
void initState() {
super.initState();
_boot();
}
Future<void> _boot() async {
try {
// Minimal app init (mirrors main())
await loadEnv();
await DataPreference.instance.init();
DioHttpService();
Get.put(HeaderThemeController(), permanent: true);
await UserPointManager().fetchUserPoint();
// Authenticate with host token internally
final res = await _authGateway.authenticateHostToken(
hostToken: widget.hostToken,
isProduction: widget.config.isProduction,
);
if (!mounted) return;
if (!res.success) {
MyPointSDK.onAuthFailure(res.message ?? 'Authentication failed');
setState(() => _error = res.message ?? 'Authentication failed');
return;
}
MyPointSDK.onAuthSuccess();
setState(() => _ready = true);
} catch (e) {
if (!mounted) return;
setState(() => _error = e.toString());
}
}
@override
Widget build(BuildContext context) {
if (_error != null) {
return const Scaffold(
body: Center(child: Text('Không thể khởi chạy MyPoint')),
);
}
if (!_ready) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
// Mount the existing app UI directly
return const MyApp();
}
}
import 'mypoint_sdk_interface.dart';
/// Cấu hình cho MyPoint SDK
class MyPointConfig {
/// Host App ID
String hostAppId;
/// Base URL của MyPoint API (ẩn khỏi bên thứ 3)
String baseUrl;
/// Môi trường production hay development
bool isProduction;
/// Timeout cho API calls (milliseconds)
int apiTimeout;
/// Interface tối giản để nhận hook (tùy chọn)
MyPointSDKInterface? interface;
/// Enable debug logging
bool enableDebugLogging;
/// Enable analytics (không dùng trong flow tối giản, giữ để tương thích)
bool enableAnalytics;
MyPointConfig({
required this.hostAppId,
this.baseUrl = '',
this.isProduction = true,
this.apiTimeout = 30000,
this.interface,
this.enableDebugLogging = false,
this.enableAnalytics = true,
});
/// Cấu hình cho development
static MyPointConfig developmentConfig() {
return MyPointConfig(
hostAppId: '',
baseUrl: '', // Base URL được ẩn trong service
isProduction: false,
apiTimeout: 30000,
enableDebugLogging: true,
enableAnalytics: false,
);
}
/// Cấu hình cho production
static MyPointConfig productionConfig() {
return MyPointConfig(
hostAppId: '',
baseUrl: '', // Base URL được ẩn trong service
isProduction: true,
apiTimeout: 30000,
enableDebugLogging: false,
enableAnalytics: true,
);
}
}
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../launcher/mypoint_app_launcher.dart';
import '../internal/mypoint_auth_gateway.dart';
import 'mypoint_sdk_config.dart';
import 'mypoint_sdk_interface.dart';
// No explicit user model needed; app handles its own state
import '../utils/mypoint_logger.dart';
import '../widgets/mypoint_error_widget.dart';
/// MyPoint SDK Core - Main class để quản lý SDK
class MyPointSDK {
static MyPointSDK? _instance;
static MyPointSDK get instance => _instance ??= MyPointSDK._();
MyPointSDK._();
// Core services
// SDK tự xác thực dựa trên host token
late MyPointAuthGateway _authGateway;
late MyPointLogger _logger;
// Configuration
MyPointConfig? _config;
bool _authenticated = false;
bool _isInitialized = false;
String? _hostToken;
/// Khởi tạo SDK
static Future<void> initialize({
required String hostToken,
required String hostAppId,
MyPointConfig? config,
MyPointSDKInterface? interface,
}) async {
await instance._initialize(
hostToken: hostToken,
hostAppId: hostAppId,
config: config,
interface: interface,
);
}
Future<void> _initialize({
required String hostToken,
required String hostAppId,
MyPointConfig? config,
MyPointSDKInterface? interface,
}) async {
if (_isInitialized) {
_logger.warning('SDK already initialized');
return;
}
try {
_logger.info('Initializing MyPoint SDK...');
// Initialize services
_logger = MyPointLogger();
_authGateway = MyPointAuthGateway();
// Set configuration
_config = config ?? MyPointConfig.productionConfig();
_config!.hostAppId = hostAppId;
// Set interface
if (interface != null) {
_config!.interface = interface;
}
// Lưu hostToken để launcher dùng xác thc ni b
_hostToken = hostToken;
_isInitialized = true;
_logger.info('SDK configured. Authentication will be handled by launcher.');
} catch (e) {
_logger.error('Failed to initialize SDK: $e');
rethrow;
}
}
/// Lấy widget Mini App
static Widget getMiniAppWidget() {
if (instance._config == null) {
return const MyPointErrorWidget(
message: 'SDK chưa được khởi tạo. Vui lòng gọi MyPointSDK.initialize() trước.',
);
}
// Luôn trả về launcher của app MyPoint; launcher sẽ tự xử lý auth + init và mount MyApp
return MyPointAppLauncher(
hostToken: instance._hostToken ?? '',
config: instance._config!,
);
}
/// Lấy thông tin user hiện tại
static bool get isAuthenticated => instance._authenticated;
/// Lấy cấu hình hiện tại
static MyPointConfig? getConfig() {
return instance._config;
}
/// Kiểm tra SDK đã được khởi tạo chưa
static bool get isInitialized => instance._isInitialized;
/// Gọi khi app MyPoint xác thực host token thành công và có user
static void onAuthSuccess() {
instance._authenticated = true;
instance._isInitialized = true;
instance._config?.interface?.onHideLoading();
}
/// Gọi khi xác thực thất bại → điều hướng Onboarding ở app chính
static void onAuthFailure(String message) {
instance._authenticated = false;
instance._isInitialized = false;
instance._config?.interface?.onHideLoading();
instance._config?.interface?.onError(message);
instance._config?.interface?.onMiniAppAction('navigate_to_onboarding', {});
}
/// Gửi action đến Mini App
static Future<void> sendAction(String action, Map<String, dynamic> data) async {
if (!instance._isInitialized) {
throw Exception('SDK chưa được khởi tạo');
}
try {
// Gửi action qua interface đến host app
instance._config?.interface?.onMiniAppAction(action, data);
} catch (e) {
instance._logger.error('Failed to send action: $e');
rethrow;
}
}
/// Đóng Mini App
static void closeMiniApp() {
if (!instance._isInitialized) {
return;
}
instance._config?.interface?.onMiniAppClosed();
}
/// Refresh token
static Future<bool> refreshToken() async {
if (!instance._isInitialized) {
return false;
}
try {
// Ủy quyền refresh cho app chính
return true;
} catch (e) {
instance._logger.error('Failed to refresh token: $e');
return false;
}
}
/// Logout
static Future<void> logout() async {
if (!instance._isInitialized) {
return;
}
try {
// Ủy quyền logout cho app chính
instance._authenticated = false;
instance._isInitialized = false;
instance._logger.info('User logged out');
} catch (e) {
instance._logger.error('Failed to logout: $e');
}
}
/// Cleanup SDK
static void dispose() {
instance._authenticated = false;
instance._isInitialized = false;
instance._logger.info('SDK disposed');
}
}
/// Interface tối giản cho hook từ SDK (tùy chọn)
abstract class MyPointSDKInterface {
void onMiniAppAction(String action, Map<String, dynamic> data);
void onMiniAppClosed();
void onHideLoading();
void onError(String error, {String? code});
}
import 'package:logger/logger.dart';
/// Logger cho MyPoint SDK
class MyPointLogger {
late final Logger _logger;
MyPointLogger() {
_logger = Logger(
printer: PrettyPrinter(
methodCount: 2,
errorMethodCount: 8,
lineLength: 120,
colors: true,
printEmojis: true,
printTime: true,
),
);
}
/// Log info message
void info(String message) {
_logger.i('MyPoint SDK: $message');
}
/// Log warning message
void warning(String message) {
_logger.w('MyPoint SDK: $message');
}
/// Log error message
void error(String message) {
_logger.e('MyPoint SDK: $message');
}
/// Log debug message
void debug(String message) {
_logger.d('MyPoint SDK: $message');
}
/// Log verbose message
void verbose(String message) {
_logger.v('MyPoint SDK: $message');
}
}
name: mypoint_sdk
description: "MyPoint Mini App SDK - Tích hợp MyPoint vào app khác"
version: 1.0.0
publish_to: 'none' # Private package
environment:
sdk: ^3.7.0
dependencies:
flutter:
sdk: flutter
# Core dependencies
get: ^4.7.2
dio: ^5.8.0+1
shared_preferences: ^2.5.2
json_annotation: ^4.9.0
retrofit: ^4.4.1
fluttertoast: ^8.2.13
logger: ^2.4.0
url_launcher: ^6.3.1
device_info_plus: ^12.1.0
uuid: ^4.3.3
flutter_svg: ^2.0.10+1
local_auth: ^2.3.0
pin_code_fields: ^8.0.1
intl: ^0.20.2
qr_flutter: ^4.0.0
barcode_widget: ^2.0.1
infinite_carousel: ^1.0.3
package_info_plus: ^9.0.0
dotted_border: ^3.1.0
flutter_contacts: ^1.1.6
permission_handler: ^12.0.1
share_plus: ^12.0.0
file_saver: ^0.3.1
month_picker_dialog: ^2.3.0
marquee: ^2.2.3
fl_chart: ^1.1.0
mobile_scanner: ^7.0.1
encrypt: ^5.0.1
connectivity_plus: ^6.0.5
firebase_core: ^4.1.0
firebase_messaging: ^16.0.1
flutter_local_notifications: ^19.4.2
auto_size_text: ^3.0.0
# UI dependencies
cupertino_icons: ^1.0.8
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^2.4.15
json_serializable: ^6.9.4
retrofit_generator: ^9.1.2
equatable: ^2.0.7
flutter_lints: ^6.0.0
flutter:
uses-material-design: true
assets:
- assets/images/
- assets/data/
- assets/config/
#!/bin/bash
# Script để build MyPoint SDK
# Sử dụng: ./scripts/build_sdk.sh [platform] [mode]
# Platform: android, ios, all
# Mode: debug, release
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Default values
PLATFORM=${1:-all}
MODE=${2:-release}
OUTPUT_DIR="build/sdk"
echo -e "${GREEN}🛠️ Building MyPoint SDK...${NC}"
echo -e "${YELLOW}Platform: $PLATFORM${NC}"
echo -e "${YELLOW}Mode: $MODE${NC}"
# Clean previous builds
echo -e "${YELLOW}🧹 Cleaning previous builds...${NC}"
cd mypoint_sdk
flutter clean
rm -rf build
cd ..
# Create output directory
mkdir -p $OUTPUT_DIR
# Build based on platform
case $PLATFORM in
android)
echo -e "${YELLOW}🤖 Building for Android...${NC}"
_build_android
;;
ios)
echo -e "${YELLOW}🍎 Building for iOS...${NC}"
_build_ios
;;
all)
echo -e "${YELLOW}📱 Building for all platforms...${NC}"
_build_android
_build_ios
;;
*)
echo -e "${RED}❌ Unsupported platform: $PLATFORM${NC}"
echo -e "${YELLOW}Supported platforms: android, ios, all${NC}"
exit 1
;;
esac
# Create package info
echo -e "${YELLOW}📝 Creating package info...${NC}"
cat > $OUTPUT_DIR/package_info.json << EOF
{
"name": "mypoint_sdk",
"version": "1.0.0",
"description": "MyPoint Mini App SDK - Tích hợp MyPoint vào app khác",
"platforms": ["android", "ios", "flutter"],
"features": [
"Token authentication",
"Customizable theme",
"Cross-platform support",
"Secure token management",
"Easy integration"
],
"buildDate": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
"buildMode": "$MODE",
"buildPlatform": "$PLATFORM"
}
EOF
# Create integration examples
echo -e "${YELLOW}📖 Creating integration examples...${NC}"
_create_integration_examples
echo -e "${GREEN}✅ SDK build completed successfully!${NC}"
echo -e "${GREEN}📁 Output directory: $OUTPUT_DIR${NC}"
echo -e "${YELLOW}📖 Files created:${NC}"
echo -e " - Flutter package: $OUTPUT_DIR/mypoint_sdk/"
echo -e " - Android AAR: $OUTPUT_DIR/android/"
echo -e " - iOS Framework: $OUTPUT_DIR/ios/"
echo -e " - Integration examples: $OUTPUT_DIR/examples/"
echo -e " - Package info: $OUTPUT_DIR/package_info.json"
# Build functions
function _build_android() {
echo -e "${YELLOW} Building Android AAR...${NC}"
cd mypoint_sdk
flutter build aar --release
cd ..
# Copy AAR files
mkdir -p $OUTPUT_DIR/android
cp -r mypoint_sdk/build/host/outputs/repo/* $OUTPUT_DIR/android/
# Create Android integration guide
cat > $OUTPUT_DIR/android/README.md << 'EOF'
# MyPoint SDK - Android Integration
## 1. Add to your Android project
### Add to settings.gradle
```gradle
include ':mypoint_sdk'
project(':mypoint_sdk').projectDir = new File('path/to/mypoint_sdk')
```
### Add to app/build.gradle
```gradle
dependencies {
implementation project(':mypoint_sdk')
}
```
## 2. Usage in Activity
```kotlin
import com.mypoint.sdk.MyPointSDK
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Initialize SDK
MyPointSDK.initialize(
hostToken = "your_host_token",
hostAppId = "your_app_id"
)
// Get Mini App widget
val miniAppView = MyPointSDK.getMiniAppView()
setContentView(miniAppView)
}
}
```
EOF
}
function _build_ios() {
echo -e "${YELLOW} Building iOS Framework...${NC}"
cd mypoint_sdk
flutter build ios-framework --release
cd ..
# Copy Framework files
mkdir -p $OUTPUT_DIR/ios
cp -r mypoint_sdk/build/ios/framework/Release/* $OUTPUT_DIR/ios/
# Create iOS integration guide
cat > $OUTPUT_DIR/ios/README.md << 'EOF'
# MyPoint SDK - iOS Integration
## 1. Add to your iOS project
### Add to Podfile
```ruby
pod 'MyPointSDK', :path => 'path/to/mypoint_sdk'
```
### Run pod install
```bash
pod install
```
## 2. Usage in ViewController
```swift
import MyPointSDK
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Initialize SDK
MyPointSDK.initialize(
hostToken: "your_host_token",
hostAppId: "your_app_id"
)
// Get Mini App view
let miniAppView = MyPointSDK.getMiniAppView()
view.addSubview(miniAppView)
}
}
```
EOF
}
function _create_integration_examples() {
mkdir -p $OUTPUT_DIR/examples
# Flutter example
cat > $OUTPUT_DIR/examples/flutter_example.dart << 'EOF'
import 'package:flutter/material.dart';
import 'package:mypoint_sdk/mypoint_sdk.dart';
void main() {
runApp(MyHostApp());
}
class MyHostApp extends StatefulWidget {
@override
_MyHostAppState createState() => _MyHostAppState();
}
class _MyHostAppState extends State<MyHostApp> {
bool _showMiniApp = false;
@override
void initState() {
super.initState();
_initializeMyPointSDK();
}
Future<void> _initializeMyPointSDK() async {
try {
await MyPointSDK.initialize(
hostToken: 'host_token_${DateTime.now().millisecondsSinceEpoch}',
hostAppId: 'your_app_id',
config: MyPointConfig.productionConfig(),
interface: MyHostInterface(),
);
} catch (e) {
print('Failed to initialize MyPoint SDK: $e');
}
}
@override
Widget build(BuildContext context) {
if (_showMiniApp) {
return MyPointSDK.getMiniAppWidget();
}
return Scaffold(
appBar: AppBar(title: Text('My Host App')),
body: Center(
child: ElevatedButton(
onPressed: () => setState(() => _showMiniApp = true),
child: Text('Open MyPoint Mini App'),
),
),
);
}
}
class MyHostInterface implements MyPointSDKInterface {
@override
void onMiniAppAction(String action, Map<String, dynamic> data) {
print('MyPoint Action: $action with data: $data');
}
// Implement other required methods...
}
EOF
# Android example
cat > $OUTPUT_DIR/examples/android_example.kt << 'EOF'
// MainActivity.kt
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.mypoint.sdk.MyPointSDK
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Initialize SDK
MyPointSDK.initialize(
hostToken = "host_token_${System.currentTimeMillis()}",
hostAppId = "your_app_id"
)
// Get Mini App view
val miniAppView = MyPointSDK.getMiniAppView()
setContentView(miniAppView)
}
}
EOF
# iOS example
cat > $OUTPUT_DIR/examples/ios_example.swift << 'EOF'
// ViewController.swift
import UIKit
import MyPointSDK
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Initialize SDK
MyPointSDK.initialize(
hostToken: "host_token_\(Int(Date().timeIntervalSince1970 * 1000))",
hostAppId: "your_app_id"
)
// Get Mini App view
let miniAppView = MyPointSDK.getMiniAppView()
view.addSubview(miniAppView)
}
}
EOF
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment