### Dart Example: Annotated Shelf Router and Application Setup Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_routing/README.md This comprehensive Dart example demonstrates how to build a web application with `shelf` and `shelf_routing_generator`. It defines a `User` model, a `UserController` with annotated routes for listing, fetching, and creating users, and an `ApiRouter` to mount the user controller. The `main` function illustrates how to initialize a database connection and serve the application using the generated router. ```dart import 'package:shelf/shelf.dart'; import 'package:shelf_router/shelf_router.dart'; import 'package:shelf_routing/shelf_routing.dart'; // generated with 'dart run build_runner build' part 'example.g.dart'; class User { final int id; final String name; const User({required this.id, required this.name}); factory User.fromJson(Map map) => User(id: map['id'], name: map['name']); Map toJson() => {'id': id, 'name': name}; } class UserController implements RouterMixin { // Create router using the generate function defined in 'example.g.dart'. @override Router get router => _$UserControllerRouter(this); final DatabaseConnection connection; UserController(this.connection); @Route.get('/') Future> listUsers(Request request, {String? query}) async { return ['user1']; } @Route.get('/') Future fetchUser(Request request, int userId) async { if (userId == 1) { return Response.ok('user1'); } return Response.notFound('no such user'); } @Route.post('/') Future> createUser(Request request, User user) async { if (user.name.isEmpty) { return JsonResponse.badRequest(body: 'Missing name field'); } return JsonResponse.ok(user); } } class ApiRouter { static const _prefix = '/api'; final DatabaseConnection connection; ApiRouter(this.connection); Router get router => _$ApiRouterRouter(this); @Route.mount('$_prefix/users') UserController get users => UserController(connection); } class DatabaseConnection { static Future connect(String _) => throw UnimplementedError(); } void main() async { // You can setup context, database connections, cache connections, email // services, before you create an instance of your service. final connection = await DatabaseConnection.connect('localhost:1234'); // Service request using the router, note the router can also be mounted. final handler = const Pipeline().addHandler(ApiRouter(connection).router); await serve(handler, 'localhost', 8080); } ``` -------------------------------- ### Annotated Dart API Routing Example Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_routing_generator/README.md This comprehensive Dart example demonstrates how to define API routes using annotations (`@Route.get`, `@Route.post`, `@Route.mount`) with `shelf_routing_generator`. It includes a `User` model, a `UserController` with various HTTP methods, an `ApiRouter` to mount controllers, and a `main` function to set up and serve the application, showcasing the full workflow from model definition to server startup. ```dart import 'package:shelf/shelf.dart'; import 'package:shelf_router/shelf_router.dart'; import 'package:shelf_routing/shelf_routing.dart'; // generated with 'dart run build_runner build' part 'example.g.dart'; class User { final int id; final String name; const User({required this.id, required this.name}); factory User.fromJson(Map map) => User(id: map['id'], name: map['name']); Map toJson() => {'id': id, 'name': name}; } class UserController implements RouterMixin { // Create router using the generate function defined in 'example.g.dart'. @override Router get router => _$UserControllerRouter(this); final DatabaseConnection connection; UserController(this.connection); @Route.get('/') Future> listUsers(Request request, {String? query}) async { return ['user1']; } @Route.get('/') Future fetchUser(Request request, int userId) async { if (userId == 1) { return Response.ok('user1'); } return Response.notFound('no such user'); } @Route.post('/') Future> createUser(Request request, User user) async { if (user.name.isEmpty) { return JsonResponse.badRequest(body: 'Missing name field'); } return JsonResponse.ok(user); } } class ApiRouter { static const _prefix = '/api'; final DatabaseConnection connection; ApiRouter(this.connection); Router get router => _$ApiRouterRouter(this); @Route.mount('$_prefix/users') UserController get users => UserController(connection); } class DatabaseConnection { static Future connect(String _) => throw UnimplementedError(); } void main() async { // You can setup context, database connections, cache connections, email // services, before you create an instance of your service. final connection = await DatabaseConnection.connect('localhost:1234'); // Service request using the router, note the router can also be mounted. final handler = const Pipeline().addHandler(ApiRouter(connection).router); await serve(handler, 'localhost', 8080); } ``` -------------------------------- ### Install shelf_open_api and build_runner Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_open_api/README.md Add 'shelf_open_api', 'build_runner', and 'shelf_open_api_generator' to your project's 'pubspec.yaml' file under 'dependencies' and 'dev_dependencies' respectively. ```yaml dependencies: shelf_open_api: dev_dependencies: build_runner: shelf_open_api_generator: ``` -------------------------------- ### Adding Descriptions and Examples to DTOs for OpenAPI Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_open_api_generator/README.md Explains how to use Dart doc comments to provide summaries, descriptions, and examples for fields within data transfer objects (DTOs). These comments are then automatically reflected in the generated OpenAPI specification, enhancing API clarity. ```dart class MessageCreateDto { /// The id of the chat where the message will be sent final String chatId; /// The content of the message. /// /// You can enter texts and emojis. Images are not supported. /// /// `Hi, Luigi!` final String content; const MessageCreateDto({ required this.chatId, required this.content, }); } ``` -------------------------------- ### Configure shelf_open_api_generator options Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_open_api/README.md Example 'build.yaml' configuration for 'shelf_open_api_generator', demonstrating how to set global OpenAPI information (title, description), server URLs, and security schemes (e.g., HTTP Bearer JWT) for the generated specification. ```yaml targets: $default: builders: shelf_open_api_generator: options: info: # See more info on open_api_specification.InfoOpenApi class title: 'Api' description: 'Shelf open api example' servers: # See more info on open_api_specification.ServerOpenApi class url: 'http://localhost:8080' security_schemes: # See more info on open_api_specification.SecuritySchemeOpenApi class appwriteJwt: type: http scheme: Bearer bearerFormat: JWT ``` -------------------------------- ### Install shelf_open_api and build_runner Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_open_api_generator/README.md Instructions to add `shelf_open_api`, `build_runner`, and `shelf_open_api_generator` to your Dart project's `pubspec.yaml` file for dependency management and code generation. ```yaml dependencies: shelf_open_api: dev_dependencies: build_runner: shelf_open_api_generator: ``` -------------------------------- ### Generate API Client via Dart Script Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/open_api_client_generator/README.md This example illustrates how to integrate the OpenAPI client generator directly into a Dart application. It shows how to import the necessary package and call the `generateApi` function with `Options` to configure the input OpenAPI spec URI and output folder, along with specifying `DioClientCodec` and `JsonSerializableSerializationCodec`. ```dart import 'package:open_api_client_generator/open_api_client_generator.dart'; void main() async { await generateApi( options: Options( input: Uri.parse('http://0.0.0.0:8080/api/v1/swagger/open_api.yaml'), outputFolder: 'lib/api', ), clientCodec: const DioClientCodec(), serializationCodec: const JsonSerializableSerializationCodec(), ); } ``` -------------------------------- ### Node.js Backend Endpoint for Stripe Terminal Connection Token Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md This Node.js code snippet provides an example backend implementation for generating a Stripe Terminal connection token. It uses the Stripe Node.js library to create a `connectionToken` and exposes it via an Express.js GET endpoint, which the mobile client calls during SDK initialization. ```javascript import Stripe from "stripe"; import express from "express"; const stripe = new Stripe("sk_test_XXXXXXXXXXXXXXXXXX", { apiVersion: "2020-08-27" }) const app = express(); app.get("/connectionToken", async (req, res) => { const token = await stripe.terminal.connectionTokens.create(); res.send({ success: true, data: token.secret }); }); app.listen(8000, () => { console.log("Server started") }); ``` -------------------------------- ### Document DTO fields with summaries and descriptions Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_open_api/README.md Illustrates how to add Javadoc-style comments to Data Transfer Object (DTO) fields. These comments are used by the generator to produce summaries, detailed descriptions, and examples for queries or requests within the OpenAPI specification. ```dart class MessageCreateDto { /// The id of the chat where the message will be sent final String chatId; /// The content of the message. /// /// You can enter texts and emojis. Images are not supported. /// /// `Hi, Luigi!` final String content; const MessageCreateDto({ required this.chatId, required this.content, }); } ``` -------------------------------- ### Run Flutter App with Environment Variables Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/example/README.md This command runs a Flutter application, injecting environment variables from a specified .env file using the `--dart-define-from-file` flag. This is crucial for securely providing API keys or other sensitive configuration at runtime without hardcoding them. ```bash flutter run --dart-define-from-file=.env ``` -------------------------------- ### OpenAPI Client Generator Arguments Reference Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/open_api_client_generator/README.md This section provides a comprehensive reference for the various command-line arguments and their corresponding Dart classes used to configure the OpenAPI client generator. It details options for HTTP clients, serialization libraries, collection types, and additional plugins, including their associated packages and descriptions. ```APIDOC Arguments: Client: - CommandLine: --client=abstract Dart Class: AbstractClientCodec Package: N/A Description: Generate an abstract client - CommandLine: --client=dart Dart Class: DartClientCodec Package: N/A Description: Generate a client that does not use external libraries - CommandLine: --client=http Dart Class: HttpClientCodec Package: http Description: Generate a client that uses the http library - CommandLine: --client=dio Dart Class: DioClientCodec Package: dio Description: Generate a client that uses the dio library Serialization: - CommandLine: --serialization=json_serializable Dart Class: JsonSerializableSerializationCodec Package: json_serializable Description: Generate serialization use the json_serializable package - CommandLine: --serialization=built_value Dart Class: BuiltValueSerializationCodec Package: built_value Description: Generate serialization use the built_value package Collection: - CommandLine: --collection=dart Dart Class: DartCollectionCodec Package: N/A Description: Use List an Map from dart core - CommandLine: --collection=fast_immutable_collection Dart Class: FastImmutableCollectionCodec Package: fast_immutable_collection Description: Instead of List and Map use IList and IMap - CommandLine: --collection=built_collection Dart Class: BuiltCollectionCodec Package: built_collection Description: Instead of List and Map use BuiltList and BuiltMap Plugins: - CommandLine: --plugins=mek_data_class Dart Class: MekDataClassPlugin Package: mek_data_class Description: Generates data classes with Data Class annotation, implements toString and equals ``` -------------------------------- ### Configuring shelf_open_api_generator via build.yaml Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_open_api_generator/README.md Details how to configure the `shelf_open_api_generator` using a `build.yaml` file. This includes setting API `info` (title, description), `servers` (URL), and `security_schemes` (e.g., JWT Bearer) for the generated OpenAPI specification. ```yaml targets: $default: builders: shelf_open_api_generator: options: info: # See more info on open_api_specification.InfoOpenApi class title: 'Api' description: 'Shelf open api example' servers: # See more info on open_api_specification.ServerOpenApi class url: 'http://localhost:8080' security_schemes: # See more info on open_api_specification.SecuritySchemeOpenApi class appwriteJwt: type: http scheme: Bearer bearerFormat: JWT ``` -------------------------------- ### Generate API Client via Command Line Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/open_api_client_generator/README.md This snippet demonstrates how to run the OpenAPI client generator from the command line. It specifies the input OpenAPI YAML file, the output directory for the generated code, the desired HTTP client library (Dio), and the data serialization method (json_serializable). ```shell dart run open_api_client_generator \ --input=http://0.0.0.0:8080/api/v1/swagger/open_api.yaml \ --output-folder=lib/api \ --client=dio \ --data=json_serializable ``` -------------------------------- ### Annotating Shelf Controllers for OpenAPI Generation Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_open_api_generator/README.md Demonstrates how to annotate a Shelf controller class with `@OpenApiFile` to enable OpenAPI specification generation, specifying the output format (e.g., JSON). After annotation, run `dart run build_runner build` to generate the OpenAPI file. ```dart @OpenApiFile(format: OpenApiFile.json) class MessagesController { @Route.get('/messages') Future fetch(Request request) async { // Code... } } ``` -------------------------------- ### Connect FlutterApi Implementation to Native Channel Source: https://github.com/brex900/mek-packages/blob/main/one_for_all/README.md This Dart snippet demonstrates how to instantiate the `_FlutterTerminal` class and establish its connection to the generated channel using the `setupFlutterTerminal` function. This step is crucial for making the `onFetchToken` method available for invocation from native code. ```Dart final flutterTerminal = _FlutterTerminal(); setupFlutterTerminal(flutterTerminal); ``` -------------------------------- ### Annotate Shelf routes with OpenApiFile Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_open_api/README.md Demonstrates how to annotate a Shelf controller class with `@OpenApiFile` to enable OpenAPI specification generation for its routes, specifying the output format. ```dart @OpenApiFile(format: OpenApiFile.json) class MessagesController { @Route.get('/messages') Future fetch(Request request) async { // Code... } } ``` -------------------------------- ### shelf_open_api_generator Configuration API Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_open_api_generator/README.md API documentation for the configuration options available for `shelf_open_api_generator`, typically defined within the `build.yaml` file under the `options` key. These options control the metadata and structure of the generated OpenAPI specification. ```APIDOC shelf_open_api_generator.options: info: # Object defining API metadata title: string (required) - The title of the API. description: string (optional) - A general description of the API. servers: # Array of server objects - url: string (required) - A URL to the target host. security_schemes: # Map of security scheme definitions : # User-defined name for the security scheme type: string (required) - The type of the security scheme (e.g., 'http', 'apiKey', 'oauth2'). scheme: string (optional, required for type 'http') - The name of the HTTP Authorization scheme to be used (e.g., 'Bearer'). bearerFormat: string (optional) - A hint to the client to identify how the bearer token is formatted (e.g., 'JWT'). ``` -------------------------------- ### Defining Route Parameters and Bodies with OpenApiRoute Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_open_api_generator/README.md Illustrates how to explicitly define request query and body types for API routes using the `@OpenApiRoute` annotation. This allows for detailed OpenAPI specification generation, including summaries and descriptions for each route. ```dart @OpenApi() class MessagesController { @Route.get('/messages') @OpenApiRoute(requestQuery: MessageFetchDto) Future> fetch(Request request) async { // Code... } /// This is a summary /// /// This is a /// long description @Route.post('/messages') @OpenApiRoute(requestBody: MessageCreateDto) Future> create(Request request) async { // Code... } } ``` -------------------------------- ### iOS API Beta: collectInputs Method Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/ROADMAP.md Adds a beta `collectInputs` method to display forms and collect customer information. ```APIDOC collectInputs ``` -------------------------------- ### Generate OneForAll Code using Dart CLI Source: https://github.com/brex900/mek-packages/blob/main/one_for_all/README.md This Bash command demonstrates how to use the `one_for_all_generator` CLI tool to initiate native code generation. It specifies the Dart API file path, and the desired output locations for Kotlin (Android) and Swift (iOS/macOS) files, along with the Kotlin package name. ```Bash dart run one_for_all_generator \ --api-path=lib/terminal.dart \ --kotlin-output-file=android/src/main/Terminal.kt \ --kotlin-package=com.terminal --swift-output-file=ios/Classes/Terminal.swift ``` -------------------------------- ### Android API Beta: Terminal.collectInputs Method Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/ROADMAP.md Introduces the beta `Terminal.collectInputs` method for displaying forms and collecting customer information. It requires the `@OptIn` annotation `@CollectInputs`. ```APIDOC Terminal.collectInputs @OptIn(CollectInputs) ``` -------------------------------- ### Define route types with OpenApiRoute annotations Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_open_api/README.md Shows how to use `@OpenApiRoute` to explicitly define request query or body types for Shelf routes. It also demonstrates how to add summaries and multi-line descriptions for each route, which will be reflected in the generated OpenAPI documentation. ```dart @OpenApi() class MessagesController { @Route.get('/messages') @OpenApiRoute(requestQuery: MessageFetchDto) Future> fetch(Request request) async { // Code... } /// This is a summary /// /// This is a /// long description @Route.post('/messages') @OpenApiRoute(requestBody: MessageCreateDto) Future> create(Request request) async { // Code... } } ``` -------------------------------- ### Initialize Stripe Terminal SDK in Dart Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md This Dart code snippet initializes the `StripeTerminal` SDK. It requires a `fetchToken` callback function that asynchronously retrieves a connection token, typically from a backend service, which is vital for authenticating and connecting to the Stripe Terminal. ```dart StripeTerminal.initTerminal( fetchToken: () async { // Call your backend to get the connection token and return to this function // Example token can be. const token = "pst_test_XXXXXXXXXX...."; return token; }, ); ``` -------------------------------- ### Type Shelf routes using shelf_routing and RouterMixin Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_open_api/README.md Illustrates how to integrate 'shelf_routing' and 'RouterMixin' to define typed routes, allowing for automatic OpenAPI specification generation without explicit annotations on each route. It shows nested controllers and typed request/response bodies. ```dart class MessagesController with RouterMixin { Router get router => _$MessagesController(this); @Route.post('/') Future> get(Request request, int messageId) async { // Code... return JsonResponse.ok(MessageDto(messageId: messageId)); } @Route.post('/') Future> post(Request request, MessageCreateDto data) async { // Code... return JsonResponse.ok(MessageDto(messageId: data.messageId)); } } @OpenApi() class ApiController { static const _prefix = '/api-v1'; Router get router => _$ApiController(this); @Route.mount('$_prefix/messages') MessagesController get messages => MessagesController(); } ``` -------------------------------- ### Integrating shelf_routing for Typed API Endpoints Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_open_api_generator/README.md Shows how to use `shelf_routing` and `shelf_routing_generator` with `shelf_open_api` to define typed routes. This includes using `RouterMixin`, `Route.post`, and `Route.mount` for structured API endpoint definition, reducing the need for explicit OpenAPI annotations on routes. ```dart class MessagesController with RouterMixin { Router get router => _$MessagesController(this); @Route.post('/') Future> get(Request request, int messageId) async { // Code... return JsonResponse.ok(MessageDto(messageId: messageId)); } @Route.post('/') Future> post(Request request, MessageCreateDto data) async { // Code... return JsonResponse.ok(MessageDto(messageId: data.messageId)); } } @OpenApi() class ApiController { static const _prefix = '/api-v1'; Router get router => _$ApiController(this); @Route.mount('$_prefix/messages') MessagesController get messages => MessagesController(); } ``` -------------------------------- ### Project Dependencies for Shelf Routing Generator Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_routing_generator/README.md This YAML configuration specifies the necessary `dependencies` and `dev_dependencies` for a Dart project utilizing `shelf`, `shelf_router`, `shelf_routing`, `build_runner`, and `shelf_routing_generator` to enable annotation-based routing. ```yaml dependencies: shelf: shelf_router: shelf_routing: dev_dependencies: build_runner: shelf_routing_generator: ``` -------------------------------- ### iOS API Beta: Reader Settings Management Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/ROADMAP.md Introduces beta support for retrieving and updating reader settings on WisePOS E and Stripe S700 by calling `retrieveReaderSettings` and `setReaderSettings` on `SCPTerminal`. Accessibility settings (text-to-speech) are currently supported. ```APIDOC SCPTerminal.retrieveReaderSettings SCPTerminal.setReaderSettings ``` -------------------------------- ### iOS API Beta: Offline Payments Support Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/ROADMAP.md Announces private beta support for collecting payments while offline. ```APIDOC Offline Payments (private beta) ``` -------------------------------- ### Android API Beta: Reader Settings Management Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/ROADMAP.md Announces beta support for retrieving and updating reader settings on WisePOS E and Stripe S700 via `Terminal.getReaderSettings` and `Terminal.setReaderSettings`. Currently, accessibility settings (text-to-speech) are supported. This feature requires reader software version `2.20` or later. ```APIDOC Terminal.getReaderSettings Terminal.setReaderSettings ``` -------------------------------- ### Annotate Dart Class with HostApi for Code Generation Source: https://github.com/brex900/mek-packages/blob/main/one_for_all/README.md This Dart code snippet illustrates how to annotate a class with `@HostApi()` and define an abstract method that returns a `Future`. This annotated class serves as the blueprint for OneForAll to generate corresponding native code for platform communication. ```Dart @HostApi() class Terminal extends _$Terminal { Future> fetchReaders(); } ``` -------------------------------- ### YAML Dependency Configuration for Shelf Routing Generator Source: https://github.com/brex900/mek-packages/blob/main/shelf_packages/shelf_routing/README.md This YAML snippet outlines the necessary dependencies for a Dart project utilizing `shelf_routing_generator`. It specifies `shelf`, `shelf_router`, and `shelf_routing` as regular dependencies, and `build_runner` and `shelf_routing_generator` as development dependencies, essential for code generation. ```yaml dependencies: shelf: shelf_router: shelf_routing: dev_dependencies: build_runner: shelf_routing_generator: ``` -------------------------------- ### Android API Update: Reader Device Property Replacement Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/ROADMAP.md Notes the removal of `Reader.device` and its replacement with `Reader.bluetoothDevice` and `Reader.usbDevice` for more specific reader identification. ```APIDOC Reader.device (removed) Reader.bluetoothDevice Reader.usbDevice ``` -------------------------------- ### Connect to a Bluetooth Stripe Terminal Reader (Dart) Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md This snippet illustrates how to establish a connection to a previously discovered Bluetooth reader. It uses `Terminal.instance.connectReader`, passing the selected reader, a `BluetoothConnectionConfiguration` with a `locationId`, and an instance of the custom `MyMobileReaderDelegate` to handle reader events during the connection. ```Dart await Terminal.instance.connectReader(readers[0], BluetoothConnectionConfiguration( locationId: locationId, delegate: MyMobileReaderDelegate(), )); print("Connected to a device"); ``` -------------------------------- ### Discover Nearby Stripe Terminal Readers (Dart) Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md This snippet demonstrates how to initiate a discovery process for nearby Stripe Terminal readers using `Terminal.instance.discoverReaders`. It configures a Bluetooth discovery with simulation enabled and listens for a list of `StripeReader` objects, updating the UI state with the discovered readers. ```Dart Terminal.instance .discoverReaders(BluetoothDiscoveryConfiguration(isSimulated: true)) .listen((List readers) { setState(() => _readers = readers); }); ``` -------------------------------- ### Generate OneForAll Code Programmatically in Dart Source: https://github.com/brex900/mek-packages/blob/main/one_for_all/README.md This Dart script shows an alternative method to programmatically invoke the OneForAll code generation process. It utilizes `OneForAll.from` to configure various options, including the API file, and specific settings for Dart, Kotlin (output file and package), and Swift (output file) generation. ```Dart import 'package:one_for_all_generator/one_for_all_generator.dart'; void main() async { await OneForAll.from( options: const OneForAllOptions( apiFile: 'lib/terminal.dart', ), dartOptions: const DartOptions(), kotlinOptions: const KotlinOptions( outputFile: 'android/src/main/Terminal.kt', package: 'com.terminal', ), swiftOptions: const SwiftOptions( outputFile: 'ios/Classes/Terminal.swift', ), ).build(); } ``` -------------------------------- ### Implement Stripe Terminal Mobile Reader Delegate (Dart) Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md This code defines `MyMobileReaderDelegate`, a custom implementation of `MobileReaderDelegate`. It shows how to override methods like `onReportAvailableUpdate` to handle events from the connected reader, such as software updates. Other delegate methods would be implemented here as needed. ```Dart class MyMobileReaderDelegate extends MobileReaderDelegate { void onReportAvailableUpdate(ReaderSoftwareUpdate update) { print('A new update is available!'); } // and handle others methods... } ``` -------------------------------- ### Android API Update: Terminal Permission Checks Relocation Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/ROADMAP.md Explains the relocation of runtime permission checks from `Terminal.initTerminal()` to `Terminal.discoverReaders()`. Bluetooth permissions are now specific to `BluetoothDiscoveryConfiguration`, while location permissions remain universal for all `DiscoveryConfigurations` and require device location services. ```APIDOC Terminal.initTerminal() Terminal.discoverReaders() BluetoothDiscoveryConfiguration DiscoveryConfigurations ``` -------------------------------- ### Open Xcode Workspace for Flutter Project Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md This command opens the Xcode workspace for a Flutter project. This is a common step when needing to access iOS-specific project settings or assets, such as `Assets.xcassets`, for managing launch screen images or other visual assets. ```Shell open ios/Runner.xcworkspace ``` -------------------------------- ### Add OneForAll Dependencies to pubspec.yaml Source: https://github.com/brex900/mek-packages/blob/main/one_for_all/README.md This YAML snippet demonstrates how to add `one_for_all` as a regular dependency and `one_for_all_generator` as a development dependency to your Flutter project's `pubspec.yaml` file. These dependencies are essential for using the OneForAll code generation capabilities. ```YAML dependencies: one_for_all: dev_dependencies: one_for_all_generator: ``` -------------------------------- ### Collect Payment Method with Stripe Terminal (Dart) Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md This code demonstrates the process of collecting a payment method from the connected reader. `Terminal.instance.collectPaymentMethod` takes the retrieved `paymentIntent` and interacts with the reader to securely obtain the customer's payment details, returning a processable payment intent. ```Dart final processablePaymentIntent = await Terminal.instance.collectPaymentMethod(paymentIntent); ``` -------------------------------- ### Create Stripe Payment Intent on Backend (Dart) Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md This code represents a call to a backend service to create a new Stripe Payment Intent. The `backend.createPaymentIntent()` function is expected to return the necessary payment intent details, which are crucial for subsequent client-side operations. ```Dart // Get this from your backend by creating a new payment intent final backendPaymentIntent = await backend.createPaymentIntent(); ``` -------------------------------- ### Configure Native Method Generation Types with MethodApi Source: https://github.com/brex900/mek-packages/blob/main/one_for_all/README.md This Dart snippet illustrates how to use the `@MethodApi` annotation to control the generation type (sync, async, or callbacks) for native methods in Kotlin and Swift. This provides fine-grained control over how the generated native code handles method calls and their execution flow. ```Dart @HostApi() class Terminal extends _$Terminal { @MethodApi( kotlin: MethodApiType. swift: MethodApiType., ) Future> fetchReaders(); } ``` -------------------------------- ### iOS API Update: SCPPaymentIntent Stripe ID Nullability Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/ROADMAP.md Details the change in `SCPPaymentIntent.stripeId` to be nullable, supporting offline payments. ```APIDOC SCPPaymentIntent.stripeId (now nullable) ``` -------------------------------- ### Android API Update: Terminal.collectInputs Optional Toggles Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/ROADMAP.md Describes the enhancement to `Terminal.collectInputs` allowing the display of optional toggles within forms. ```APIDOC Terminal.collectInputs (now supports optional toggles) ``` -------------------------------- ### Configure Android Gradle for Stripe Terminal Dependency Exclusion Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md This Gradle configuration snippet addresses a known dependency conflict in the Stripe Terminal Android SDK. It excludes a duplicate 'bcprov-jdk15to18' module and prioritizes specific Bouncy Castle properties files to resolve potential build issues. ```groovy android { // TODO: remove this two directives once stripe_terminal fixes its plugin // these two snippets are excluding a dup dependency that is probably not transitive // https://github.com/stripe/stripe-terminal-android/issues/349 configurations { all*.exclude module: 'bcprov-jdk15to18' } packagingOptions { pickFirst 'org/bouncycastle/x509/CertPathReviewerMessages.properties' pickFirst 'org/bouncycastle/x509/CertPathReviewerMessages_de.properties' } } ``` -------------------------------- ### Request Runtime Permissions for Stripe Terminal in Dart Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md This Dart code snippet demonstrates how to request necessary runtime permissions using the `permission_handler` package. It requests `locationWhenInUse` and `bluetooth` permissions, adding `bluetoothScan` and `bluetoothConnect` specifically for Android, which are essential for the Stripe Terminal SDK's operation. ```dart import 'package:permission_handler/permission_handler.dart'; final permissions = [ Permission.locationWhenInUse, Permission.bluetooth, if (Platform.isAndroid) ...[ Permission.bluetoothScan, Permission.bluetoothConnect, ], ]; await permissions.request(); ``` -------------------------------- ### Define Flutter Methods Callable from Native Code Source: https://github.com/brex900/mek-packages/blob/main/one_for_all/README.md This Dart code defines a class annotated with `@FlutterApi()` to expose methods that can be invoked from native platforms. For proper recognition by the generator, methods within this class must begin with either `on` or `_on`. ```Dart @FlutterApi() class _FlutterTerminal { Future onFetchToken() async { return await httpClient.getToken(); } } ``` -------------------------------- ### Configure iOS Info.plist for Location and Bluetooth Permissions Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md This XML snippet adds required permission request strings to the iOS `Info.plist` file. It includes descriptions for `NSLocationWhenInUseUsageDescription`, `NSBluetoothPeripheralUsageDescription`, and `NSBluetoothAlwaysUsageDescription`, which are necessary for the Stripe Terminal SDK to access location and connect to Bluetooth card readers. ```xml NSLocationWhenInUseUsageDescription Location access is required in order to accept payments. NSBluetoothPeripheralUsageDescription Bluetooth access is required in order to connect to supported bluetooth card readers. NSBluetoothAlwaysUsageDescription This app uses Bluetooth to connect to supported card readers. ``` -------------------------------- ### Retrieve Stripe Payment Intent (Dart) Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md After creating a payment intent on the backend, this snippet shows how to retrieve it on the client side using `Terminal.instance.retrievePaymentIntent`. It requires the `clientSecret` obtained from the backend-created payment intent to fetch the full intent object. ```Dart final paymentIntent = await Terminal.instance.retrievePaymentIntent(backendPaymentIntent.clientSecret); ``` -------------------------------- ### Android API Update: PaymentIntent ID Nullability Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/ROADMAP.md Details the change in the `PaymentIntent::id` property to be nullable, supporting offline payment intent creation. This feature is currently in an invite-only beta. ```APIDOC PaymentIntent::id (now nullable) ``` -------------------------------- ### Confirm Stripe Payment Intent and Capture (Dart) Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md The final step in the client-side payment flow, this snippet uses `Terminal.instance.confirmPaymentIntent` to confirm the payment intent after the payment method has been collected. This action prepares the intent for final capture, which typically occurs on the backend, and prints a message indicating the next step. ```Dart final capturablePaymentIntent = await Terminal.instance.confirmPaymentIntent(processablePaymentIntent) print("A payment intent has captured a payment method, send this payment intent to you backend to capture the payment"); ``` -------------------------------- ### Configure iOS Entitlement for Tap to Pay on iPhone Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md This XML snippet adds the `com.apple.developer.proximity-reader.payment.acceptance` entitlement to an iOS application's entitlements file. This entitlement is required by Apple for applications to use the Tap to Pay on iPhone feature for accepting payments. ```xml com.apple.developer.proximity-reader.payment.acceptance ``` -------------------------------- ### Configure iOS Info.plist for Bluetooth Background Mode Source: https://github.com/brex900/mek-packages/blob/main/stripe_terminal/README.md This XML snippet adds the `bluetooth-central` background mode to the iOS `Info.plist` file. This authorization is crucial for the application to maintain Bluetooth connections with card readers even when the app is in the background. ```xml UIBackgroundModes bluetooth-central ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.