diff --git a/guides/additional-content/security/oauth/introduction.pt.md b/guides/additional-content/security/oauth/introduction.pt.md index 8e5ae15a21..15454fafca 100644 --- a/guides/additional-content/security/oauth/introduction.pt.md +++ b/guides/additional-content/security/oauth/introduction.pt.md @@ -1,6 +1,6 @@ # OAuth -O OAuth é um protocolo de autorização que permite que aplicações tenham acesso limitado às informações privadas das contas do Mercado Pago. Ele utiliza o protocolo HTTP e introduz uma camada de autenticação e autorização. Por meio desse protocolo, é possível solicitar acesso a recursos protegidos dos vendedores, utilizando um **Access Token** limitado a uma determinada aplicação, sem precisar das credenciais dos vendedores por meio de **fluxos de acesso**. +OAuth is an authorization protocol that allows applications to have limited access to private information from Mercado Pago accounts. It uses the HTTP protocol and introduces a layer of authentication and authorization. Through this protocol, it is possible to request access to protected resources of sellers using an **Access Token** that is limited to a specific application, without needing the sellers' credentials via **access flows**. > NOTE > diff --git a/guides/checkout-bricks/prerequisites.en.md b/guides/checkout-bricks/prerequisites.en.md index e9897357e3..82e5246238 100644 --- a/guides/checkout-bricks/prerequisites.en.md +++ b/guides/checkout-bricks/prerequisites.en.md @@ -12,7 +12,7 @@ To perform a Bricks integration, you must meet the requirements listed below. |---|---| | Application | Applications are the different integrations in one or more stores. You can create an application for each solution you implement to keep everything organized and on track for easier management. Check [Your integrations](/developers/en/docs/checkout-bricks/additional-content/your-integrations/introduction) for more information on how to create an application. | | Mercado Pago or Mercado Libre seller account | To integrate Bricks you need a seller account on Mercado Pago or Mercado Libre. If not, [click here](https://www.mercadopago[FAKER][URL][DOMAIN]/hub/registration/landing) to create. | -| Credentials | Unique passwords with which we identify an integration in your account. To perform the integrations, you will need the _Public key_ and the _Access Token_. [Click here](/developers/en/guides//checkout-bricks/additional-content/your-integrations/credentials) for more information. | +| Credentials | Unique passwords with which we identify an integration in your account. To perform the integrations, you will need the _Public key_ and the _Access Token_. [Click here](/developers/en/docs/checkout-bricks/additional-content/your-integrations/credentials) for more information. | | Install the Mercado Pago SDK | Install the official SDKs to simplify your integration with our [APIs](/developers/en/reference/payments/_payments/post). For more information, [click here](/developers/en/docs/sdks-library/landing). | If all the prerequisites are met, you can perform the Bricks integration. \ No newline at end of file diff --git a/guides/checkout-bricks/prerequisites.es.md b/guides/checkout-bricks/prerequisites.es.md index fe2a6897f0..a94e7383b5 100644 --- a/guides/checkout-bricks/prerequisites.es.md +++ b/guides/checkout-bricks/prerequisites.es.md @@ -12,7 +12,7 @@ Para realizar la integración de los Bricks, debes cumplir con los requisitos qu |---|---| | Aplicación | Las aplicaciones son las diversas integraciones contenidas en una o varias tiendas. Puedes crear una aplicación para cada solución que implementes a fin de tener todo organizado y mantener un control que facilite la gestión. Consulta tu [Tus integraciones](/developers/es/docs/checkout-bricks/additional-content/your-integrations/introduction) para obtener más información sobre cómo crear una aplicación. | | Cuenta de vendedor de Mercado Pago o Mercado Libre | Para integrar los Bricks necesitas una cuenta de vendedor en Mercado Pago o Mercado Libre. Sino, [haz clic aquí](https://www.mercadopago[FAKER][URL][DOMAIN]/hub/registration/landing) para crearla gratis. | -|Credenciales | Contraseñas únicas con las que identificamos una integración en tu cuenta. Para realizar las integraciones, necesitará la _Public key_ y el _Access Token_. [Haz clic aquí](/developers/es/guides/checkout-bricks/additional-content/your-integrations/credentials) para obtener más información. | +|Credenciales | Contraseñas únicas con las que identificamos una integración en tu cuenta. Para realizar las integraciones, necesitará la _Public key_ y el _Access Token_. [Haz clic aquí](/developers/es/docs/checkout-bricks/additional-content/your-integrations/credentials) para obtener más información. | | Instalar el SDK de Mercado Pago | Instala los SDK oficiales para simplificar tu integración con nuestras [APIs](/developers/es/reference/payments/_payments/post). Para obtener más información, [haz clic aquí](/developers/es/docs/sdks-library/landing). | Si se cumplen todos los requisitos previos, podrás realizar la integración de los Bricks. \ No newline at end of file diff --git a/guides/mp-point-main-apps/access-settings.en.md b/guides/mp-point-main-apps/access-settings.en.md new file mode 100644 index 0000000000..f772109a03 --- /dev/null +++ b/guides/mp-point-main-apps/access-settings.en.md @@ -0,0 +1,20 @@ +# Access settings + +Use the `launch` method of the `BluetoothUiSettings` class to start with the bluetooth settings on Mercado Pago. That component provides several features, like activating and deactivating, searching for devices, and pairing and unpairing, among others. Check how to access it. + +[[[ +```kotlin +val bluetoothUiSettings = MPManager.bluetoothUiSettings + +bluetoothUiSettings.launch(context) +``` +```java +final BluetoothUiSettings bluetoothUiSettings = MPManager.INSTANCE.getBluetoothUiSettings(); + +bluetoothUiSettings.launch(context); +``` +]]] + +|Field|Description| +|---|---| +|**context (Context)**| It must be the context of the app and it’s mandatory to begin the activity.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/access-settings.es.md b/guides/mp-point-main-apps/access-settings.es.md new file mode 100644 index 0000000000..aadf809dee --- /dev/null +++ b/guides/mp-point-main-apps/access-settings.es.md @@ -0,0 +1,20 @@ +# Acceder a la configuración + +Usa el método `launch` de la clase `BluetoothUiSettings` para iniciar la actividad de configuración de bluetooth de Mercado Pago. Este componente ofrece diversas funcionalidades, cómo activar y desactivar, buscar dispositivos, emparejar y desemparejar, entre otros. Consulta cómo acceder. + +[[[ +```kotlin +val bluetoothUiSettings = MPManager.bluetoothUiSettings + +bluetoothUiSettings.launch(context) +``` +```java +final BluetoothUiSettings bluetoothUiSettings = MPManager.INSTANCE.getBluetoothUiSettings(); + +bluetoothUiSettings.launch(context); +``` +]]] + +|Campo|Descripción| +|---|---| +|**context (Context)**| Debe ser el contexto de la app y es obligatorio para iniciar la actividad.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/access-settings.pt.md b/guides/mp-point-main-apps/access-settings.pt.md new file mode 100644 index 0000000000..e6b33becd0 --- /dev/null +++ b/guides/mp-point-main-apps/access-settings.pt.md @@ -0,0 +1,20 @@ +# Acessar configurações + +Use o método `launch` da classe `BluetoothUiSettings` para iniciar a atividade de configurações de bluetooth do Mercado Pago. Esse componente proporciona diversas funcionalidades, como ativar e desativar, buscar dispositivos, emparelhar e desemparelhar, entre outras. Confira como acessá-lo. + +[[[ +```kotlin +val bluetoothUiSettings = MPManager.bluetoothUiSettings + +bluetoothUiSettings.launch(context) +``` +```java +final BluetoothUiSettings bluetoothUiSettings = MPManager.INSTANCE.getBluetoothUiSettings(); + +bluetoothUiSettings.launch(context); +``` +]]] + +|Campo|Descrição| +|---|---| +|**context (Context)**| Deve ser o contexto do aplicativo e é obrigatório para iniciar a atividade.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/distribution.en.md b/guides/mp-point-main-apps/distribution.en.md index 8409467b9f..4d164c240d 100644 --- a/guides/mp-point-main-apps/distribution.en.md +++ b/guides/mp-point-main-apps/distribution.en.md @@ -7,9 +7,9 @@ For the distribution phase of your solution, follow these steps: 3. To upload your solution to the Mercado Pago ecosystem, guaranteeing the security of the application and its subsequent versions, digitally sign the certificate. This document must be the same for both the initial package and each update. Android provides a [step-by-step guide on how to digitally sign your app](https://developer.android.com/studio/publish/app-signing#generate-key) with the certificate generated by the developer. 4. Share the **.apk** package with the Mercado Pago support team. They will carry out a series of validations and notify the integrator company of the result. -> **The Mercado Pago support team is responsible for facilitating the following operations:** ->

-> - Delivery of new versions.
-> - Pre-configuration of devices.
-> - UX and security validations.
-> - Distribution of native APKs.
\ No newline at end of file +The Mercado Pago support team is responsible for facilitating the following operations: + +- **Delivery of new versions.** +- **Pre-configuration of devices.** +- **UX and security validations.** +- **Distribution of native APKs.** \ No newline at end of file diff --git a/guides/mp-point-main-apps/distribution.es.md b/guides/mp-point-main-apps/distribution.es.md index d77b537dfd..0b44a8dd23 100644 --- a/guides/mp-point-main-apps/distribution.es.md +++ b/guides/mp-point-main-apps/distribution.es.md @@ -7,9 +7,9 @@ Para la fase de distribución de tu solución, sigue estas etapas: 3. Para subir tu solución al ecosistema de Mercado Pago, garantizando la seguridad de la app y de tus posteriores versiones, suscribe al certificado de manera digital. Este documento debe ser el mismo tanto para el paquete inicial, como para cada una de las actualizaciones. Android disponibiliza [un paso a paso de cómo suscribir digitalmente la app](https://developer.android.com/studio/publish/app-signing?hl=es-419#generate-key), con el certificado generado por la persona desarrolladora. 4. Comparte el paquete **.apk**` com el equipo de soporte de Mercado Pago, que hará una serie de validaciones y avisará a la empresa integradora del resultado. -> **El equipo de soporte de Mercado Pago es responsable de facilitar las siguientes operaciones:** ->

-> - Entrega de nuevas versiones.
-> - Pre-configuración de los dispositivos.
-> - Validaciones de UX y Seguridad.
-> - Distribución de los APKs nativos. \ No newline at end of file +El equipo de soporte de Mercado Pago es responsable de facilitar las siguientes operaciones: + +- **Entrega de nuevas versiones.** +- **Pre-configuración de los dispositivos.** +- **Validaciones de UX y Seguridad.** +- **Distribución de los APKs nativos.** \ No newline at end of file diff --git a/guides/mp-point-main-apps/distribution.pt.md b/guides/mp-point-main-apps/distribution.pt.md index 92b325199e..1e782b621f 100644 --- a/guides/mp-point-main-apps/distribution.pt.md +++ b/guides/mp-point-main-apps/distribution.pt.md @@ -7,9 +7,9 @@ Para a fase de distribuição da sua solução, siga estas etapas: 3. Para subir sua solução ao ecossistema do Mercado Pago, garantindo a segurança do aplicativo e de suas posteriores versões, faça a assinatura digital do certificado. Este documento deve ser o mesmo tanto para o pacote inicial, como para cada uma das atualizações. O Android disponibiliza [um passo a passo de como assinar o app digitalmente](https://developer.android.com/studio/publish/app-signing?hl=pt-br#generate-key), com o certificado gerado pela pessoa desenvolvedora. 4. Compartilhe o pacote **.apk** com a equipe de suporte do Mercado Pago. Ela fará uma série de validações e notificará a empresa integradora sobre o resultado. -> **A equipe de suporte do Mercado Pago é responsável por facilitar as seguintes operações:** ->

-> - Entrega de novas versões.
-> - Pré-configuração dos dispositivos.
-> - Validações de UX e segurança.
-> - Distribuição dos APKs nativos.
\ No newline at end of file +A equipe de suporte do Mercado Pago é responsável por facilitar as seguintes operações: + +- **Entrega de novas versões.** +- **Pré-configuração dos dispositivos.** +- **Validações de UX e segurança.** +- **Distribuição dos APKs nativos.** \ No newline at end of file diff --git a/guides/mp-point-main-apps/first-steps.en.md b/guides/mp-point-main-apps/first-steps.en.md index 82184934da..69085edb3c 100644 --- a/guides/mp-point-main-apps/first-steps.en.md +++ b/guides/mp-point-main-apps/first-steps.en.md @@ -15,7 +15,56 @@ dependencies { } ``` -3. In the **AndroidManifest.xml** file, define the main activity that will be set as the application launcher. Add the following `intent-filter`: +3. The correct configuration of metadata in the **AndroidManifest.xml** file is crucial to ensure optimal functioning and full integration of our SDK into your application. The metadata allows you to define essential and customized settings that the SDK needs to operate properly, adapting to the specific needs of each application and its usage environment. To do this, configure the following information: + + - **CLIENT_ID**: to identify the transactions of the integrators, indicate the [credential](/developers/en/docs/main-apps/additional-content/your-integrations/credentials) **Client ID** that was assigned to the application created in the [Developer dashboard](/developers/en/docs/checkout-bricks/additional-content/your-integrations/dashboard). + + ```xml + + + + + + + ``` + + > WARNING + > + > Important + > + > It is crucial that the metadata name is exactly `com.test.android.sdk.CLIENT_ID`. Any variation in the name may result in the SDK not recognizing the field. + >

+ > Additionally, make sure that the **Client ID** value ends with the letter "L" to indicate that it is a Long type number. This is necessary for the SDK to process the value correctly. + + - **OAUTH_ENABLED**: use the `OAUTH_ENABLED` field to enable the [OAuth](/developers/en/docs/main-apps/additional-content/security/oauth/introduction) authorization protocol, which is necessary when devices will be used with accounts different from that of the application developer. This field is optional, and if it is not added to the metadata, it will be considered the default value `false`. + + ```xml + + + + + + + + ``` + + > WARNING + > + > Important + > + > It is crucial that the metadata name is exactly `com.mercadolibre.android.sdk.OAUTH_ENABLED`. Any variation in the name may result in the SDK not recognizing the field. + >

+ > Make sure to correctly set the value of the field to only `true` or `false`, according to the need to enable or not the [OAuth](/developers/en/docs/main-apps/additional-content/security/oauth/introduction) protocol. If not specified, the default value will be `false`. + +4. Still in the **AndroidManifest.xml** file, define the main activity that will be set as the application launcher. Add the following `intent-filter`: ```xml diff --git a/guides/mp-point-main-apps/first-steps.es.md b/guides/mp-point-main-apps/first-steps.es.md index 144c0b3ed2..a4441aad94 100644 --- a/guides/mp-point-main-apps/first-steps.es.md +++ b/guides/mp-point-main-apps/first-steps.es.md @@ -15,7 +15,56 @@ dependencies { } ``` -3. En el archivo **AndroidManifest.xml**, define la actividad principal que se establecerá como _launcher_ de la app. Agrega los siguientes `intent-filter`: +3. La configuración correcta de metadata en el archivo **AndroidManifest.xml** es crucial para garantizar el funcionamiento óptimo y la integración completa de nuestro SDK en tu aplicación. La metadata permite definir configuraciones esenciales y personalizadas que el SDK necesita para operar adecuadamente, adaptándose a las necesidades específicas de cada aplicación y su entorno de uso. Para ello, configure las siguientes información: + + - **CLIENT_ID**: para identificar las transacciones de los integradores, indica la [credencial](/developers/es/docs/main-apps/additional-content/your-integrations/credentials) **Client ID** que fue asignada a la aplicación creada en el [Panel del desarrollador](/developers/es/docs/checkout-bricks/additional-content/your-integrations/dashboard). + + ```xml + + + + + + + ``` + + > WARNING + > + > Importante + > + > Es crucial que el nombre de la metadata sea exactamente `com.test.android.sdk.CLIENT_ID`. Cualquier variación en el nombre puede resultar en la falta de reconocimiento del campo por parte del SDK. + >

+ > Además, asegúrate de que el valor del **Client ID** termine con la letra "L" para indicar que es un número del tipo _Long_. Esto es necesario para que el SDK procese correctamente el valor. + + - **OAUTH_ENABLED**: utiliza el campo `OAUTH_ENABLED` para activar el protocolo de autorización [OAuth](/developers/es/docs/main-apps/additional-content/security/oauth/introduction), que es necesario cuando los dispositivos se utilizarán con cuentas diferentes a la del desarrollador de la aplicación. Este campo es opcional y, si no se agrega en la metadata, se considerará el valor predeterminado `false`. + + ```xml + + + + + + + + ``` + + > WARNING + > + > Importante + > + > Es crucial que el nombre de la metadata sea exactamente `com.mercadolibre.android.sdk.OAUTH_ENABLED`. Cualquier variación en el nombre puede resultar en la falta de reconocimiento del campo por parte del SDK. + >

+ > Asegúrate de definir correctamente el valor del campo solo con `true` o `false`, de acuerdo con la necesidad de habilitar o no el protocolo [OAuth](/developers/es/docs/main-apps/additional-content/security/oauth/introduction). Si no se especifica, el valor predeterminado será `false`. + +4. Aún en el archivo **AndroidManifest.xml**, define la actividad principal que se establecerá como _launcher_ de la app. Agrega los siguientes `intent-filter`: ```xml diff --git a/guides/mp-point-main-apps/first-steps.pt.md b/guides/mp-point-main-apps/first-steps.pt.md index d7ced9e730..2b19c9228f 100644 --- a/guides/mp-point-main-apps/first-steps.pt.md +++ b/guides/mp-point-main-apps/first-steps.pt.md @@ -15,7 +15,55 @@ dependencies { } ``` -3. No arquivo **AndroidManifest.xml**, defina a atividade principal que será estabelecida como _launcher_ da aplicação. Adicione os seguintes `intent-filter`: +3. A configuração correta de metadata no arquivo **AndroidManifest.xml** é crucial para garantir o funcionamento ideal e a integração completa do nosso SDK em sua aplicação. A metadata permite definir configurações essenciais e personalizadas que o SDK precisa para operar adequadamente, adaptando-se às necessidades específicas de cada aplicação e seu ambiente de uso. Para isso, configure as seguintes informações: + + - **CLIENT_ID**: para identificar as transações dos integradores, indique a [credencial](/developers/pt/docs/main-apps/additional-content/your-integrations/credentials) **Client ID** que foi atribuída à aplicação criada no [Painel do desenvolvedor](/developers/pt/docs/checkout-bricks/additional-content/your-integrations/dashboard). + + ```xml + + + + + + + ``` + + > WARNING + > + > Importante + > + > É crucial que o nome da metadata seja exatamente `com.test.android.sdk.CLIENT_ID`. Qualquer variação no nome pode resultar na falta de reconhecimento do campo pelo SDK. + >

+ > Além disso, certifique-se de que o valor do **Client ID** termine com a letra "L" para indicar que é um número do tipo _Long_. Isso é necessário para que o SDK processe corretamente o valor. + + - **OAUTH_ENABLED**: utilize o campo `OAUTH_ENABLED` para ativar o protocolo de autorização [OAuth](/developers/pt/docs/main-apps/additional-content/security/oauth/introduction), que é necessário quando os dispositivos serão usados com contas diferentes da do desenvolvedor da aplicação. Este campo é opcional e, caso não seja adicionado na metadata, será considerado o valor padrão `false`. + + ```xml + + + + + + + ``` + + > WARNING + > + > Importante + > + > É crucial que o nome da metadata seja exatamente `com.mercadolibre.android.sdk.OAUTH_ENABLED`. Qualquer variação no nome pode resultar na falta de reconhecimento do campo pelo SDK. + >

+ > Certifique-se de definir corretamente o valor do campo apenas com `true` ou `false`, de acordo com a necessidade de habilitar ou não o protocolo [OAuth](/developers/pt/docs/main-apps/additional-content/security/oauth/introduction). Se não for especificado, o valor padrão será `false`. + +4. Ainda no arquivo **AndroidManifest.xml**, defina a atividade principal que será estabelecida como _launcher_ da aplicação. Adicione os seguintes `intent-filter`: ```xml diff --git a/guides/mp-point-main-apps/get-information.en.md b/guides/mp-point-main-apps/get-information.en.md new file mode 100644 index 0000000000..7a0c7246f0 --- /dev/null +++ b/guides/mp-point-main-apps/get-information.en.md @@ -0,0 +1,52 @@ +# Get information + +Through the `getInformation` feature of the `SmartInformationTools` class, you recover detailed information about a device and the integration SDK. Access this feature through the `MPManager` object, as in the following example: + +[[[ +```kotlin +val informationTools = MPManager.smartInformationTools + +informationTools.getInformation { response -> +   response.doIfSuccess { smartInformation -> +       // Manage information on the device and integration +       val deviceSerialNumber = smartInformation.smartDevice.serialNumber +       val brandName = smartInformation.smartDevice.brandName +       val modelName = smartInformation.smartDevice.modelName +       val paymentModuleVersion = smartInformation.smartDevice.paymentModuleVersion + +       val sdkVersion = smartInformation.integration.nativeSdkVersion +   }.doIfError { error -> +       // Manage error in information request +} +``` +```java +final SmartInformationTools smartInformationTools = MPManager.INSTANCE.getSmartInformationTools(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Manage information on the device and integration +   final String deviceSerialNumber = response.getData().getSmartDevice().getSerialNumber(); +   final String brandName = response.getData().getSmartDevice().getBrandName(); +   final String modelName = response.getData().getSmartDevice().getModelName(); +   final String paymentModuleVersion = response.getData().getSmartDevice().getPaymentModuleVersion(); + +   final String sdkVersion = response.getData().getIntegration().getNativeSdkVersion(); + } else { +   // Manage error in information request + } + return Unit.INSTANCE; +}; + +smartInformationTools.getInformation(callback); +``` +]]] + +|Field|Description| +|---|---| +|**smartDevice**| Device details.| +|**integration**| Integration SDK details.| +|**serialNumber**| POS machine serial number.| +|**brandName**| POS machine brand.| +|**modelName**| POS machine model.| +|**paymentModuleVersion**| Version of the payment module of the [SmartPOS](/developers/en/docs/mp-point/landing).| +|**nativeSdkVersion**| Integration SDK version.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/get-information.es.md b/guides/mp-point-main-apps/get-information.es.md new file mode 100644 index 0000000000..220da4ba8f --- /dev/null +++ b/guides/mp-point-main-apps/get-information.es.md @@ -0,0 +1,67 @@ +# Obtener información + +A través de la función `getInformation` de la clase `SmartInformationTools`, recuperas información detallada sobre un dispositivo y el SDK de las integraciones. Accede a esta función por el a través del objeto `MPManager`, como en el ejemplo a continuación: + +[[[ +```kotlin +val informationTools = MPManager.smartInformationTools + +informationTools.getInformation { response -> +   response.doIfSuccess { smartInformation -> +       // Manejar la información del dispositivo e integración +       val deviceSerialNumber = smartInformation.smartDevice.serialNumber +       val brandName = smartInformation.smartDevice.brandName +       val modelName = smartInformation.smartDevice.modelName +       val paymentModuleVersion = smartInformation.smartDevice.paymentModuleVersion + +       val sdkVersion = smartInformation.integration.nativeSdkVersion +   }.doIfError { error -> +       // Manejar el error en la solicitud de información +} +``` +```java +final SmartInformationTools smartInformationTools = MPManager.INSTANCE.getSmartInformationTools(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Manejar la información del dispositivo e integración +   final String deviceSerialNumber = response.getData().getSmartDevice().getSerialNumber(); +   final String brandName = response.getData().getSmartDevice().getBrandName(); +   final String modelName = response.getData().getSmartDevice().getModelName(); +   final String paymentModuleVersion = response.getData().getSmartDevice().getPaymentModuleVersion(); + +   final String sdkVersion = response.getData().getIntegration().getNativeSdkVersion(); + } else { +   // Manejar el error en la solicitud de información + } + return Unit.INSTANCE; +}; + +smartInformationTools.getInformation(callback); +``` +]]] + +----[mla, mlb]---- +|Campo|Descripción| +|---|---| +|**smartDevice**| Detalles del dispositivo.| +|**integration**| Detalles del SDK de las integraciones.| +|**serialNumber**| Número de serie del lector.| +|**brandName**| Nombre de la marca del lector.| +|**modelName**| Nombre del modelo del lector.| +|**paymentModuleVersion**| Versión del módulo de pago del [SmartPOS](/developers/en/docs/mp-point/landing).| +|**nativeSdkVersion**| Versión del SDK de las integraciones.| + +------------ +----[mlm]---- +|Campo|Descripción| +|---|---| +|**smartDevice**| Detalles del dispositivo.| +|**integration**| Detalles del SDK de las integraciones.| +|**serialNumber**| Número de serie de la terminal.| +|**brandName**| Nombre de la marca de la terminal.| +|**modelName**| Nombre del modelo de la terminal.| +|**paymentModuleVersion**| Versión del módulo de pago del [SmartPOS](/developers/en/docs/mp-point/landing).| +|**nativeSdkVersion**| Versión del SDK de las integraciones.| + +------------ \ No newline at end of file diff --git a/guides/mp-point-main-apps/get-information.pt.md b/guides/mp-point-main-apps/get-information.pt.md new file mode 100644 index 0000000000..2b6f6518da --- /dev/null +++ b/guides/mp-point-main-apps/get-information.pt.md @@ -0,0 +1,52 @@ +# Obter informações + +Através da função `getInformation` da classe `SmartInformationTools`, você recupera informações detalhadas sobre um dispositivo e o SDK de integrações. Acesse essa função pelo objeto `MPManager`, como no exemplo a seguir: + +[[[ +```kotlin +val informationTools = MPManager.smartInformationTools + +informationTools.getInformation { response -> +   response.doIfSuccess { smartInformation -> +       // Gerencie informações no dispositivo e integração +       val deviceSerialNumber = smartInformation.smartDevice.serialNumber +       val brandName = smartInformation.smartDevice.brandName +       val modelName = smartInformation.smartDevice.modelName +       val paymentModuleVersion = smartInformation.smartDevice.paymentModuleVersion + +       val sdkVersion = smartInformation.integration.nativeSdkVersion +   }.doIfError { error -> +       // Gerencie erro na solicitação de informações +} +``` +```java +final SmartInformationTools smartInformationTools = MPManager.INSTANCE.getSmartInformationTools(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Gerencie informações no dispositivo e integração +   final String deviceSerialNumber = response.getData().getSmartDevice().getSerialNumber(); +   final String brandName = response.getData().getSmartDevice().getBrandName(); +   final String modelName = response.getData().getSmartDevice().getModelName(); +   final String paymentModuleVersion = response.getData().getSmartDevice().getPaymentModuleVersion(); + +   final String sdkVersion = response.getData().getIntegration().getNativeSdkVersion(); + } else { +   // Gerencie erro na solicitação de informações + } + return Unit.INSTANCE; +}; + +smartInformationTools.getInformation(callback); +``` +]]] + +|Campo|Descrição| +|---|---| +|**smartDevice**| Detalhes do dispositivo.| +|**integration**| Detalhes do SDK de integrações.| +|**serialNumber**| Número de série da maquininha.| +|**brandName**| Nome da marca da maquininha.| +|**modelName**| Nome do modelo da maquininha.| +|**paymentModuleVersion**| Versão do módulo de pagamento do [SmartPOS](/developers/pt/docs/mp-point/landing).| +|**nativeSdkVersion**| Versão do SDK de integrações.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/get-list-installments.en.md b/guides/mp-point-main-apps/get-list-installments.en.md new file mode 100644 index 0000000000..146a195c1b --- /dev/null +++ b/guides/mp-point-main-apps/get-list-installments.en.md @@ -0,0 +1,56 @@ +# Get list of installments + +To get the list of installments linked to a specific amount, use the feature `getInstallmentsAmount`. Its accessible in the `PaymentInstallmentTools` instance, through the `MPManager` object. + +The function `getInstallmentsAmount` simplifies the process of obtaining detailed information about the installments associated with a specific amount. + +> WARNING +> +> Attention +> +> Currently this option will only be available for solutions implemented within Brazil. + +To use this feature, you have to: + +1. Select the **CREDIT-CARD** payment method. +2. Use an amount greater than R$10,00. + +Like this: + +[[[ +```kotlin +MPManager.paymentInstallmentTools.getInstallmentsAmount( +   callback = { mpResponse -> +       mpResponse.doIfSuccess { installments -> +           // Successfully manage the list of installments +       }.doIfError { +           // Manage the error in the installment request +       } +   }, +   amount = "11.0" +) +``` +```java +final PaymentInstallmentTools paymentInstallmentTools = MPManager.INSTANCE.getPaymentInstallmentTools(); + +final Function1>, Unit> callback = (final MPResponse> response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Successfully manage the list of installments + } else { +   // Manage the error in the installment request + } + return Unit.INSTANCE; +}; +final String amount = "11.0"; + +paymentInstallmentTools.getInstallmentsAmount(callback, amount); +``` +]]] + +|Field|Description| +|---|---| +|**callback ((MPResponse<List<InstallmentAmount>>) -> Unit)**|Response feature with the result of the request of the list of installments. Make sure to properly handle both the success case and the error case when requesting the list.| +|**amount (String)**|Amount with which the list of installments is determined.| +|**installment (Int)**|Number of installments.| +|**amount (Double)**|Amount of each installment.| +|**financialAmount (Double)**|Interest rate for each installment.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/get-list-installments.es.md b/guides/mp-point-main-apps/get-list-installments.es.md new file mode 100644 index 0000000000..3fa3716d9e --- /dev/null +++ b/guides/mp-point-main-apps/get-list-installments.es.md @@ -0,0 +1,111 @@ + +----[mla, mlb]---- +# Obtener lista de cuotas + +Para obtener la lista de cuotas asociadas a un monto específico, usa la función `getInstallmentsAmount`. Puedes acceder a ella a través de la `PaymentInstallmentTools`, a través del objeto `MPManager`. + +La función `getInstallmentsAmount` simplifica el proceso de obtención de información detallada sobre las cuotas asociadas a un monto específico. + +------------ +----[mlm]---- +# Obtener lista de mensualidades + +Para obtener la lista de cuotas asociadas a un monto específico, usa la función `getInstallmentsAmount`. Puedes acceder a ella a través de la `PaymentInstallmentTools`, a través del objeto `MPManager`. + +La función `getInstallmentsAmount` simplifica el proceso de obtención de información detallada sobre las mensualidades asociadas a un monto específico. + +------------ + +> WARNING +> +> Attention +> +> Por el momento, esta opción solo está disponible para soluciones implementadas en Brasil. + +Para usar la función, debes: + +1. Seleccionar el medio de pago **CREDIT-CARD**. +2. Usar un monto mayor que $ 10,00. + +De esta manera: + +----[mla, mlb]---- +[[[ +```kotlin +MPManager.paymentInstallmentTools.getInstallmentsAmount( +   callback = { mpResponse -> +       mpResponse.doIfSuccess { installments -> +           // Manejar la lista de cuotas exitosamente +       }.doIfError { +           // Manejar el error en la solicitud de cuotas +       } +   }, +   amount = "11.0" +) +``` +```java +final PaymentInstallmentTools paymentInstallmentTools = MPManager.INSTANCE.getPaymentInstallmentTools(); + +final Function1>, Unit> callback = (final MPResponse> response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Manejar la lista de cuotas exitosamente + } else { +   // Manejar el error en la solicitud de cuotas + } + return Unit.INSTANCE; +}; +final String amount = "11.0"; + +paymentInstallmentTools.getInstallmentsAmount(callback, amount); +``` +]]] + +|Campo|Descripción| +|---|---| +|**callback ((MPResponse<List<InstallmentAmount>>) -> Unit)**|Función de respuesta con el resultado de la solicitud de la lista de cuotas. Asegúrate de manejar adecuadamente tanto el caso de éxito como el caso de error en la solicitud de la lista. | +|**amount (String)**|Monto con el cual se determina la lista de cuotas.| +|**installment (Int)**|Número de cuotas.| +|**amount (Double)**|Monto de cada cuota.| +|**financialAmount (Double)**|Porcentaje de interés de cada cuota.| + +------------ +----[mlm]---- +[[[ +```kotlin +MPManager.paymentInstallmentTools.getInstallmentsAmount( +   callback = { mpResponse -> +       mpResponse.doIfSuccess { installments -> +           // Manejar la lista de mensualidades exitosamente +       }.doIfError { +           // Manejar el error en la solicitud de mensualidades +       } +   }, +   amount = "11.0" +) +``` +```java +final PaymentInstallmentTools paymentInstallmentTools = MPManager.INSTANCE.getPaymentInstallmentTools(); + +final Function1>, Unit> callback = (final MPResponse> response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Manejar la lista de mensualidades exitosamente + } else { +   // Manejar el error en la solicitud de mensualidades + } + return Unit.INSTANCE; +}; +final String amount = "11.0"; + +paymentInstallmentTools.getInstallmentsAmount(callback, amount); +``` +]]] + +|Campo|Descripción| +|---|---| +|**callback ((MPResponse<List<InstallmentAmount>>) -> Unit)**|Función de respuesta con el resultado de la solicitud de la lista de mensualidades. Asegúrate de manejar adecuadamente tanto el caso de éxito como el caso de error en la solicitud de la lista.| +|**amount (String)**|Monto con el cual se determina la lista de mensualidades.| +|**installment (Int)**|Número de mensualidades.| +|**amount (Double)**|Monto de cada mensualidade.| +|**financialAmount (Double)**|Porcentaje de interés de cada mensualidade.| + +------------ \ No newline at end of file diff --git a/guides/mp-point-main-apps/get-list-installments.pt.md b/guides/mp-point-main-apps/get-list-installments.pt.md new file mode 100644 index 0000000000..f256ce36a5 --- /dev/null +++ b/guides/mp-point-main-apps/get-list-installments.pt.md @@ -0,0 +1,56 @@ +# Obter lista de parcelas + +Para obter a lista de parcelas associadas a um valor específico, utilize a função `getInstallmentsAmount`. Ela está acessível pela instância `PaymentInstallmentTools`, por meio do objeto `MPManager`. + +A função `getInstallmentsAmount` simplifica o processo de obtenção de informações detalhadas sobre as parcelas associadas a um valor específico. + +> WARNING +> +> Atenção +> +> Atualmente, essa opção só está disponível para soluções implementadas no Brasil. + +Para usar a função, você deve: + +1. Selecionar o método de pagamento **CREDIT-CARD**. +2. Usar um valor maior que R$ 10,00. + +Dessa forma: + +[[[ +```kotlin +MPManager.paymentInstallmentTools.getInstallmentsAmount( +   callback = { mpResponse -> +       mpResponse.doIfSuccess { installments -> +           // Gerencie com sucesso a lista de parcelas +       }.doIfError { +           // Gerencie o erro na solicitação de parcelas +       } +   }, +   amount = "11.0" +) +``` +```java +final PaymentInstallmentTools paymentInstallmentTools = MPManager.INSTANCE.getPaymentInstallmentTools(); + +final Function1>, Unit> callback = (final MPResponse> response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Gerencie com sucesso a lista de parcelas + } else { +   // Gerencie o erro na solicitação de parcelas + } + return Unit.INSTANCE; +}; +final String amount = "11.0"; + +paymentInstallmentTools.getInstallmentsAmount(callback, amount); +``` +]]] + +|Campo|Descrição| +|---|---| +|**callback ((MPResponse<List<InstallmentAmount>>) -> Unit)**|Função de resposta com o resultado da solicitação da lista de parcelas. Lembre-se de lidar corretamente tanto com o caso de sucesso quanto com o caso de erro na solicitação da lista.| +|**amount (String)**|Valor com o qual se determina a lista de parcelas.| +|**installment (Int)**|Número de parcelas.| +|**amount (Double)**|Valor de cada parcela.| +|**inancialAmount (Double)**|Porcentagem de acréscimo de cada parcela.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/get-payment-methods.en.md b/guides/mp-point-main-apps/get-payment-methods.en.md new file mode 100644 index 0000000000..644d92ad61 --- /dev/null +++ b/guides/mp-point-main-apps/get-payment-methods.en.md @@ -0,0 +1,27 @@ +# Get payment methods + +Through `MPManager`, use the instance `PaymentsMethodsTools` with the feature `getPaymentMethods`. The payment methods will be shown by an **ENUM** called `PaymentMethod`, like in the example below. + +[[[ +```kotlin +MPManager.paymentMethodsTools.getPaymentMethods { response -> +   response +       .doIfSuccess { result -> +           // You can render the list of payment methods in a recycler view +       }.doIfError { exception -> +           // Error management +       } +} +``` +```java +final Function1>, Unit> callback = (final MPResponse> response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // You can render the list of payment methods in a recycler view + } else { +   // Error management + } + return Unit.INSTANCE; +}; +MPManager.INSTANCE.getPaymentMethodsTools().getPaymentMethods(callback); +``` +]]] \ No newline at end of file diff --git a/guides/mp-point-main-apps/get-payment-methods.es.md b/guides/mp-point-main-apps/get-payment-methods.es.md new file mode 100644 index 0000000000..f444439928 --- /dev/null +++ b/guides/mp-point-main-apps/get-payment-methods.es.md @@ -0,0 +1,27 @@ +# Obtener medios de pago + +A través del `MPManager`, usa la instancia `PaymentsMethodsTools` con la función `getPaymentMethods`. Los medios de pagos se mostrarán por un **ENUM** llamado `PaymentMethod`, como en el ejemplo a continuación. + +[[[ +```kotlin +MPManager.paymentMethodsTools.getPaymentMethods { response -> +   response +       .doIfSuccess { result -> +           // Puedes renderizar la lista de payment methods en un recycler view +       }.doIfError { exception -> +           // Manejo del error +       } +} +``` +```java +final Function1>, Unit> callback = (final MPResponse> response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Puedes renderizar la lista de payment methods en un recycler view + } else { +   // Manejo del error + } + return Unit.INSTANCE; +}; +MPManager.INSTANCE.getPaymentMethodsTools().getPaymentMethods(callback); +``` +]]] \ No newline at end of file diff --git a/guides/mp-point-main-apps/get-payment-methods.pt.md b/guides/mp-point-main-apps/get-payment-methods.pt.md new file mode 100644 index 0000000000..97f237738e --- /dev/null +++ b/guides/mp-point-main-apps/get-payment-methods.pt.md @@ -0,0 +1,27 @@ +# Obter meios de pagamento + +Por meio do `MPManager`, use a instância `PaymentsMethodsTools` com a função `getPaymentMethods`. Os meios de pagamentos serão mostrados por um **ENUM** chamado `PaymentMethod`, como no exemplo a seguir. + +[[[ +```kotlin +MPManager.paymentMethodsTools.getPaymentMethods { response -> +   response +       .doIfSuccess { result -> +           // Você pode renderizar a lista de métodos de pagamento em um recycler view +       }.doIfError { exception -> +           // Gerenciamento do erro +       } +} +``` +```java +final Function1>, Unit> callback = (final MPResponse> response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Você pode renderizar a lista de métodos de pagamento em um recycler view + } else { +   // Gerenciamento do erro + } + return Unit.INSTANCE; +}; +MPManager.INSTANCE.getPaymentMethodsTools().getPaymentMethods(callback); +``` +]]] \ No newline at end of file diff --git a/guides/mp-point-main-apps/introduction.en.md b/guides/mp-point-main-apps/introduction.en.md index ec36ee2b03..2b16f4c6cc 100644 --- a/guides/mp-point-main-apps/introduction.en.md +++ b/guides/mp-point-main-apps/introduction.en.md @@ -8,25 +8,4 @@ Main apps are business management applications that can be integrated with [Point Smart](/developers/en/docs/mp-point/landing). They become the main interface, and the seller uses the functionalities of the POS machine with Mercado Pago processing the payments. -The application is private, with a [closed distribution model](/developers/en/docs/main-apps/distribution) for exclusive use by the company. - -## Features - -Once integrated, the application can use the machine's functionalities to complete the experience. These are: - -### Available - -- Login in the main app from the Point Smart. -- Debit, credit and NFC payments with card or cell phone. -- Pix or QR code payments. -- Access to the camera to read the QR code. -- Customized printing of receipts and bitmap image files. -- Bluetooth connection to printers, keyboards and barcode readers. - -### Coming soon - -- Access to the camera for reading barcodes. -- Payment refunds by the POS. -- Control panel with application information. -- Testing environment. -- Remote application updates controlled by device. \ No newline at end of file +The application is private, with a [closed distribution model](/developers/en/docs/main-apps/distribution) for exclusive use by the company. \ No newline at end of file diff --git a/guides/mp-point-main-apps/introduction.es.md b/guides/mp-point-main-apps/introduction.es.md index dd75c66b68..9345bc17af 100644 --- a/guides/mp-point-main-apps/introduction.es.md +++ b/guides/mp-point-main-apps/introduction.es.md @@ -8,25 +8,4 @@ El [Point Smart](/developers/es/docs/mp-point/landing) es un dispositivo de pago Las main apps son aplicativos de gestión de negocio que se pueden integrar a [Point Smart](/developers/es/docs/mp-point/landing). Se convierten en la interfaz principal, y la persona vendedora usa las funcionalidades del lector con Mercado Pago procesando los pagos. -La app es privada, con [modelo cerrado de distribución](/developers/es/docs/main-apps/distribution) de uso exclusivo de la empresa. - -## Funcionalidades - -Cuando se integra, la app puede usar las funcionalidades del lector que completan la experiencia. Ellas son: - -### Disponibles - -- Inicio de sesión en la main app desde Point Smart. -- Pagos en débito, crédito y NFC (pago sin contacto) con tarjeta o celular. -- Pagos por Pix o código QR. -- Acceso a la cámara para lectura del código QR. -- Impresión customizada de comprobantes y archivos de imagen bitmap. -- Conexión por bluetooth a impresoras, teclados y lectores de código de barras. - -### En breve - -- Acceso a la cámara para lectura de códigos de barra. -- Reembolso y devolución de pago a través del lector. -- Panel de control con información de la app. -- Ambiente de pruebas. -- Actualizaciones remotas de la app controlada por dispositivo. \ No newline at end of file +La app es privada, con [modelo cerrado de distribución](/developers/es/docs/main-apps/distribution) de uso exclusivo de la empresa. \ No newline at end of file diff --git a/guides/mp-point-main-apps/introduction.pt.md b/guides/mp-point-main-apps/introduction.pt.md index 43e3bd4cdc..2640b1b1e3 100644 --- a/guides/mp-point-main-apps/introduction.pt.md +++ b/guides/mp-point-main-apps/introduction.pt.md @@ -8,25 +8,4 @@ A [Point Smart](/developers/pt/docs/mp-point/landing) é um dispositivo de pagam Main apps são aplicativos de gestão de negócio que podem ser integrados à [Point Smart](/developers/pt/docs/mp-point/landing). Eles se transformam na interface principal, e a pessoa vendedora utiliza as funcionalidades da maquininha com o Mercado Pago processando os pagamentos. -O aplicativo é privado, com [modelo fechado de distribuição](/developers/pt/docs/main-apps/distribution) de uso exclusivo da empresa. - -## Funcionalidades - -Uma vez integrado, o aplicativo pode usar as funções da maquininha que completam a experiência. São elas: - -### Disponíveis - -- Login no main app a partir da Point Smart. -- Pagamentos em débito, crédito e NFC (pagamento por aproximação) com cartão ou celular. -- Pagamentos por Pix ou código QR. -- Acesso à câmera para leitura do código QR. -- Impressão customizada de comprovantes e arquivos de imagem bitmap. -- Conexão via bluetooth a impressoras, teclados e leitores de código de barras. - -### Em breve - -- Acesso à câmera para leitura de códigos de barra. -- Reembolso e devolução de pagamento pela maquininha. -- Painel de controle com informações do aplicativo. -- Ambiente de testes. -- Atualizações remotas do aplicativo controlada por dispositivo. \ No newline at end of file +O aplicativo é privado, com [modelo fechado de distribuição](/developers/pt/docs/main-apps/distribution) de uso exclusivo da empresa. \ No newline at end of file diff --git a/guides/mp-point-main-apps/landing.en.md b/guides/mp-point-main-apps/landing.en.md index 9857ad46c5..36025d2d0e 100644 --- a/guides/mp-point-main-apps/landing.en.md +++ b/guides/mp-point-main-apps/landing.en.md @@ -1,7 +1,7 @@ --- content_section_with_media: - - title: Main Apps Playbook - - message: This is a guide for you to develop and integrate main apps with Point Smart. Browse the side menu to find the processes, requirements and guidelines, from the POS technical data sheet to the solution distribution. The material is constantly evolving, with new content being included. + - title: Main Apps + - message: This is a guide for you to develop and integrate main apps, business management applications that can be integrated with Mercado Pago's Point Smart. Browse the side menu to find the processes, requirements and guidelines, from the POS technical data sheet to the solution distribution. - media_image: /main-apps/landing-all.png --- @@ -9,10 +9,49 @@ content_section_with_media: >>>> Availability by countrys<<<< --- -available_countries: mlb +available_countries: mlb, mla, mlm --- +----[mlb]---- + +--- +bullet_section_with_media: + - title: Features + - type: normal + - message: Once integrated, the application can use the machine's functionalities to complete the experience. These are: + - image: /main-apps/landing2-all.png + - benefit_title: Access + - benefit_message: Login in the main app from the Point Smart. + - benefit_title: Payments + - benefit_message: Payments via Pix, debit or credit card, QR code, and NFC (contactless payment) with card or cellphone. + - benefit_title: Camera + - benefit_message: Access to the camera to read the QR code and barcodes. + - benefit_title: Printing + - benefit_message: Connection via Bluetooth to printers, keyboards, and barcode scanners. Additionally, it allows for customized printing of receipts and bitmap image files. +--- + +------------ +----[mla, mlm]---- + +--- +bullet_section_with_media: + - title: Features + - type: normal + - message: Once integrated, the application can use the machine's functionalities to complete the experience. These are: + - image: /main-apps/landing2-all.png + - benefit_title: Access + - benefit_message: Login in the main app from the Point Smart. + - benefit_title: Payments + - benefit_message: Payments with debit or credit card, QR code, and NFC (contactless payment) with card or cellphone. + - benefit_title: Camera + - benefit_message: Access to the camera to read the QR code and barcodes. + - benefit_title: Printing + - benefit_message: Connection via Bluetooth to printers, keyboards, and barcode scanners. Additionally, it allows for customized printing of receipts and bitmap image files. +--- + +------------ + --- mini_landing_separator --- >>>> Accepted payment types <<<< diff --git a/guides/mp-point-main-apps/landing.es.md b/guides/mp-point-main-apps/landing.es.md index 8c2c2e83c0..0d1cd34a8b 100644 --- a/guides/mp-point-main-apps/landing.es.md +++ b/guides/mp-point-main-apps/landing.es.md @@ -1,7 +1,7 @@ --- content_section_with_media: - - title: Main Apps Playbook - - message: Esta es una guía para que desarrolles e integres main apps al Point Smart. Navega por el menú lateral para encontrar los procesos, requisitos y direccionamientos, desde la ficha técnica del lector a la distribución de la solución. El material está en constante evolución, con nuevos contenidos que se van incluyendo. + - title: Main Apps + - message: Esta es una guía para que desarrolles e integres main apps, aplicaciones de gestión de negocio que se pueden integrar a Point Smart de Mercado Pago. Navega por el menú lateral para encontrar los procesos, requisitos y direccionamientos, desde la ficha técnica del lector a la distribución de la solución. - media_image: /main-apps/landing-all.png --- @@ -9,10 +9,49 @@ content_section_with_media: >>>> Disponibilidad por país <<<< --- -available_countries: mlb +available_countries: mlb, mla, mlm --- +----[mlb]---- + +--- +bullet_section_with_media: + - title: Funcionalidades + - type: normal + - message: Cuando se integra, la app puede usar las funcionalidades del lector que completan la experiencia. Ellas son: + - image: /main-apps/landing2-all.png + - benefit_title: Acceso + - benefit_message: Inicio de sesión en la main app desde Point Smart. + - benefit_title: Pagos + - benefit_message: Pagos mediante Pix, tarjeta de débito o crédito, código QR y NFC (pagos sin contacto) con tarjeta o celular. + - benefit_title: Cámara + - benefit_message: Acceso a la cámara para lectura del código QR y de códigos de barra. + - benefit_title: Impresión + - benefit_message: Conexión vía bluetooth a impresoras, teclados y lectores de códigos de barras. Además, posibilita la impresión customizada de comprobantes y archivos de imagen bitmap. +--- + +------------ +----[mla, mlm]---- + +--- +bullet_section_with_media: + - title: Funcionalidades + - type: normal + - message: Cuando se integra, la app puede usar las funcionalidades del lector que completan la experiencia. Ellas son: + - image: /main-apps/landing2-all.png + - benefit_title: Acceso + - benefit_message: Inicio de sesión en la main app desde Point Smart. + - benefit_title: Pagos + - benefit_message: Pagos con tarjeta de débito o crédito, código QR y NFC (pagos sin contacto) con tarjeta o celular. + - benefit_title: Cámara + - benefit_message: Acceso a la cámara para lectura del código QR y de códigos de barra. + - benefit_title: Impresión + - benefit_message: Conexión vía bluetooth a impresoras, teclados y lectores de códigos de barras. Además, posibilita la impresión customizada de comprobantes y archivos de imagen bitmap. +--- + +------------ + --- mini_landing_separator --- >>>> Tipos de pago aceptados <<<< @@ -23,7 +62,6 @@ available_countries: mlb available_payments: credit, debit, mercadopago, pix --- - ------------ ----[mla]---- diff --git a/guides/mp-point-main-apps/landing.pt.md b/guides/mp-point-main-apps/landing.pt.md index acddf3e564..9d229c782d 100644 --- a/guides/mp-point-main-apps/landing.pt.md +++ b/guides/mp-point-main-apps/landing.pt.md @@ -1,17 +1,56 @@ --- content_section_with_media: - - title: Main Apps Playbook - - message: Este é um guia para você desenvolver e integrar main apps à Point Smart. Navegue pelo menu lateral para encontrar os processos, requisitos e direcionamentos, da ficha técnica da maquininha à distribuição da solução. O material está em constante evolução, com novos conteúdos sendo incluídos. + - title: Main Apps + - message: Este é um guia para você desenvolver e integrar main apps, aplicativos de gestão de negócio que podem ser integrados à Point Smart do Mercado Pago. Navegue pelo menu lateral para encontrar os processos, requisitos e direcionamentos, da ficha técnica da maquininha à distribuição da solução. - media_image: /main-apps/landing-all.png --- +----[mlb]---- + --- mini_landing_separator --- >>>> Disponibilidade por país <<<< --- -available_countries: mlb +available_countries: mlb, mla, mlm + +--- --- +bullet_section_with_media: + - title: Funcionalidades + - type: normal + - message: Uma vez integrado, o aplicativo pode usar as funções da maquininha que completam a experiência. São elas: + - image: /main-apps/landing2-all.png + - benefit_title: Acesso + - benefit_message: Login no main app a partir da Point Smart. + - benefit_title: Pagamentos + - benefit_message: Pagamentos via Pix, cartão de débito ou crédito, código QR e NFC (pagamento por aproximação) com cartão ou celular. + - benefit_title: Câmera + - benefit_message: Acesso à câmera para leitura do código QR e de códigos de barra. + - benefit_title: Impressão + - benefit_message: Conexão via bluetooth a impressoras, teclados e leitores de código de barras. Além disso, possibilida a impressão customizada de comprovantes e arquivos de imagem bitmap. +--- + +------------ +----[mla, mlm]---- + +--- +bullet_section_with_media: + - title: Funcionalidades + - type: normal + - message: Uma vez integrado, o aplicativo pode usar as funções da maquininha que completam a experiência. São elas: + - image: /main-apps/landing2-all.png + - benefit_title: Acesso + - benefit_message: Login no main app a partir da Point Smart. + - benefit_title: Pagamentos + - benefit_message: Pagamentos com cartão de débito ou crédito, código QR e NFC (pagamento por aproximação) com cartão ou celular. + - benefit_title: Câmera + - benefit_message: Acesso à câmera para leitura do código QR e de códigos de barra. + - benefit_title: Impressão + - benefit_message: Conexão via bluetooth a impressoras, teclados e leitores de código de barras. Além disso, possibilida a impressão customizada de comprovantes e arquivos de imagem bitmap. +--- + +------------ --- mini_landing_separator --- @@ -23,9 +62,7 @@ available_countries: mlb available_payments: credit, debit, mercadopago, pix --- - ------------ - ----[mla]---- --- @@ -33,7 +70,6 @@ available_payments: credit, debit, mercadopago --- ------------ - ----[mlm]---- --- diff --git a/guides/mp-point-main-apps/manage-connections.en.md b/guides/mp-point-main-apps/manage-connections.en.md new file mode 100644 index 0000000000..b1b7b6b9be --- /dev/null +++ b/guides/mp-point-main-apps/manage-connections.en.md @@ -0,0 +1,162 @@ +# Manage connections + +On our SDK, you can search for printers and other bluetooth devices, in addition to checking the ones paired with the POS machine. Learn how to continue. + +## Manage paired devices + +To get the list of paired devices with [Point Smart](/developers/en/docs/mp-point/landing) use the `getPairedDevices feature`, from the `BluetoothDiscoverDevices` class. Check below how to access it through the `MPManager`. + +[[[ +```kotlin +val bluetoothDiscoverDevices = MPManager.bluetooth.discover + +bluetoothDiscoverDevices.getPairedDevices { result -> +   result +       .doIfSuccess { devices -> +           // Work with the list of paired devices +       } +       .doIfError { error -> +           // Manage the error case if necessary +       } +} +``` +```java +final BluetoothDiscoverDevices bluetoothDiscoverDevices = MPManager.INSTANCE.getBluetooth().getDiscover(); + +final Function1>, Unit> callback = (final MPResponse> response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   final List devices = response.getData(); +   // Work with the list of paired devices + } else { +   // Manage the error case if necessary + } + return Unit.INSTANCE; +}; + +bluetoothDiscoverDevices.getPairedDevices(callback); +``` +]]] + +|Field|Description| +|---|---| +|**callback ((MPResponse<List<BluetoothDeviceModel>>) -> Unit)**| Request response feature that provides the paired devices as a result. The `[MPResponse]` includes the status, the error (if any), and the details in case of success, in a list of `BluetoothDeviceModel` models.| +|**id (String)**| Unique identifier of the bluetooth device.| +|**boundState (Int)**| Pairing status of the device. It can have different values representing different status.| +|**name (String)**| Name of the device provided by the operational system.| +|**address (String)**| MAC address of the bluetooth device.| +|**isConnected (Boolean)**| Indicates if the device is connected. In a positive case, the answer is `true`; if disconnected, it appears as `false`.| + +## Get paired printers + +Use the `getPairedPrinterDevices` feature from the `BluetoothDiscoverDevices` class to check the list of bluetooth printers with the [Point Smart](/developers/en/docs/mp-point/landing). The access is done through the `MPManager object`, as in the example below. + +[[[ +```kotlin +val bluetoothDiscoverDevices = MPManager.bluetooth.discover + +bluetoothDiscoverDevices.getPairedPrinterDevices { result -> +   result +       .doIfSuccess { printers -> +           // Work with the list of paired devices +       } +       .doIfError { error -> +           // Manage the error case if necessary +       } +} +``` +```java +final BluetoothDiscoverDevices bluetoothDiscoverDevices = MPManager.INSTANCE.getBluetooth().getDiscover(); + +final Function1>, Unit> callback = (final MPResponse> response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   final List printers = response.getData(); +   // Work with the list of paired devices + } else { +   // Manage the error case if necessary + } + return Unit.INSTANCE; +}; + +bluetoothDiscoverDevices.getPairedPrinterDevices(callback); +``` +]]] + +|Field|Description| +|---|---| +|**callback ((MPResponse<List<BluetoothDeviceModel>>) -> Unit)**| Request response feature that provides the paired printers as a result. The `[MPResponse]` includes the status, the error (if any) and the details in case of success in a list of `BluetoothDeviceModel` models.| +|**id (String)**| Unique identifier of the bluetooth device.| +|**boundState (Int)**| Pairing status of the device. It can have different values representing different status.| +|**name (String)**| Name of the device provided by the operational system.| +|**address (String)**| MAC address of the bluetooth device.| +|**isConnected (Boolean)**| Indicates if the device is connected. In a positive case, the answer is `true`; if disconnected, it appears as `false`.| + +## Start search + +The `startDiscovery` feature from the `BluetoothDiscoverDevices` class starts the discovery of bluetooth devices. The access is through the `MPManager` object. This method makes the dynamic implementation of the logic based on events in your solution easier. Like this: + +[[[ +```kotlin +val bluetoothDiscover = MPManager.bluetooth.discover + +bluetoothDiscover.startDiscovery { response -> +   response +       .doIfSuccess { discoveryState -> +           when (discoveryState.type) { +               BluetoothDiscoveryState.Type.STARTED -> { +                   // Manage the start of the discovery +               } +               BluetoothDiscoveryState.Type.DEVICE_FOUND -> discoveryState.device?.let { device -> +                   // Manage the discovery of a new device +               } +               BluetoothDiscoveryState.Type.DEVICE_CHANGE -> discoveryState.device?.let { device -> +                   // Manage changes in a discovered device +               } +               BluetoothDiscoveryState.Type.ENDED -> { +                   // Manage the end of the discovery +               } +           } +       } +       .doIfError { error -> +           // Manage the error case if necessary +       } +} +``` +```java +final BluetoothDiscoverDevices bluetoothDiscoverDevices = MPManager.INSTANCE.getBluetooth().getDiscover(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   switch (response.getData().getType()) { +     case STARTED: +       // Manage the start of the discovery +       break; +     case DEVICE_FOUND: +       // Manage the discovery of a new device +       final BluetoothDeviceModel foundDevice = response.getData().getDevice(); +       break; +     case DEVICE_CHANGE: +       // Manage changes in a discovered device +       final BluetoothDeviceModel changedDevice = response.getData().getDevice(); +       break; +     case ENDED: +       // Manage the end of the discovery + +   } + } else { +   // Manage the error case if necessary + } + return Unit.INSTANCE; +}; + +bluetoothDiscoverDevices.startDiscovery(callback); +``` +]]] + +|Field|Description| +|---|---| +|**callback ((MPResponse<BluetoothDiscoveryState>) -> Unit)**| Request response feature that provides the result of the discovery process. The `[MPResponse]` includes the status, the error (if any), and the details in case of success, containing a `BluetoothDiscoveryState` object that represents the current status of the discovery, events such as the start and end of the discovery and changes in the device.| +|**id (String)**| Unique identifier of the bluetooth device.| +|**boundState (Int)**| Pairing status of the device. It can have different values representing different status.| +|**name (String)**| Name of the device provided by the operational system.| +|**address (String)**| MAC address of the bluetooth device.| +|**isConnected (Boolean)**| Indicates if the device is connected. In a positive case, the answer is `true`; if disconnected, it appears as `false`.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/manage-connections.es.md b/guides/mp-point-main-apps/manage-connections.es.md new file mode 100644 index 0000000000..185db561ae --- /dev/null +++ b/guides/mp-point-main-apps/manage-connections.es.md @@ -0,0 +1,162 @@ +# Gestionar conexiones + +En nuestro SDK, puedes buscar impresoras y otros dispositivos bluetooth, además de gestionar los que ya están emparejados al lector. Aprende cómo hacerlo. + +## Obtener dispositivos emparejados + +La obtención de la lista de dispositivos emparejados con el [Point Smart](/developers/es/docs/mp-point/landing) se hace usando la función `getPairedDevices`, de la clase `BluetoothDiscoverDevices`. Consulta a continuación cómo acceder a ella a través del objeto `MPManager`. + +[[[ +```kotlin +val bluetoothDiscoverDevices = MPManager.bluetooth.discover + +bluetoothDiscoverDevices.getPairedDevices { result -> +   result +       .doIfSuccess { devices -> +           // Trabajar con la lista de dispositivos emparejados +       } +       .doIfError { error -> +           // Manejar el caso de error si es necesario +       } +} +``` +```java +final BluetoothDiscoverDevices bluetoothDiscoverDevices = MPManager.INSTANCE.getBluetooth().getDiscover(); + +final Function1>, Unit> callback = (final MPResponse> response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   final List devices = response.getData(); +   // Trabajar con la lista de dispositivos emparejados + } else { +   // Manejar el caso de error si es necesario + } + return Unit.INSTANCE; +}; + +bluetoothDiscoverDevices.getPairedDevices(callback); +``` +]]] + +|Campo|Descripción| +|---|---| +|**callback ((MPResponse<List<BluetoothDeviceModel>>) -> Unit)**| Función de devolución del llamado que ofrece los dispositivos emparejados como resultado. El `[MPResponse]` encapsula el estado, el error (si lo hay) y los datos en caso de éxito, en una lista de modelos `BluetoothDeviceModel`.| +|**id (String)**| Identificador único del dispositivo bluetooth.| +|**boundState (Int)**| Estado de emparejamiento del dispositivo. Puede tener diferentes valores representando estados distintos.| +|**name (String)**| Nombre del dispositivo ofrecido por el sistema operacional.| +|**address (String)**| Dirección MAC del dispositivo bluetooth.| +|**isConnected (Boolean)**| Indica si el dispositivo está conectado. En caso de ser positivo, la respuesta es `true`. Si está desconectado, aparece como `false`.| + +## Obtener impresoras emparejadas + +Usa la función `getPairedPrinterDevices` de la clase `BluetoothDiscoverDevices` para consultar la lista de impresoras bluetooth emparejadas al [Point Smart](/developers/es/docs/mp-point/landing). El acceso se hace a través del objeto `MPManager`, como en el ejemplo a continuación. + +[[[ +```kotlin +val bluetoothDiscoverDevices = MPManager.bluetooth.discover + +bluetoothDiscoverDevices.getPairedPrinterDevices { result -> +   result +       .doIfSuccess { printers -> +           // Trabajar con la lista de dispositivos emparejados +       } +       .doIfError { error -> +           // Manejar el caso de error si es necesario +       } +} +``` +```java +final BluetoothDiscoverDevices bluetoothDiscoverDevices = MPManager.INSTANCE.getBluetooth().getDiscover(); + +final Function1>, Unit> callback = (final MPResponse> response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   final List printers = response.getData(); +   // Trabajar con la lista de dispositivos emparejados + } else { +   // Manejar el caso de error si es necesario + } + return Unit.INSTANCE; +}; + +bluetoothDiscoverDevices.getPairedPrinterDevices(callback); +``` +]]] + +|Campo|Descripción| +|---|---| +|**callback ((MPResponse<List<BluetoothDeviceModel>>) -> Unit)**| Función de devolución del llamado que ofrece las impresonas emparejadas como resultado. El `[MPResponse]` encapsula el estado, el error (si lo hay) y los datos en caso de éxito en una lista de modelos `BluetoothDeviceModel`.| +|**id (String)**| Identificador único del dispositivo bluetooth.| +|**boundState (Int)**| Estado de emparejamiento del dispositivo. Puede tener diferentes valores representando estados distintos.| +|**name (String)**| Nombre del dispositivo ofrecido por el sistema operacional.| +|**address (String)**| Dirección MAC del dispositivo bluetooth.| +|**isConnected (Boolean)**| Indica si el dispositivo está conectado. En caso de ser positivo, la respuesta es `true`. Si está desconectado, aparece como `false`.| + +## Iniciar búsqueda + +La función `startDiscovery` de la clase `BluetoothDiscoverDevices` inicia la búsqueda de dispositivos bluetooth. El acceso se hace a través del objeto `MPManager`. Este método facilita la implementación dinámica de la lógica basada en eventos en tu solución. Así: + +[[[ +```kotlin +val bluetoothDiscover = MPManager.bluetooth.discover + +bluetoothDiscover.startDiscovery { response -> +   response +       .doIfSuccess { discoveryState -> +           when (discoveryState.type) { +               BluetoothDiscoveryState.Type.STARTED -> { +                   // Manejar el inicio del descubrimiento +               } +               BluetoothDiscoveryState.Type.DEVICE_FOUND -> discoveryState.device?.let { device -> +                   // Manejar el descubrimiento de un nuevo dispositivo +               } +               BluetoothDiscoveryState.Type.DEVICE_CHANGE -> discoveryState.device?.let { device -> +                   // Manejar cambios en un dispositivo descubierto +               } +               BluetoothDiscoveryState.Type.ENDED -> { +                   // Manejar el fin del descubrimiento +               } +           } +       } +       .doIfError { error -> +           // Manejar el caso de error si es necesario +       } +} +``` +```java +final BluetoothDiscoverDevices bluetoothDiscoverDevices = MPManager.INSTANCE.getBluetooth().getDiscover(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   switch (response.getData().getType()) { +     case STARTED: +       // Manejar el inicio del descubrimiento +       break; +     case DEVICE_FOUND: +       // Manejar el descubrimiento de un nuevo dispositivo +       final BluetoothDeviceModel foundDevice = response.getData().getDevice(); +       break; +     case DEVICE_CHANGE: +       // Manejar cambios en un dispositivo descubierto +       final BluetoothDeviceModel changedDevice = response.getData().getDevice(); +       break; +     case ENDED: +       // Manejar el fin del descubrimiento + +   } + } else { +   // Manejar el caso de error si es necesario + } + return Unit.INSTANCE; +}; + +bluetoothDiscoverDevices.startDiscovery(callback); +``` +]]] + +|Campo|Descripción| +|---|---| +|**callback ((MPResponse<BluetoothDiscoveryState>) -> Unit)**| Función de devolución del llamado que ofrece el resultado del proceso de búsqueda. El `[MPResponse]` encapsula el estado, el error (si lo hay) y los datos en caso de éxito, teniendo un objeto `BluetoothDiscoveryState` que representa el estado actual de la búsqueda, eventos como el inicio y el fin de la búsqueda y los cambios en el dispositivo.| +|**id (String)**| Identificador único del dispositivo bluetooth.| +|**boundState (Int)**| Estado de emparejamiento del dispositivo. Puede tener diferentes valores representando estados distintos.| +|**name (String)**| Nombre del dispositivo ofrecido por el sistema operacional.| +|**address (String)**| Dirección MAC del dispositivo bluetooth.| +|**isConnected (Boolean)**| Indica si el dispositivo está conectado. En caso de ser positivo, la respuesta es `true`. Si está desconectado, aparece como `false`.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/manage-connections.pt.md b/guides/mp-point-main-apps/manage-connections.pt.md new file mode 100644 index 0000000000..1296930409 --- /dev/null +++ b/guides/mp-point-main-apps/manage-connections.pt.md @@ -0,0 +1,162 @@ +# Gerenciar conexões + +Em nosso SDK, você pode buscar impressoras e outros dispositivos bluetooth, além de checar os que estão emparelhados com a maquininha. Aprenda a seguir como fazê-lo. + +## Obter dispositivos emparelhados + +A obtenção da lista dos dispositivos emparelhados com a [Point Smart](/developers/pt/docs/mp-point/landing) é feita usando a função `getPairedDevices`, da classe `BluetoothDiscoverDevices`. Confira abaixo como acessá-la por meio do objeto `MPManager`. + +[[[ +```kotlin +val bluetoothDiscoverDevices = MPManager.bluetooth.discover + +bluetoothDiscoverDevices.getPairedDevices { result -> +   result +       .doIfSuccess { devices -> +           // Trabalhar com a lista de dispositivos emparelhados +       } +       .doIfError { error -> +           // Gerenciar o caso de erro, se necessário +       } +} +``` +```java +final BluetoothDiscoverDevices bluetoothDiscoverDevices = MPManager.INSTANCE.getBluetooth().getDiscover(); + +final Function1>, Unit> callback = (final MPResponse> response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   final List devices = response.getData(); +   // Trabalhar com a lista de dispositivos emparelhados + } else { +   // Gerenciar o caso de erro, se necessário + } + return Unit.INSTANCE; +}; + +bluetoothDiscoverDevices.getPairedDevices(callback); +``` +]]] + +|Campo|Descrição| +|---|---| +|**callback ((MPResponse<List<BluetoothDeviceModel>>) -> Unit)**| Função de devolução da chamada que proporciona os dispositivos emparelhados como resultado. O `[MPResponse]` encapsula o estado, o erro (se houver) e os dados no caso de sucesso, em uma lista de modelos `BluetoothDeviceModel`.| +|**id (String)**|  Identificador único do dispositivo bluetooth.| +|**boundState (Int)**| Estado de emparelhamento do dispositivo. Pode ter diferentes valores representando estados distintos.| +|**name (String)**| Nome do dispositivo proporcionado pelo sistema operacional.| +|**address (String)**| Endereço MAC do dispositivo bluetooth.| +|**isConnected (Boolean)**| Indica se o dispositivo está conectado. Em caso positivo, a resposta é `true`; se estiver desconectado, aparece como `false`.| + +## Obter impressoras emparelhadas + +Use a função `getPairedPrinterDevices` da classe `BluetoothDiscoverDevices` para consultar a lista de impressoras bluetooth emparelhadas com a [Point Smart](/developers/pt/docs/mp-point/landing). O acesso é feito através do objeto `MPManager`, como no exemplo abaixo. + +[[[ +```kotlin +val bluetoothDiscoverDevices = MPManager.bluetooth.discover + +bluetoothDiscoverDevices.getPairedPrinterDevices { result -> +   result +       .doIfSuccess { printers -> +           // Trabalhar com a lista de dispositivos emparelhados +       } +       .doIfError { error -> +           // Gerenciar o caso de erro, se necessário +       } +} +``` +```java +final BluetoothDiscoverDevices bluetoothDiscoverDevices = MPManager.INSTANCE.getBluetooth().getDiscover(); + +final Function1>, Unit> callback = (final MPResponse> response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   final List printers = response.getData(); +   // Trabalhar com a lista de dispositivos emparelhados + } else { +   // Gerenciar o caso de erro, se necessário + } + return Unit.INSTANCE; +}; + +bluetoothDiscoverDevices.getPairedPrinterDevices(callback); +``` +]]] + +|Campo|Descrição| +|---|---| +|**callback ((MPResponse<List<BluetoothDeviceModel>>) -> Unit)**| Função de devolução da chamada que proporciona as impressoras emparelhadas como resultado. O `[MPResponse]` encapsula o estado, o erro (se houver) e os dados em caso de sucesso em uma lista de modelos `BluetoothDeviceModel`.| +|**id (String)**|  Identificador único do dispositivo bluetooth.| +|**boundState (Int)**| Estado de emparelhamento do dispositivo. Pode ter diferentes valores representando estados distintos.| +|**name (String)**| Nome do dispositivo proporcionado pelo sistema operacional.| +|**address (String)**| Endereço MAC do dispositivo bluetooth.| +|**isConnected (Boolean)**| Indica se o dispositivo está conectado. Em caso positivo, a resposta é `true`; se estiver desconectado, aparece como `false`.| + +## Iniciar busca + +A função `startDiscovery` da classe `BluetoothDiscoverDevices` inicia o descobrimento de dispositivos bluetooth. O acesso é feito através do objeto `MPManager`. Este método facilita a implementação dinâmica da lógica baseada em eventos na sua solução. Assim: + +[[[ +```kotlin +val bluetoothDiscover = MPManager.bluetooth.discover + +bluetoothDiscover.startDiscovery { response -> +   response +       .doIfSuccess { discoveryState -> +           when (discoveryState.type) { +               BluetoothDiscoveryState.Type.STARTED -> { +                   // Gerenciar o início da descoberta +               } +               BluetoothDiscoveryState.Type.DEVICE_FOUND -> discoveryState.device?.let { device -> +                   // Gerenciar a descoberta de um novo dispositivo +               } +               BluetoothDiscoveryState.Type.DEVICE_CHANGE -> discoveryState.device?.let { device -> +                   // Gerenciar mudanças em um dispositivo descoberto +               } +               BluetoothDiscoveryState.Type.ENDED -> { +                   // Gerenciar o fim da descoberta +               } +           } +       } +       .doIfError { error -> +           // Gerenciar o caso de erro, se necessário +       } +} +``` +```java +final BluetoothDiscoverDevices bluetoothDiscoverDevices = MPManager.INSTANCE.getBluetooth().getDiscover(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   switch (response.getData().getType()) { +     case STARTED: +       // Gerenciar o início da descoberta +       break; +     case DEVICE_FOUND: +       // Gerenciar a descoberta de um novo dispositivo +       final BluetoothDeviceModel foundDevice = response.getData().getDevice(); +       break; +     case DEVICE_CHANGE: +       // Gerenciar mudanças em um dispositivo descoberto +       final BluetoothDeviceModel changedDevice = response.getData().getDevice(); +       break; +     case ENDED: +       // Gerenciar o fim da descoberta + +   } + } else { +   // Gerenciar o caso de erro, se necessário + } + return Unit.INSTANCE; +}; + +bluetoothDiscoverDevices.startDiscovery(callback); +``` +]]] + +|Campo|Descrição| +|---|---| +|**callback ((MPResponse<BluetoothDiscoveryState>) -> Unit)**| Função de devolução da chamada que proporciona o resultado do processo de descobrimento. O `[MPResponse]` encapsula o estado, o erro (se houver) e os dados em caso de sucesso, contendo um objeto `BluetoothDiscoveryState` que representa o estado atual da descoberta, eventos como o início e fim do descobrimento e mudanças no dispositivo.| +|**id (String)**|  Identificador único do dispositivo bluetooth.| +|**boundState (Int)**| Estado de emparelhamento do dispositivo. Pode ter diferentes valores representando estados distintos.| +|**name (String)**| Nome do dispositivo proporcionado pelo sistema operacional.| +|**address (String)**| Endereço MAC do dispositivo bluetooth.| +|**isConnected (Boolean)**| Indica se o dispositivo está conectado. Em caso positivo, a resposta é `true`; se estiver desconectado, aparece como `false`.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/manage-status.en.md b/guides/mp-point-main-apps/manage-status.en.md new file mode 100644 index 0000000000..d74ee0fd76 --- /dev/null +++ b/guides/mp-point-main-apps/manage-status.en.md @@ -0,0 +1,150 @@ +# Manage status + +Check how to activate, deactivate and validate the current status of the bluetooth using the `BluetoothIgnitor` class. + +## Activate bluetooth + +To activate the bluetooth on the [Smart POS](/developers/en/docs/mp-point/landing) machine, use the `turnOn` feature of the `BluetoothIgnitor` class on our SDK. You can access that feature through the `MPManager` object, as in the example below. + +[[[ +```kotlin +val bluetoothIgnitor = MPManager.bluetooth.ignitor + +bluetoothIgnitor.turnOn { response -> +   response +       .doIfSuccess { result -> +           if (result) { +               // Bluetooth was successfully activated +               // Perform additional actions if necessary +           } else { +               // It wasn’t possible to activate the bluetooth +           } +       }.doIfError { +           // Manage the error case if necessary +       } +} +``` +```java +final BluetoothIgnitor bluetoothIgnitor = MPManager.INSTANCE.getBluetooth().getIgnitor(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   if (response.getData()) { +     // Bluetooth was successfully activated +     // Perform additional actions if necessary +   } else { +     // It wasn’t possible to activate the bluetooth +   } + } else { + +   // Manage the error case if necessary + } + return Unit.INSTANCE; +}; + +bluetoothIgnitor.turnOn(callback); +``` +]]] + +|Field|Description| +|---|---| +|**callback ((MPResponse<Boolean>) -> Unit)**| Request response feature that provides the result of the activation operation. The `[MPResponse]` includes the status, the error (if any) and the details in case of an error. The response contains a **boolean** value where `true` indicates that the bluetooth was activated and `false` the inability to do so.| + +## Deactivate bluetooth + +To deactivate the bluetooth on the [Point Smart](/developers/en/docs/mp-point/landing), use the feature `turnOff` from the `BluetoothIgnitor` class. The access is also done through `MPManager`, as shown below. + +[[[ +```kotlin +val bluetoothIgnitor = MPManager.bluetooth.ignitor + +bluetoothIgnitor.turnOff { response -> +   response +       .doIfSuccess { result -> +           if (!result) { +               // Bluetooth was successfully deactivated +               // Perform additional actions if necessary +           } else { +               // It wasn’t possible to deactivate the bluetooth +           } +       } +       .doIfError { error -> +           // Manage the error case +       } +} +``` +```java +final BluetoothIgnitor bluetoothIgnitor = MPManager.INSTANCE.getBluetooth().getIgnitor(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   if (!response.getData()) { +     // Bluetooth was successfully deactivated +     // Perform additional actions if necessary +   } else { +     // It wasn’t possible to deactivate the bluetooth +   } + } else { + +   // Manage the error case if necessary + } + return Unit.INSTANCE; +}; + +bluetoothIgnitor.turnOff(callback); +``` +]]] + +|Field|Description| +|---|---| +|**callback ((MPResponse<Boolean>) -> Unit)**| Request response feature that provides the result of the deactivation operation. The `[MPResponse]` includes the status, the error (if any), and the details in case of success. The response contains a **boolean** value where `false` indicates that the bluetooth was deactivated and `true` the inability to do so.| + +## Validate the current status of the bluetooth + +The feature `getCurrentState` of the `BluetoothIgnitor` class is used to validate the activation status of the bluetooth on the [Point Smart](/developers/en/docs/mp-point/landing). The access is through the `BluetoothIgnitor` instance from the `MPManager`, as shown in the example below. + +[[[ +```kotlin +val bluetoothIgnitor = MPManager.bluetooth.ignitor + +bluetoothIgnitor.getCurrentState { result -> +   result +       .doIfSuccess { state -> +           if (state) { +               // Bluetooth is activated +               // Perform additional actions if necessary +           } else { +               // Bluetooth is deactivated +               // Perform additional actions if necessary +           } +       } +       .doIfError { error -> +           // Manage the error case if necessary +       } +} +``` +```java +final BluetoothIgnitor bluetoothIgnitor = MPManager.INSTANCE.getBluetooth().getIgnitor(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   if (!response.getData()) { +     // Bluetooth is activated +     //Perform additional actions if necessary +   } else { +     // Bluetooth is deactivated +     // Perform additional actions if necessary +   } + } else { +   // Manage the error case if necessary + } + return Unit.INSTANCE; +}; + +bluetoothIgnitor.getCurrentState(callback); +``` +]]] + +|Field|Description| +|---|---| +|**callback ((MPResponse<Boolean>) -> Unit)**| Request response feature that provides the result the validation of the current status of the bluetooth. The `[MPResponse]` includes the status, the error (if any) and the details in case of success. The response contains a **boolean** value where `true` indicates that the bluetooth is activated and `false` indicates its deactivation.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/manage-status.es.md b/guides/mp-point-main-apps/manage-status.es.md new file mode 100644 index 0000000000..ed4afddd14 --- /dev/null +++ b/guides/mp-point-main-apps/manage-status.es.md @@ -0,0 +1,150 @@ +# Gestionar estado + +Consulta cómo activar, desactivar y validar el estado actual del bluetooth usando la clase `BluetoothIgnitor`. + +## Activar el bluetooth + +Para activar el bluetooth en el lector [Smart](/developers/es/docs/mp-point/landing), usa la función `turnOn` de la clase `BluetoothIgnitor` en nuestro SDK. Puedes acceder a esta función a través del objeto `MPManager`, como en el ejemplo a continuación. + +[[[ +```kotlin +val bluetoothIgnitor = MPManager.bluetooth.ignitor + +bluetoothIgnitor.turnOn { response -> +   response +       .doIfSuccess { result -> +           if (result) { +               // Bluetooth se encendió con éxito +               // Realizar acciones adicionales si es necesario +           } else { +               // No se pudo encender el Bluetooth +           } +       }.doIfError { +           // Manejar el caso de error si es necesario +       } +} +``` +```java +final BluetoothIgnitor bluetoothIgnitor = MPManager.INSTANCE.getBluetooth().getIgnitor(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   if (response.getData()) { +     // Bluetooth se encendió con éxito +     // Realizar acciones adicionales si es necesario +   } else { +     // No se pudo encender el Bluetooth +   } + } else { + +   // Manejar el caso de error si es necesario + } + return Unit.INSTANCE; +}; + +bluetoothIgnitor.turnOn(callback); +``` +]]] + +|Campo|Descripción| +|---|---| +|**callback ((MPResponse<Boolean>) -> Unit)**| Función de devolución del llamado que ofrece el resultado de la operación de activación. El `[MPResponse]` encapsula el estado, el error (si lo hay) y los datos en caso de éxito. La respuesta tiene un valor **booleano**, en el que `true` indica que el bluetooth se activó y `false`, la incapacidad de hacerlo.| + +## Desactivar el bluetooth + +Para desactivar el bluetooth en el [Point Smart](/developers/es/docs/mp-point/landing), usa la función `turnOff` de la clase `BluetoothIgnitor`. El acceso también se hace a través del `MPManager`, como se muestra a continuación. + +[[[ +```kotlin +val bluetoothIgnitor = MPManager.bluetooth.ignitor + +bluetoothIgnitor.turnOff { response -> +   response +       .doIfSuccess { result -> +           if (!result) { +               // Bluetooth se apagó con éxito +               // Realizar acciones adicionales si es necesario +           } else { +               // No se pudo apagar el Bluetooth +           } +       } +       .doIfError { error -> +           // Manejar el caso de error +       } +} +``` +```java +final BluetoothIgnitor bluetoothIgnitor = MPManager.INSTANCE.getBluetooth().getIgnitor(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   if (!response.getData()) { +     // Bluetooth se apagó con éxito +     // Realizar acciones adicionales si es necesario +   } else { +     // No se pudo apagar el Bluetooth +   } + } else { + +   // Manejar el caso de error si es necesario + } + return Unit.INSTANCE; +}; + +bluetoothIgnitor.turnOff(callback); +``` +]]] + +|Campo|Descripción| +|---|---| +|**callback ((MPResponse<Boolean>) -> Unit)**| Función de devolución del llamado que ofrece el resultado de la operación de desactivado. El `[MPResponse]` encapsula el estado, el error (si lo hay) y los datos en caso de éxito. La respuesta tiene un valor **booleano**, en el que `false` indica que o bluetooth se desactivó y `true`, la incapacidad de hacerlo.| + +## Validar el estado actual del bluetooth + +La función `getCurrentState` de la clase `BluetoothIgnitor` se emplea para validar el estado de activación del bluetooth en el [Point Smart](/developers/es/docs/mp-point/landing). El acceso se hace en la instancia `BluetoothIgnitor` a través del `MPManager`, como en el ejemplo a continuación. + +[[[ +```kotlin +val bluetoothIgnitor = MPManager.bluetooth.ignitor + +bluetoothIgnitor.getCurrentState { result -> +   result +       .doIfSuccess { state -> +           if (state) { +               // Bluetooth está encendido +               // Realizar acciones adicionales si es necesario +           } else { +               // Bluetooth está apagado +               // Realizar acciones adicionales si es necesario +           } +       } +       .doIfError { error -> +           // Manejar el caso de error si es necesario +       } +} +``` +```java +final BluetoothIgnitor bluetoothIgnitor = MPManager.INSTANCE.getBluetooth().getIgnitor(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   if (!response.getData()) { +     // Bluetooth está encendido +     // Realizar acciones adicionales si es necesario +   } else { +     // Bluetooth está apagado +     // Realizar acciones adicionales si es necesario +   } + } else { +   // Manejar el caso de error si es necesario + } + return Unit.INSTANCE; +}; + +bluetoothIgnitor.getCurrentState(callback); +``` +]]] + +|Campo|Descripción| +|---|---| +|**callback ((MPResponse<Boolean>) -> Unit)**| Función de devolución del lado que ofrece el resultado de la validación del estado atual del bluetooth. El `[MPResponse]` encapsula el estado, el error (si lo hay) y los datos en caso de éxito. La respuesta tiene un valor **booleano**, en el que `true` indica que el bluetooth está activado y `false`, su desactivación.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/manage-status.pt.md b/guides/mp-point-main-apps/manage-status.pt.md new file mode 100644 index 0000000000..9555fd8d53 --- /dev/null +++ b/guides/mp-point-main-apps/manage-status.pt.md @@ -0,0 +1,150 @@ +# Gerenciar status + +Confira como ativar, desativar e validar o estado atual do bluetooth utilizando a classe `BluetoothIgnitor`. + +## Ativar o bluetooth + +Para ativar o bluetooth na maquininha [Smart](/developers/pt/docs/mp-point/landing), use a função `turnOn` da classe `BluetoothIgnitor` em nosso SDK. Você pode acessar essa função através do objeto `MPManager`, como no exemplo abaixo. + +[[[ +```kotlin +val bluetoothIgnitor = MPManager.bluetooth.ignitor + +bluetoothIgnitor.turnOn { response -> +   response +       .doIfSuccess { result -> +           if (result) { +               // O Bluetooth foi ativado com sucesso +               // Realizar ações adicionais, se necessário +           } else { +               // Não foi possível ativar o Bluetooth +           } +       }.doIfError { +           // Gerenciar o caso de erro, se necessário +       } +} +``` +```java +final BluetoothIgnitor bluetoothIgnitor = MPManager.INSTANCE.getBluetooth().getIgnitor(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   if (response.getData()) { +     // O Bluetooth foi ativado com sucesso +     // Realizar ações adicionais, se necessário +   } else { +     // Não foi possível ativar o Bluetooth +   } + } else { + +   // Gerenciar o caso de erro, se necessário + } + return Unit.INSTANCE; +}; + +bluetoothIgnitor.turnOn(callback); +``` +]]] + +|Campo|Descrição| +|---|---| +|**callback ((MPResponse<Boolean>) -> Unit)**| Função de devolução da chamada que proporciona o resultado da operação de ativação. O `[MPResponse]` encapsula o estado, o erro (se houver) e os dados em caso de sucesso. A resposta contém um valor **booleano**, em que `true` indica que o bluetooth foi ativado e `false`, a incapacidade de fazê-lo.| + +## Desativar o bluetooth + +Para desativar o bluetooth na [Point Smart](/developers/pt/docs/mp-point/landing), use a função `turnOff` da classe `BluetoothIgnitor`. O acesso também é feito através do `MPManager`, como mostrado a seguir. + +[[[ +```kotlin +val bluetoothIgnitor = MPManager.bluetooth.ignitor + +bluetoothIgnitor.turnOff { response -> +   response +       .doIfSuccess { result -> +           if (!result) { +               // O Bluetooth foi desligado com sucesso +               // Realizar ações adicionais, se necessário +           } else { +               // Não foi possível desligar o Bluetooth +           } +       } +       .doIfError { error -> +           // Gerenciar o caso de erro, se necessário +       } +} +``` +```java +final BluetoothIgnitor bluetoothIgnitor = MPManager.INSTANCE.getBluetooth().getIgnitor(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   if (!response.getData()) { +     // O Bluetooth foi desligado com sucesso +     // Realizar ações adicionais, se necessário +   } else { +     // Não foi possível desligar o Bluetooth +   } + } else { + +   // Gerenciar o caso de erro, se necessário + } + return Unit.INSTANCE; +}; + +bluetoothIgnitor.turnOff(callback); +``` +]]] + +|Campo|Descrição| +|---|---| +|**callback ((MPResponse<Boolean>) -> Unit)**| Função de devolução da chamada que proporciona o resultado da operação de desativação. O `[MPResponse]` encapsula o estado, o erro (se houver) e os dados em caso de sucesso. A resposta contém um valor **booleano**, em que `false` indica que o bluetooth foi desativado e `true`, a incapacidade de fazê-lo.| + +## Validar o estado atual do bluetooth + +A função `getCurrentState` da classe `BluetoothIgnitor` é empregada para validar o estado de ativação do bluetooth na [Point Smart](/developers/pt/docs/mp-point/landing). O acesso é feito pela instância `BluetoothIgnitor` através do `MPManager`, como no exemplo abaixo. + +[[[ +```kotlin +val bluetoothIgnitor = MPManager.bluetooth.ignitor + +bluetoothIgnitor.getCurrentState { result -> +   result +       .doIfSuccess { state -> +           if (state) { +               // O Bluetooth está ligado +               // Realizar ações adicionais, se necessário +           } else { +               // O Bluetooth está desligado +               // Realizar acciones adicionales si es necesario +           } +       } +       .doIfError { error -> +           // Gerenciar o caso de erro, se necessário +       } +} +``` +```java +final BluetoothIgnitor bluetoothIgnitor = MPManager.INSTANCE.getBluetooth().getIgnitor(); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   if (!response.getData()) { +     // O Bluetooth está ligado +     // Realizar ações adicionais, se necessário +   } else { +     // O Bluetooth está desligado +     // Realizar ações adicionais, se necessário +   } + } else { +   // Gerenciar o caso de erro, se necessário + } + return Unit.INSTANCE; +}; + +bluetoothIgnitor.getCurrentState(callback); +``` +]]] + +|Campo|Descrição| +|---|---| +|**callback ((MPResponse<Boolean>) -> Unit)**| Função de devolução da chamada que proporciona o resultado da validação do estado atual do bluetooth. O `[MPResponse]` encapsula o estado, o erro (se houver) e os dados em caso de sucesso. A resposta contém um valor **booleano**, em que `true` indica que o bluetooth está ativado e `false`, sua desativação.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/pair-unpair.en.md b/guides/mp-point-main-apps/pair-unpair.en.md new file mode 100644 index 0000000000..ecc1793b54 --- /dev/null +++ b/guides/mp-point-main-apps/pair-unpair.en.md @@ -0,0 +1,94 @@ +# Pair and unpair + +In this section, you’ll learn how to pair and unpair devices with a [Point Smart](/developers/en/docs/mp-point/landing) by using a `BluetoothDevicesPairing` class. + +## Pair a device + +Use the `pairDevice` feature from the `BluetoothDevicesPairing` class to pair a device with Point Smart by sending only the `(address)`. The access is through the  `MPManager` object, as shown below. + +[[[ +```kotlin +val bluetoothPairing = MPManager.bluetooth.paring + +bluetoothPairing.pairDevice(address) { response -> +   response.doIfSuccess { result -> +       // Manage pairing success +       val bondState = result.first +       val deviceModel = result.second +       // ... Perform additional actions if necessary +   }.doIfError { error -> +       // Manage the error case if necessary +   } +} +``` +```java +final BluetoothDevicesPairing bluetoothPairing = MPManager.INSTANCE.getBluetooth().getParing(); + +final Function1>, Unit> callback = +   (final MPResponse> response) -> { +     if (response.getStatus() == ResponseStatus.SUCCESS) { +       final BluetoothBondState bondState = response.getData().getFirst(); +       final BluetoothDeviceModel deviceModel = response.getData().getSecond(); +       // Perform additional actions if necessary +     } else { +       // Manage the error case if necessary +     } +     return Unit.INSTANCE; +   }; + +bluetoothPairing.pairDevice(address, callback); +``` +]]] + +## Unpair a device + +To unpair a device, use the `unPairDevice` feature from the `BluetoothDevicesPairing` class by accessing through the `MPManager` object. This feature uses the (`(address)`) of the selected device as a parameter, as shown below. + +[[[ +```kotlin +val bluetoothPairing = MPManager.bluetooth.paring + +bluetoothPairing.unPairDevice(address) { response -> +   response.doIfSuccess { result -> +       // Manage pairing success +       val bondState = result.first +       val deviceModel = result.second +       // ... Perform additional actions if necessary +   }.doIfError { error -> +       // Manage the error case if necessary +   } +} +``` +```java +final BluetoothDevicesPairing bluetoothPairing = MPManager.INSTANCE.getBluetooth().getParing(); + +final Function1>, Unit> callback = +   (final MPResponse> response) -> { +     if (response.getStatus() == ResponseStatus.SUCCESS) { +       final BluetoothBondState bondState = response.getData().getFirst(); +       final BluetoothDeviceModel deviceModel = response.getData().getSecond(); +       // Perform additional actions if necessary +     } else { +       // Manage the error case if necessary +     } +     return Unit.INSTANCE; +   }; + +bluetoothPairing.unPairDevice(address, callback); +``` +]]] + +## Description of the fields + +|Field|Description| +|---|---| +|**address (String)**| Location of the selected device, obtained through `[BluetoothDeviceModel]`.| +|**callback ((MPResponse<Pair<BluetoothBondState, BluetoothDeviceModel>>) -> Unit)**| Request response feature that provides the result of the pairing process. The [MPResponse] includes the status, the error (if any), and the details in case of success, which contain a `(Pair)` that comprises `[BluetoothBondState]` and [BluetoothDeviceModel].| +|**NONE (BOND_NONE)**| Indicates that the device isn’t paired.| +|**BONDING (BOND_BONDING)**| Indicates that the device is in pairing process. | +|**BONDED (BOND_BONDED)**| Indicates that the device is paired.| +|**id (String)**| Identificador del dispositivo.| +|**boundState (Int)**| Estado de emparejamiento del dispositivo. Puede ser `true` o `false`.| +|**name (String)**| Nombre del dispositivo ofrecido por el sistema operacional.| +|**id (String)**| Dirección MAC del dispositivo.| +|**isConnected (Boolean)**| Indica si el dispositivo está conectado.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/pair-unpair.es.md b/guides/mp-point-main-apps/pair-unpair.es.md new file mode 100644 index 0000000000..da1ad0920e --- /dev/null +++ b/guides/mp-point-main-apps/pair-unpair.es.md @@ -0,0 +1,94 @@ +# Conectar y desconectar + +En esta sección, comprenderás cómo emparejar y desemparejar dispositivos con el [Point Smart](/developers/es/docs/mp-point/landing) usando la clase `BluetoothDevicesPairing`. + +## Emparejar un dispositivo + +Usa la función `pairDevice` de la clase `BluetoothDevicesPairing` para emparejar un dispositivo con el [Point Smart](/developers/es/docs/mp-point/landing) enviando solo la dirección `(address)`. El acceso se hace a través del objeto `MPManager`, como se muestra a continuación. + +[[[ +```kotlin +val bluetoothPairing = MPManager.bluetooth.paring + +bluetoothPairing.pairDevice(address) { response -> +   response.doIfSuccess { result -> +       // Manejar el éxito del emparejamiento +       val bondState = result.first +       val deviceModel = result.second +       // ... Realizar acciones adicionales si es necesario +   }.doIfError { error -> +       // Manejar el caso de error si es necesario +   } +} +``` +```java +final BluetoothDevicesPairing bluetoothPairing = MPManager.INSTANCE.getBluetooth().getParing(); + +final Function1>, Unit> callback = +   (final MPResponse> response) -> { +     if (response.getStatus() == ResponseStatus.SUCCESS) { +       final BluetoothBondState bondState = response.getData().getFirst(); +       final BluetoothDeviceModel deviceModel = response.getData().getSecond(); +       // Realizar acciones adicionales si es necesario +     } else { +       // Manejar el caso de error si es necesario +     } +     return Unit.INSTANCE; +   }; + +bluetoothPairing.pairDevice(address, callback); +``` +]]] + +## Desemparejar un dispositivo + +Para desemparejar un dispositivo, usa la función `unPairDevice` de la clase `BluetoothDevicesPairing` accediendo a través del objeto `MPManager`. Esta función usa como parámetro la dirección `(address)` del dispositivo seleccionado, como se muestra a continuación. + +[[[ +```kotlin +val bluetoothPairing = MPManager.bluetooth.paring + +bluetoothPairing.unPairDevice(address) { response -> +   response.doIfSuccess { result -> +       // Manejar el éxito del emparejamiento +       val bondState = result.first +       val deviceModel = result.second +       // ... Realizar acciones adicionales si es necesario +   }.doIfError { error -> +       // Manejar el caso de error si es necesario +   } +} +``` +```java +final BluetoothDevicesPairing bluetoothPairing = MPManager.INSTANCE.getBluetooth().getParing(); + +final Function1>, Unit> callback = +   (final MPResponse> response) -> { +     if (response.getStatus() == ResponseStatus.SUCCESS) { +       final BluetoothBondState bondState = response.getData().getFirst(); +       final BluetoothDeviceModel deviceModel = response.getData().getSecond(); +       // Realizar acciones adicionales si es necesario +     } else { +       // Manejar el caso de error si es necesario +     } +     return Unit.INSTANCE; +   }; + +bluetoothPairing.unPairDevice(address, callback); +``` +]]] + +## Descripción de campos + +|Campo|Descripción| +|---|---| +|**address (String)**| Ubicación del dispositivo seleccionado, obtenida a través de `[BluetoothDeviceModel]`.| +|**callback ((MPResponse<Pair<BluetoothBondState, BluetoothDeviceModel>>) -> Unit)**| Función de devolución del llamado que ofrece el resultado del proceso de emparejamiento. El `[MPResponse]` encapsula el estado, el error (si lo hay) y los datos en caso de éxito, que tiene un `(Pair)` compuesto por `[BluetoothBondState]` y `[BluetoothDeviceModel]`.| +|**NONE (BOND_NONE)**| Indica que el dispositivo no está emparejado.| +|**BONDING (BOND_BONDING)**| Indica que el dispositivo está en proceso de emparejamiento.| +|**BONDED (BOND_BONDED)**| Indica que o dispositivo está emparejado.| +|**id (String)**| Identificador del dispositivo.| +|**boundState (Int)**| Estado de emparejamiento del dispositivo. Puede ser `true` o `false`.| +|**name (String)**| Nombre del dispositivo ofrecido por el sistema operacional.| +|**id (String)**| Dirección MAC del dispositivo.| +|**isConnected (Boolean)**| Indica si el dispositivo está conectado.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/pair-unpair.pt.md b/guides/mp-point-main-apps/pair-unpair.pt.md new file mode 100644 index 0000000000..980f291291 --- /dev/null +++ b/guides/mp-point-main-apps/pair-unpair.pt.md @@ -0,0 +1,94 @@ +# Emparelhar e desemparelhar + +Nesta seção, você entenderá como emparelhar e desemparelhar dispositivos com a [Point Smart](/developers/pt/docs/mp-point/landing) usando a classe `BluetoothDevicesPairing`. + +## Emparelhar um dispositivo + +Use a função `pairDevice` da classe `BluetoothDevicesPairing` para emparelhar um dispositivo com a [Point Smart](/developers/pt/docs/mp-point/landing) enviando apenas o endereço `(address)`. O acesso é feito por meio do objeto `MPManager`, como mostrado abaixo. + +[[[ +```kotlin +val bluetoothPairing = MPManager.bluetooth.paring + +bluetoothPairing.pairDevice(address) { response -> +   response.doIfSuccess { result -> +       // Manage pairing success +       val bondState = result.first +       val deviceModel = result.second +       // ... Realizar ações adicionais, se necessário +   }.doIfError { error -> +       // Gerenciar o caso de erro, se necessário +   } +} +``` +```java +final BluetoothDevicesPairing bluetoothPairing = MPManager.INSTANCE.getBluetooth().getParing(); + +final Function1>, Unit> callback = +   (final MPResponse> response) -> { +     if (response.getStatus() == ResponseStatus.SUCCESS) { +       final BluetoothBondState bondState = response.getData().getFirst(); +       final BluetoothDeviceModel deviceModel = response.getData().getSecond(); +       // Realizar ações adicionais, se necessário +     } else { +       // Gerenciar o caso de erro, se necessário +     } +     return Unit.INSTANCE; +   }; + +bluetoothPairing.pairDevice(address, callback); +``` +]]] + +## Desemparelhar um dispositivo + +Para desemparelhar um dispositivo, use a função `unPairDevice` da classe `BluetoothDevicesPairing` acessando pelo objeto `MPManager`. Essa função usa como parâmetro o endereço `(address)` do aparelho selecionado, como mostrado a seguir. + +[[[ +```kotlin +val bluetoothPairing = MPManager.bluetooth.paring + +bluetoothPairing.unPairDevice(address) { response -> +   response.doIfSuccess { result -> +       // Manage pairing success +       val bondState = result.first +       val deviceModel = result.second +       // ... Realizar ações adicionais, se necessário +   }.doIfError { error -> +       // Gerenciar o caso de erro, se necessário +   } +} +``` +```java +final BluetoothDevicesPairing bluetoothPairing = MPManager.INSTANCE.getBluetooth().getParing(); + +final Function1>, Unit> callback = +   (final MPResponse> response) -> { +     if (response.getStatus() == ResponseStatus.SUCCESS) { +       final BluetoothBondState bondState = response.getData().getFirst(); +       final BluetoothDeviceModel deviceModel = response.getData().getSecond(); +       // Realizar ações adicionais, se necessário +     } else { +       // Gerenciar o caso de erro, se necessário +     } +     return Unit.INSTANCE; +   }; + +bluetoothPairing.unPairDevice(address, callback); +``` +]]] + +## Descrição dos campos + +|Campo|Descrição| +|---|---| +|**address (String)**| Localização do dispositivo selecionado, obtida por `[BluetoothDeviceModel]`.| +|**callback ((MPResponse<Pair<BluetoothBondState, BluetoothDeviceModel>>) -> Unit)**| Função de devolução da chamada que proporciona o resultado do processo de emparelhamento. O `[MPResponse]` encapsula o estado, o erro (se houver) e os dados no caso de sucesso, que contêm um `(Pair)` composto por `[BluetoothBondState]` e `[BluetoothDeviceModel]`.| +|**NONE (BOND_NONE)**| Indica que o dispositivo não está emparelhado.| +|**BONDING (BOND_BONDING)**| Indica que o dispositivo está em processo de emparelhamento. | +|**BONDED (BOND_BONDED)**| Indica que o dispositivo está emparelhado.| +|**id (String)**| Identificador do dispositivo.| +|**boundState (Int)**| Estado de emparejação do dispositivo. Pode ser `true` ou `false`.| +|**name (String)**| Nome do dispositivo proporcionado pelo sistema operacional.| +|**id (String)**| Endereço MAC do dispositivo.| +|**isConnected (Boolean)**| Indica se o dispositivo está conectado.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/prerequisites.en.md b/guides/mp-point-main-apps/prerequisites.en.md index bc43543417..a5574b862d 100644 --- a/guides/mp-point-main-apps/prerequisites.en.md +++ b/guides/mp-point-main-apps/prerequisites.en.md @@ -4,15 +4,17 @@ Before you start developing your solution, take a look at the requirements that | Requirement | Description | |---|---| +| Aplicação | As aplicações são as diferentes integrações contidas em uma ou mais lojas. Você pode criar uma aplicação para cada solução que implementar, a fim de ter tudo organizado e manter um controle que facilite a gestão. Veja [Suas integrações](/developers/pt/docs/main-apps/additional-content/your-integrations/introduction) para mais informações sobre como criar uma aplicação.| +| Credentials | Unique passwords with which we identify an integration in your account. To perform the integrations, you will need the **Client ID**. [Click here](/developers/en/docss/main-apps/additional-content/your-integrations/credentials) for more information. | +| Mercado Pago's Point Smart | [Mercado Pago Point](/developers/en/docs/mp-point/landing) is the Mercado Pago card machine that allows buyers to pay in person quickly and securely using credit or debit cards.| | Device pre-configuration| In order for the machines to operate in **Integrated mode** and for the pre-configuration to be carried out, share with Mercado Pago the account that will be used for the integration, as well as the cash register and store configurations and the serial numbers of the devices. | |Development kit | To start development, download the [Development kit](https://github.com/mercadolibre/point-mainapp-demo-android) provided by Mercado Pago. | -|Android Studio| Install the [integrated development environment](https://developer.android.com/studio) to build and debug the main apps. | -|App in the Developer Panel | Create an app in the [developer panel](/developers/panel/app) with the integrator's account. Then generate the `ClientId` that will serve as the integration identifier. Check out more information about creating an application in [Application details](/developers/en/docs/main-apps/additional-content/your-integrations/application-details). | -|OAuth flow| If you want to obtain information from the seller's account, do the [OAuth flow](/developers/en/docs/main-apps/additional-content/security/oauth/introduction). | +|Android Studio| OAuth is an authorization protocol that allows applications to have limited access to the private information of Mercado Pago accounts. Install the [integrated development environment](https://developer.android.com/studio) to build and debug the main apps. | +|OAuth| If you want to obtain information from the seller's account, do the [OAuth flow](/developers/en/docs/main-apps/additional-content/security/oauth/introduction). | ## Point Smart technical specifications -To ensure that the integration is successful, consider the machine's characteristics and how the application will adapt to them. +To ensure that the integration is successful, consider the [Point Smart](/developers/en/docs/mp-point/landing) machine's characteristics and how the application will adapt to them. ![prerequisites](/main-apps/prerequisites-all.png) diff --git a/guides/mp-point-main-apps/prerequisites.es.md b/guides/mp-point-main-apps/prerequisites.es.md index 51f74c2a6a..a38312c227 100644 --- a/guides/mp-point-main-apps/prerequisites.es.md +++ b/guides/mp-point-main-apps/prerequisites.es.md @@ -4,15 +4,17 @@ Antes de empezar a desarrollar tu solución, consulta las condiciones que debes | Requisitos | Descripción | |---|---| +| Aplicación | Las aplicaciones son las diversas integraciones contenidas en una o varias tiendas. Puedes crear una aplicación para cada solución que implementes a fin de tener todo organizado y mantener un control que facilite la gestión. Consulta tu [Tus integraciones](/developers/es/docs/main-apps/additional-content/your-integrations/introduction) para obtener más información sobre cómo crear una aplicación. | +|Credenciales | Contraseñas únicas con las que identificamos una integración en tu cuenta. Para realizar las integraciones, necesitará del **Client ID**. Accede a [Credenciales](/developers/es/docs/main-apps/additional-content/your-integrations/credentials) para obtener más información. | +| Point Smart de Mercado Pago | [Mercado Pago Point](/developers/es/docs/mp-point/landing) es la máquina de tarjetas de Mercado Pago que permite a los compradores realizar pagos presenciales de forma rápida y segura mediante tarjetas de crédito o débito.| | Pre-configuración de dispositivos | Para que los lectores operen de **Modo integrado** y se haga la pre-configuración, comparte con Mercado Pago la cuenta que se usará para la integración, así como la configuración de cajas, tiendas y números de serie de dispositivos. | |Kit de Desarrollo | Para empezar el desarrollo, descarga el [Kit de Desarrollo](https://github.com/mercadolibre/point-mainapp-demo-android) que ofrece Mercado Pago. | |Android Studio | Instala el [ambiente de desarrollo Android](https://developer.android.com/studio) para construir y depurar las main apps. | -|App en Panel de Desarrolladores | Crea una app en el [panel de desarrolladores](/developers/panel/app) con la cuenta de integrador. Luego, genera el `ClientId` que servirá como identificador de la integración. Consulte más información sobre cómo crear una aplicación en [Detalles de la aplicación](/developers/es/docs/main-apps/additional-content/your-integrations/application-details). | -|Flujo de OAuth | Para obtener información de la cuenta de quienes venden, haz el [flujo de OAuth](/developers/es/docs/main-apps/additional-content/security/oauth/introduction). | +|OAuth | OAuth es un protocolo de autorización que permite que las aplicaciones tengan acceso limitado a la información privada de las cuentas de Mercado Pago. Para obtener información de la cuenta de quienes venden, haz el [flujo de OAuth](/developers/es/docs/main-apps/additional-content/security/oauth/introduction). | ## Especificaciones técnicas de Point Smart -Para garantizar que la integración sea exitosa, considera las características del lector y cómo la app se adaptará a ellas. +Para garantizar que la integración sea exitosa, considera las características del lector [Point Smart](/developers/es/docs/mp-point/landing) y cómo la app se adaptará a ellas. ![prerequisites](/main-apps/prerequisites-all.png) diff --git a/guides/mp-point-main-apps/prerequisites.pt.md b/guides/mp-point-main-apps/prerequisites.pt.md index d471fbd29f..21a696e134 100644 --- a/guides/mp-point-main-apps/prerequisites.pt.md +++ b/guides/mp-point-main-apps/prerequisites.pt.md @@ -4,15 +4,17 @@ Antes de começar a desenvolver sua solução, veja as condições que devem ser | Requisitos | Descrição | |---|---| +| Aplicação | As aplicações são as diferentes integrações contidas em uma ou mais lojas. Você pode criar uma aplicação para cada solução que implementar, a fim de ter tudo organizado e manter um controle que facilite a gestão. Veja [Suas integrações](/developers/pt/docs/checkout-bricks/additional-content/your-integrations/introduction) para mais informações sobre como criar uma aplicação. | +| Credenciais | Senhas únicas com as quais identificamos uma integração na sua conta. Para realizar as integrações, será necessário o **Client ID**. Acesse [Credenciais](/developers/pt/docs/main-apps/additional-content/your-integrations/credentials) para mais informações. | +| Point Smart do Mercado Pago | [Mercado Pago Point](/developers/pt/docs/mp-point/landing) é a maquininha de cartão do Mercado Pago que permite aos compradores realizarem pagamentos presenciais de maneira rápida e segura utilizando cartões de crédito ou débito. | | Pré-configuração de dispositivos | Para que as maquininhas operem em **Modo integrado** e a pré-configuração seja feita, compartilhe com o Mercado Pago a conta que será utilizada para a integração, bem como as configurações de caixas, lojas e números de série dos aparelhos. | |Kit de Desenvolvimento| Para iniciar o desenvolvimento, baixe o [Kit de Desenvolvimento](https://github.com/mercadolibre/point-mainapp-demo-android) fornecido pelo Mercado Pago. | |Android Studio| Instale o [ambiente de desenvolvimento Android](https://developer.android.com/studio) para construir e depurar os main apps.| -|App no Painel de Desenvolvedores | Crie um app no [painel de desenvolvedores](/developers/panel/app) com a conta do integrador. Em seguida, gere o `ClientId` que servirá como identificador da integração. Veja mais informações sobre como criar uma aplicação em [Detalhes da aplicação](/developers/pt/docs/main-apps/additional-content/your-integrations/application-details).| -|Fluxo de OAuth| Se for obter informações da conta da pessoa vendedora, faça o [fluxo de OAuth](/developers/pt/docs/main-apps/additional-content/security/oauth/introduction). | +|OAuth| O OAuth é um protocolo de autorização que permite que aplicações tenham acesso limitado às informações privadas das contas do Mercado Pago. Se for obter informações da conta da pessoa vendedora, faça o [fluxo de OAuth](/developers/pt/docs/main-apps/additional-content/security/oauth/introduction). | ## Especificações técnicas da Point Smart -Para garantir que a integração seja exitosa, considere as características da maquininha e como o aplicativo se adaptará a elas. +Para garantir que a integração seja exitosa, considere as características da maquininha [Point Smart](/developers/pt/docs/mp-point/landing) e como o aplicativo se adaptará a elas. ![prerequisites](/main-apps/prerequisites-all.png) diff --git a/guides/mp-point-main-apps/print-external-printer.en.md b/guides/mp-point-main-apps/print-external-printer.en.md new file mode 100644 index 0000000000..b12829624e --- /dev/null +++ b/guides/mp-point-main-apps/print-external-printer.en.md @@ -0,0 +1,104 @@ +# Print with an external printer + +Use the print feature, of the `BluetoothPrinter` class, to print with an external printer. Access is through the `MPManager` object. Check how to do it. + +[[[ +```kotlin +val bluetoothPrinter = MPManager.bluetooth.printer + +bluetoothPrinter.print(dataToPrint) { response -> +   response +       .doIfSuccess { printerResult -> +           // Manage successful print case +           when (printerResult) { +               BluetoothPrinterResult.SUCCESS -> { +                   // Successful print +                   // ... Perform additional actions if necessary +               } + +               BluetoothPrinterResult.NEED_SELECTION_DEVICE -> { +                   // More than one paired device, specific address is required +                   // ... Perform additional actions if necessary +               } + +               else -> { // Other success cases } +               } +           } +       }.doIfError { error -> +           // Manage the error case if necessary +       } +} +``` +```java +final BluetoothPrinter bluetoothPrinter = MPManager.INSTANCE.getBluetooth().getPrinter(); + +final Function1, Unit> callback = +   (final MPResponse response) -> { +     if (response.getStatus() == ResponseStatus.SUCCESS) { +       // Perform additional actions if necessary +     } else { +       //Manage the error case if necessary +     } +     return Unit.INSTANCE; +   }; + +bluetoothPrinter.print(dataToPrint, callback); +``` +]]] + +|Field|Description| +|---|---| +|**dataToPrint (String)**| Text sequence you want to print.| +|**callback ((MPResponse<BluetoothPrinterResult>) -> Unit)**| Request response feature that provides the result of the print request. The `[MPResponse]` includes the status, the error (if any), and the details in case of success, which contain a `[BluetoothPrinterResult]` object.| +|**CONNECTION_FAILED**| Indicates that the connection failed.| +|**ERROR_UNDEFINED**| Indicates that there is an error with an unknown cause. | +|**SUCCESS**| Indicates that the printing was successful.| +|**NEED_SELECTION_DEVICE**| Indicates that it’s necessary to specify the address of the devices when there’s more than one printer paired.| +|**ERROR_DATA_TO_PRINT_NULL**| Indicates that the details to print are null.| +|**ERROR_PRINTER_NOT_FOUND**| Indicates that no paired printers were found.| + +## Print using an external printer with a specific address + +To print with an external printer identified by its address, use the print feature of the BluetoothPrinter class. Access must be through the MPManager object, as shown below. + +[[[ +```kotlin +val bluetoothPrinter = MPManager.bluetooth.printer + +bluetoothPrinter.print(dataToPrint, address) { response -> +   response +       .doIfSuccess { printerResult -> +           // Manage successful printing result +       }.doIfError { error -> +           // Manage the error case if necessary +       } +} +``` +```java +final BluetoothPrinter bluetoothPrinter = MPManager.INSTANCE.getBluetooth().getPrinter(); + +final Function1, Unit> callback = +   (final MPResponse response) -> { +     if (response.getStatus() == ResponseStatus.SUCCESS) { +       // Perform additional actions if necessary +     } else { +       // Manage the error case if necessary +     } +     return Unit.INSTANCE; +   }; + +bluetoothPrinter.print(dataToPrint, address, callback); +``` +]]] + +|Field|Description| +|---|---| +|**dataToPrint (String)**| Text sequence you want to print.| +|**address (String)**| Address of the printer that will be used to print.| +|**callback ((MPResponse<BluetoothPrinterResult>) -> Unit)**| Request response feature that provides the result of the print request. The `[MPResponse]` includes the status, the error (if any), and the details in case of success, which contain a `[BluetoothPrinterResult]` object.| +|**CONNECTION_FAILED**| Indicates that the connection failed.| +|**ERROR_UNDEFINED**| Indicates that there is an error with an unknown cause. | +|**SUCCESS**| Indicates that the printing was successful.| +|**NEED_SELECTION_DEVICE**| Indicates that it’s necessary to specify the address of the devices when there’s more than one printer paired.| +|**ERROR_DATA_TO_PRINT_NULL**| Indicates that the details to print are null.| +|**ERROR_PRINTER_NOT_FOUND**| Indicates that no paired printers were found.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/print-external-printer.es.md b/guides/mp-point-main-apps/print-external-printer.es.md new file mode 100644 index 0000000000..5165dce4a0 --- /dev/null +++ b/guides/mp-point-main-apps/print-external-printer.es.md @@ -0,0 +1,104 @@ +# Imprimir con impresora externa + +Usa la función print, de la clase `BluetoothPrinter`, para hacer impresiones con la impresora externa. Este acceso se hace a través del objeto `MPManager`. Consulta cómo hacerlo. + +[[[ +```kotlin +val bluetoothPrinter = MPManager.bluetooth.printer + +bluetoothPrinter.print(dataToPrint) { response -> +   response +       .doIfSuccess { printerResult -> +           // Manejar el resultado exitoso de la impresión +           when (printerResult) { +               BluetoothPrinterResult.SUCCESS -> { +                   // Impresión exitosa +                   // ... Realizar acciones adicionales si es necesario +               } + +               BluetoothPrinterResult.NEED_SELECTION_DEVICE -> { +                   // Más de un dispositivo emparejado, se requiere especificar la dirección +                   // ... Realizar acciones adicionales si es necesario +               } + +               else -> { // Otros casos de resultado exitoso } +               } +           } +       }.doIfError { error -> +           // Manejar el caso de error si es necesario +       } +} +``` +```java +final BluetoothPrinter bluetoothPrinter = MPManager.INSTANCE.getBluetooth().getPrinter(); + +final Function1, Unit> callback = +   (final MPResponse response) -> { +     if (response.getStatus() == ResponseStatus.SUCCESS) { +       // Realizar acciones adicionales si es necesario +     } else { +       // Manejar el caso de error si es necesario +     } +     return Unit.INSTANCE; +   }; + +bluetoothPrinter.print(dataToPrint, callback); +``` +]]] + +|Campo|Descripción| +|---|---| +|**dataToPrint (String)**| Secuencia de texto que se quiere imprimir.| +|**callback ((MPResponse<BluetoothPrinterResult>) -> Unit)**| Función de devolución del llamado que ofrece el resultado del pedido de impresión. El `[MPResponse]` encapsula el estado, el error (si lo hay) y los datos en caso de éxito, que tiene un objeto `[BluetoothPrinterResult]`.| +|**CONNECTION_FAILED**| Indica que la conexión falló.| +|**ERROR_UNDEFINED**| Indica que hay un error de causa indefinida. | +|**SUCCESS**| Indica que la impresión fue exitosa.| +|**NEED_SELECTION_DEVICE**| Indica que hace falta especificar la dirección de los dispositivos cuando hay más de una impresora emparejada.| +|**ERROR_DATA_TO_PRINT_NULL**| Indica que los datos para imprimir son nulos.| +|**ERROR_PRINTER_NOT_FOUND**| Indica que no se encontraron impresoras emparejadas.| + +## Imprimir usando una impressora externa con dirección específica + +Para imprimir con una impresora externa identificada por tu dirección, usa la función print de la clase `BluetoothPrinter`. El acceso se debe hacer a través del objeto `MPManager`, como se ejemplifica a continuación. + +[[[ +```kotlin +val bluetoothPrinter = MPManager.bluetooth.printer + +bluetoothPrinter.print(dataToPrint, address) { response -> +   response +       .doIfSuccess { printerResult -> +           // Manejar el resultado exitoso de la impresión +       }.doIfError { error -> +           // Manejar el caso de error si es necesario +       } +} +``` +```java +final BluetoothPrinter bluetoothPrinter = MPManager.INSTANCE.getBluetooth().getPrinter(); + +final Function1, Unit> callback = +   (final MPResponse response) -> { +     if (response.getStatus() == ResponseStatus.SUCCESS) { +       // Realizar acciones adicionales si es necesario +     } else { +       // Manejar el caso de error si es necesario +     } +     return Unit.INSTANCE; +   }; + +bluetoothPrinter.print(dataToPrint, address, callback); +``` +]]] + +|Campo|Descripción| +|---|---| +|**dataToPrint (String)**| Secuencia de texto que se quiere imprimir| +|**address (String)**| Dirección de la impresora que se usará para la impresión.| +|**callback ((MPResponse<BluetoothPrinterResult>) -> Unit)**| Función de devolución del llamado que ofrece el resultado del pedido de impresión. El `[MPResponse]` encapsula el estado, el error (si lo hay) y los datos en caso de éxito, que tiene un objeto `[BluetoothPrinterResult]`.| +|**CONNECTION_FAILED**| Indica que la conexión falló.| +|**ERROR_UNDEFINED**| Indica que hay un error de causa indefinida. | +|**SUCCESS**| Indica que la impresión fue exitosa| +|**NEED_SELECTION_DEVICE**| Indica que hace falta especificar la dirección de los dispositivos cuando hay más de una impresora emparejada| +|**ERROR_DATA_TO_PRINT_NULL**| Indica que los datos para imprimir son nulos.| +|**ERROR_PRINTER_NOT_FOUND**| Indica que no se encontraron impresoras emparejadas.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/print-external-printer.pt.md b/guides/mp-point-main-apps/print-external-printer.pt.md new file mode 100644 index 0000000000..3f0da40648 --- /dev/null +++ b/guides/mp-point-main-apps/print-external-printer.pt.md @@ -0,0 +1,104 @@ +# Imprimir com impressora externa + +Use a função print, da classe `BluetoothPrinter`, para fazer impressões com uma impressora externa. Este acesso é feito pelo objeto `MPManager`. Confira como fazê-lo. + +[[[ +```kotlin +val bluetoothPrinter = MPManager.bluetooth.printer + +bluetoothPrinter.print(dataToPrint) { response -> +   response +       .doIfSuccess { printerResult -> +           // Gerenciar o resultado bem-sucedido da impressão +           when (printerResult) { +               BluetoothPrinterResult.SUCCESS -> { +                   // Impressão bem-sucedida +                   // ... Realizar ações adicionais, se necessário +               } + +               BluetoothPrinterResult.NEED_SELECTION_DEVICE -> { +                   // Mais de um dispositivo emparelhado, é necessário especificar o endereço +                   // ... Realizar ações adicionais, se necessário +               } + +               else -> { // Outros casos de resultado bem-sucedido } +               } +           } +       }.doIfError { error -> +           // Gerenciar o caso de erro, se necessário +       } +} +``` +```java +final BluetoothPrinter bluetoothPrinter = MPManager.INSTANCE.getBluetooth().getPrinter(); + +final Function1, Unit> callback = +   (final MPResponse response) -> { +     if (response.getStatus() == ResponseStatus.SUCCESS) { +       // Realizar ações adicionais, se necessário +     } else { +       // Gerenciar o caso de erro, se necessário +     } +     return Unit.INSTANCE; +   }; + +bluetoothPrinter.print(dataToPrint, callback); +``` +]]] + +|Campo|Descrição| +|---|---| +|**dataToPrint (String)**| Sequência de texto que se deseja imprimir.| +|**callback ((MPResponse<BluetoothPrinterResult>) -> Unit)**| Função de devolução da chamada que proporciona o resultado do pedido de impressão. O `[MPResponse]` encapsula o estado, o erro (se houver) e os dados no caso de sucesso, que contêm um objeto `[BluetoothPrinterResult]`.| +|**CONNECTION_FAILED**| Indica que a conexão falhou.| +|**ERROR_UNDEFINED**| Indica que há um erro de causa indefinida. | +|**SUCCESS**| Indica que a impressão foi exitosa.| +|**NEED_SELECTION_DEVICE**| Indica que é preciso especificar o endereço dos dispositivos quando há mais de uma impressora emparelhada.| +|**ERROR_DATA_TO_PRINT_NULL**| Indica que os dados para imprimir são nulos.| +|**ERROR_PRINTER_NOT_FOUND**| Indica que não foram encontradas impressoras emparelhadas.| + +## Imprimir usando uma impressora externa com endereço específico + +Para imprimir com uma impressora externa identificada por seu endereço, use a função print da classe `BluetoothPrinter`. O acesso deve ser feito pelo objeto `MPManager`, como exemplificado abaixo. + +[[[ +```kotlin +val bluetoothPrinter = MPManager.bluetooth.printer + +bluetoothPrinter.print(dataToPrint, address) { response -> +   response +       .doIfSuccess { printerResult -> +           // Gerenciar o resultado bem-sucedido da impressão +       }.doIfError { error -> +           // Gerenciar o caso de erro, se necessário +       } +} +``` +```java +final BluetoothPrinter bluetoothPrinter = MPManager.INSTANCE.getBluetooth().getPrinter(); + +final Function1, Unit> callback = +   (final MPResponse response) -> { +     if (response.getStatus() == ResponseStatus.SUCCESS) { +       // Realizar ações adicionais, se necessário +     } else { +       // Gerenciar o caso de erro, se necessário +     } +     return Unit.INSTANCE; +   }; + +bluetoothPrinter.print(dataToPrint, address, callback); +``` +]]] + +|Campo|Descrição| +|---|---| +|**dataToPrint (String)**| Sequência de texto que se deseja imprimir.| +|**address (String)**| Endereço da impressora que será usada para a impressão.| +|**callback ((MPResponse<BluetoothPrinterResult>) -> Unit)**| Função de devolução da chamada que proporciona o resultado do pedido de impressão. O `[MPResponse]` encapsula o estado, o erro (se houver) e os dados no caso de sucesso, que contêm um objeto `[BluetoothPrinterResult]`.| +|**CONNECTION_FAILED**| Indica que a conexão falhou.| +|**ERROR_UNDEFINED**| Indica que há um erro de causa indefinida. | +|**SUCCESS**| Indica que a impressão foi exitosa.| +|**NEED_SELECTION_DEVICE**| Indica que é preciso especificar o endereço dos dispositivos quando há mais de uma impressora emparelhada.| +|**ERROR_DATA_TO_PRINT_NULL**| Indica que os dados para imprimir são nulos.| +|**ERROR_PRINTER_NOT_FOUND**| Indica que não foram encontradas impressoras emparelhadas.| diff --git a/guides/mp-point-main-apps/print-images.en.md b/guides/mp-point-main-apps/print-images.en.md new file mode 100644 index 0000000000..f8d464c52e --- /dev/null +++ b/guides/mp-point-main-apps/print-images.en.md @@ -0,0 +1,38 @@ +# Imprimir imágenes + +Para imprimir imagens en bitmap con la impresora de [Point Smart](/developers/pt/docs/mp-point/landing), usa la **función print** de la clase `BitmapPrinter`. El acceso se da a través del objeto `MPManager`, como en el ejemplo a continuación: + +[[[ +```kotlin +val bitmapPrinter = MPManager.bitmapPrinter + +val imageToPrint: Bitmap = bitmap // Obtener la imagen bitmap que se imprimirá + +bitmapPrinter.print(imageToPrint) { response -> +   response.doIfSuccess { printResult -> +       // Gerenciar a impressão bem-sucedida +   }.doIfError { error -> +       // anage error in the printing operation +``` +```java +final BitmapPrinter bitmapPrinter = MPManager.INSTANCE.getBitmapPrinter(); + +final Bitmap imageToPrint = bitmap // Obtener la imagen bitmap que se imprimirá + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Gerenciar a impressão bem-sucedida + } else { +   // anage error in the printing operation + } + return Unit.INSTANCE; +}; + +bitmapPrinter.print(imageToPrint, callback); +``` +]]] + +|Field|Description| +|---|---| +|**dataToPrint (Bitmap)**| The bitmap image that will be printed.| +|**callback ((MPResponse<String>) -> Unit)**| Request response feature that provides the result of the printing operation. The `[MPResponse]` includes the status, the error (if any), and the details in case of success, which contain a String representing the ID or status of the printing.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/print-images.es.md b/guides/mp-point-main-apps/print-images.es.md new file mode 100644 index 0000000000..80d6619145 --- /dev/null +++ b/guides/mp-point-main-apps/print-images.es.md @@ -0,0 +1,38 @@ +# Imprimir imágenes + +Para imprimir imagens en bitmap con la impresora de [Point Smart](/developers/es/docs/mp-point/landing), usa la **función print** de la clase `BitmapPrinter`. El acceso se da a través del objeto `MPManager`, como en el ejemplo a continuación: + +[[[ +```kotlin +val bitmapPrinter = MPManager.bitmapPrinter + +val imageToPrint: Bitmap = bitmap // Get the bitmap image that will be printed + +bitmapPrinter.print(imageToPrint) { response -> +   response.doIfSuccess { printResult -> +       // Gerenciar a impressão bem-sucedida +   }.doIfError { error -> +       // Gerenciar o erro na operação de impressão +``` +```java +final BitmapPrinter bitmapPrinter = MPManager.INSTANCE.getBitmapPrinter(); + +final Bitmap imageToPrint = bitmap // Get the bitmap image that will be printed + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Gerenciar a impressão bem-sucedida + } else { +   // Gerenciar o erro na operação de impressão + } + return Unit.INSTANCE; +}; + +bitmapPrinter.print(imageToPrint, callback); +``` +]]] + +|Campo|Descripción| +|---|---| +|**dataToPrint (Bitmap)**| La imagen bitmap que se imprimirá.| +|**callback ((MPResponse<String>) -> Unit)**| Función de devolución del llamado que ofrece la operación de impresión. El `[MPResponse]` encapsula el estado, el error (si lo hay) y los datos en caso de éxito, que tiene un **String** representando el ID o estado de la impresión.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/print-images.pt.md b/guides/mp-point-main-apps/print-images.pt.md new file mode 100644 index 0000000000..bde257a758 --- /dev/null +++ b/guides/mp-point-main-apps/print-images.pt.md @@ -0,0 +1,38 @@ +# Imprimir imagens + +Para imprimir imagens em bitmap com a impressora da [Point Smart](/developers/pt/docs/mp-point/landing), use a **função print** da classe `BitmapPrinter`. O acesso ocorre por meio do objeto `MPManager`, como no exemplo a seguir: + +[[[ +```kotlin +val bitmapPrinter = MPManager.bitmapPrinter + +val imageToPrint: Bitmap = bitmap // Obter a imagem bitmap que será impressa + +bitmapPrinter.print(imageToPrint) { response -> +   response.doIfSuccess { printResult -> +       // Manejar la impresión exitosa +   }.doIfError { error -> +       // Manejar el error en la operación de impresión +``` +```java +final BitmapPrinter bitmapPrinter = MPManager.INSTANCE.getBitmapPrinter(); + +final Bitmap imageToPrint = bitmap // Obtener la imagen Bitmap que se imprimirá + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Manejar la impresión exitosa + } else { +   // Manejar el error en la operación de impresión + } + return Unit.INSTANCE; +}; + +bitmapPrinter.print(imageToPrint, callback); +``` +]]] + +|Campo|Descrição| +|---|---| +|**dataToPrint (Bitmap)**| A imagem bitmap que será impressa.| +|**callback ((MPResponse<String>) -> Unit)**| Função de devolução da chamada que proporciona o resultado da operação de impressão. O `[MPResponse]` encapsula o estado, o erro (se houver) e os dados em caso de sucesso, que contêm um String representando o ID ou estado da impressão.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/restrictions.en.md b/guides/mp-point-main-apps/restrictions.en.md index e81c26738c..9c40a2165b 100644 --- a/guides/mp-point-main-apps/restrictions.en.md +++ b/guides/mp-point-main-apps/restrictions.en.md @@ -26,11 +26,7 @@ Libraries that interact directly with the device's hardware, such as those from ## Issue with Build Tools -> WARNING -> -> Attention -> -> If the message **"Installed Build Tools revision 32.0.0 is corrupted"** is displayed, delete the program and install it again using the **SDK Manager**. +If the message **"Installed Build Tools revision 32.0.0 is corrupted"** is displayed, delete the program and install it again using the **SDK Manager**. Then run this command in the terminal: diff --git a/guides/mp-point-main-apps/restrictions.es.md b/guides/mp-point-main-apps/restrictions.es.md index 9ddf371e5c..c0ee25d05e 100644 --- a/guides/mp-point-main-apps/restrictions.es.md +++ b/guides/mp-point-main-apps/restrictions.es.md @@ -26,11 +26,7 @@ Las que interactuan directo con el hardware del dispositivo, como las de los fab ## Problema con Build Tools -> WARNING -> -> Atención -> -> Si el mensaje **"El Build Tools instalado revisión 32.0.0 está dañado"** aparece, elimina el programa y vuelve a instalarlo usando el **SDK Manager**. +Si el mensaje **"El Build Tools instalado revisión 32.0.0 está dañado"** aparece, elimina el programa y vuelve a instalarlo usando el **SDK Manager**. Luego, ejecuta este comando en la terminal: diff --git a/guides/mp-point-main-apps/restrictions.pt.md b/guides/mp-point-main-apps/restrictions.pt.md index bf32bb1ba8..2d09bb16f3 100644 --- a/guides/mp-point-main-apps/restrictions.pt.md +++ b/guides/mp-point-main-apps/restrictions.pt.md @@ -26,11 +26,7 @@ As que interagem diretamente com o hardware do dispositivo, como as dos fabrican ## Problema com o Build Tools -> WARNING -> -> Atenção -> -> Se a mensagem **"O Build Tools instalado revisão 32.0.0 está danificado”** for apresentada, exclua o programa e instale novamente utilizando o **SDK Manager**. +Se a mensagem **"O Build Tools instalado revisão 32.0.0 está danificado”** for apresentada, exclua o programa e instale novamente utilizando o **SDK Manager**. Em seguida, execute este comando no terminal: diff --git a/guides/mp-point-main-apps/scan-codes.en.md b/guides/mp-point-main-apps/scan-codes.en.md new file mode 100644 index 0000000000..dd1bcd84d9 --- /dev/null +++ b/guides/mp-point-main-apps/scan-codes.en.md @@ -0,0 +1,106 @@ +# Scan barcodes and QR codes + +Below you will find information on how to start and manage the [Point Smart](/developers/pt/docs/mp-point/landing) scanner for reading **barcodes and QR codes**. + +## Barcode + +To begin reading QR codes of the [Point Smart](/developers/en/docs/mp-point/landing), use the `initBarcodeScanner` feature of the `CameraScanner` class. + +This process uses a camera request through `startActivityForResult`, and the method `onActivityResult` must be implemented in the activity to handle the reading response. + +Check the example below: + +[[[ +```kotlin +val cameraScanner = MPManager.cameraScanner +cameraScanner.initBarcodeScanner(this@YourActivity) +``` +```java +final CameraScanner cameraScanner = MPManager.INSTANCE.getCameraScanner(); +cameraScanner.initBarcodeScanner(this); +``` +]]] + +## QR code + +To begin reading QR codes of the [Point Smart](/developers/en/docs/mp-point/landing), use the `initQRCodeScanner` feature of the `CameraScanner` class. + +This process uses a camera request through `startActivityForResult`, and the method `onActivityResult` must be implemented in the activity to handle the reading response. + +Check the example below: + +[[[ +```kotlin +val cameraScanner = MPManager.cameraScanner +cameraScanner.initQRCodeScanner(this@YourActivity) +``` +```java +final CameraScanner cameraScanner = MPManager.INSTANCE.getCameraScanner(); +cameraScanner.initQRCodeScanner(this); +``` +]]] + +## Process scanner response + +To manage the response of a **QR code** or **barcode** scanning activity, use the `handleQrResponse` feature of the `CameraScanner` class from the `onActivityResult` method. + +This function processes the scanner result from the camera, validating the response and invoking the appropriate callback based on the result. It receives an `MPResponse` object with a `[CameraScannerResponse]`, representing the reading response. + +This method simplifies the process of handling the responses from the QR code or barcode scanner in the `onActivityResult` method, processing the scanner result from the camera, validating the response, and invoking the appropriate callback based on the result. + +Check how that takes place below. + +[[[ +```kotlin +override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + + val cameraScanner = MPManager.cameraScanner + + cameraScanner.handleScannerResponse(this, resultCode, data) { response -> + response.doIfSuccess { result -> + // Manage successful response + val status = result.status + val message = result.message + // ... Do something with the response + }.doIfError { error -> + // Manage the error in the response + val errorMessage = error.message + // ... Do something with the error + } + } +} +``` +```java +@Override +protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { + super.onActivityResult(requestCode, resultCode, data); + + final CameraScanner cameraScanner = MPManager.INSTANCE.getCameraScanner(); + final Function1, Unit> callback = (final MPResponse response) -> { + + if (response.getStatus() == ResponseStatus.SUCCESS) { + final CameraScannerResponse cameraScannerResponse = response.getData(); + // Manage successful response + final String result = response.getData().getMessage(); + // ... Do something with the response + } else { + // Manage the error in the response + final Exception errorMessage = response.getError(); + // ... Do something with the error + } + return Unit.INSTANCE; + }; + + cameraScanner.handleScannerResponse(this, resultCode, data, callback); +} +``` +]]] + +|Field|Description| +|---|---| +|**resultCode (Int)**| Value of the `resultCode` in `onActivityResult`.| +|**resultData (Intent?)**| Date result in `onActivityResult`.| +|**MPResponse<CameraScannerResponse>**| Object [MPResponse] that includes the status, the error (if any), and the details in case of success, which contain an `CameraScannerResponse` object.| +|**status (CameraScannerStatus)**| Defines the status of the response. It can be "Ok" (it read it successfully), **Error** (something went wrong and it was cancelled) or **Unknown** (something went wrong).| +|**message (String)**| Defines the response message received by the scanner. If it’s ”Ok”, it will have the result of the reading of the code.| diff --git a/guides/mp-point-main-apps/scan-codes.es.md b/guides/mp-point-main-apps/scan-codes.es.md new file mode 100644 index 0000000000..a2fd4c7dc9 --- /dev/null +++ b/guides/mp-point-main-apps/scan-codes.es.md @@ -0,0 +1,106 @@ +# Escanear códigos de barras y QR + +A continuación, encontrará información sobre cómo iniciar y gestionar el escáner de [Point Smart](/developers/pt/docs/mp-point/landing) para la lectura de **códigos de barras y QR**. + +## Código de barras + +Para iniciar la lectura de códigos QR del [Point Smart](/developers/es/docs/mp-point/landing), usa la función `initBarcodeScanner` de la clase `CameraScanner`. + +Este proceso usa un llamado de cámara a través de `startActivityForResult`, de modo que el método `onActivityResult` se debe implementar en la actividad para manipular la respuesta de lectura. + +Consulta el ejemplo a continuación. + +[[[ +```kotlin +val cameraScanner = MPManager.cameraScanner +cameraScanner.initBarcodeScanner(this@YourActivity) +``` +```java +final CameraScanner cameraScanner = MPManager.INSTANCE.getCameraScanner(); +cameraScanner.initBarcodeScanner(this); +``` +]]] + +## Código QR + +Para iniciar la lectura de códigos QR del [Point Smart](/developers/es/docs/mp-point/landing), usa la función `initQRCodeScanner` de la clase `CameraScanner`. + +Este proceso usa un llamado de cámara a través de `startActivityForResult`, de modo que el método `onActivityResult` se debe implementar en la actividad para manipular la respuesta de lectura. + +Consulta el ejemplo a continuación. + +[[[ +```kotlin +val cameraScanner = MPManager.cameraScanner +cameraScanner.initQRCodeScanner(this@YourActivity) +``` +```java +final CameraScanner cameraScanner = MPManager.INSTANCE.getCameraScanner(); +cameraScanner.initQRCodeScanner(this); +``` +]]] + +## Procesar la respuesta del escáner + +Para gestionar la respuesta de una actividad de escaneo de **código QR** o de **código de barras**, usa la función `handleQrResponse` de la clase `CameraScanner` en el método `onActivityResult`. + +Esta función procesa el resultado del escáner desde la cámara, validando la respuesta e invocando el callback apropiado según el resultado. Recibe un objeto `MPResponse` con un `[CameraScannerResponse]`, representando la respuesta de lectura. + +Este método simplifica el proceso de manejo de respuestas del escáner de QR o código de barra en el método `onActivityResult`, procesando el resultado del escáner desde la cámara, validando la respuesta e invocando el _callback_ apropiado según el resultado. + +Consulta cómo continuar. + +[[[ +```kotlin +override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + + val cameraScanner = MPManager.cameraScanner + + cameraScanner.handleScannerResponse(this, resultCode, data) { response -> + response.doIfSuccess { result -> + // Manejar la respuesta exitosa + val status = result.status + val message = result.message + // ... Hacer algo con la respuesta + }.doIfError { error -> + // Manejar el error en la respuesta + val errorMessage = error.message + // ... Hacer algo con el error + } + } +} +``` +```java +@Override +protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { + super.onActivityResult(requestCode, resultCode, data); + + final CameraScanner cameraScanner = MPManager.INSTANCE.getCameraScanner(); + final Function1, Unit> callback = (final MPResponse response) -> { + + if (response.getStatus() == ResponseStatus.SUCCESS) { + final CameraScannerResponse cameraScannerResponse = response.getData(); + // Manejar la respuesta exitosa + final String result = response.getData().getMessage(); + // ... Hacer algo con la respuesta + } else { + // Manejar el error en la respuesta + final Exception errorMessage = response.getError(); + // ... Hacer algo con el error + } + return Unit.INSTANCE; + }; + + cameraScanner.handleScannerResponse(this, resultCode, data, callback); +} +``` +]]] + +|Campo|Descripción| +|---|---| +|**resultCode (Int)**| Valor del `resultCode` en `onActivityResult`.| +|**resultData (Intent?)**| Valor de la fecha en `onActivityResult`.| +|**MPResponse<CameraScannerResponse>**| Objeto `[MPResponse]` que encapsula el estado, el error (si lo hay) y los datos en caso de éxito, que tiene un objeto `CameraScannerResponse`.| +|**status (CameraScannerStatus)**| Define el estado de la respuesta. Puede ser "Ok" (la lectura fue exitosa), **Error** (hubo un error o la lectura se canceló) o **Unknown** (hubo algún error indeterminado).| +|**message (String)**| Define el mensaje de la respuesta recibida por escaner. Si es ”Ok”, tendrá el resultado de la lectura del código.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/scan-codes.pt.md b/guides/mp-point-main-apps/scan-codes.pt.md new file mode 100644 index 0000000000..d739e87ecf --- /dev/null +++ b/guides/mp-point-main-apps/scan-codes.pt.md @@ -0,0 +1,106 @@ +# Escanear códigos de barras e QR + +Abaixo você encontrará informações de como iniciar e gerenciar o escâner da [Point Smart](/developers/pt/docs/mp-point/landing) para a leitura de **códigos de barra e QR**. + +## Código de barras + +Para iniciar a leitura de códigos de barras da [Point Smart](/developers/pt/docs/mp-point/landing), use a função `initBarcodeScanner` da classe `CameraScanner`. + +Esse processo utiliza uma chamada de câmera mediante `startActivityForResult`, de modo que o método `onActivityResult` deve ser implementado na atividade para manipular a resposta de leitura. + +Confira o exemplo a seguir. + +[[[ +```kotlin +val cameraScanner = MPManager.cameraScanner +cameraScanner.initBarcodeScanner(this@YourActivity) +``` +```java +final CameraScanner cameraScanner = MPManager.INSTANCE.getCameraScanner(); +cameraScanner.initBarcodeScanner(this); +``` +]]] + +## Código QR + +Para iniciar a leitura de códigos QR da [Point Smart](/developers/pt/docs/mp-point/landing), use a função `initQRCodeScanner` da classe `CameraScanner`. + +Esse processo utiliza uma chamada de câmera mediante `startActivityForResult`, de modo que o método `onActivityResult` deve ser implementado na atividade para manipular a resposta de leitura. + +Confira o exemplo a seguir. + +[[[ +```kotlin +val cameraScanner = MPManager.cameraScanner +cameraScanner.initQRCodeScanner(this@YourActivity) +``` +```java +final CameraScanner cameraScanner = MPManager.INSTANCE.getCameraScanner(); +cameraScanner.initQRCodeScanner(this); +``` +]]] + +## Processar resposta de escâner + +Para gerenciar a resposta de uma atividade de escâner de **código QR** ou de **código de barras**, use a função `handleScannerResponse` da classe `CameraScanner` no método `onActivityResult`. + +Esta função processa o resultado do escâner da câmera, validando a resposta e invocando o _callback_ apropriado de acordo com o resultado. Recebe um objeto `MPResponse` com um `[CameraScannerResponse]`, representando a resposta da leitura. + +Este método simplifica o processo de gerenciamento das respostas do escâner de QR ou código de barras no método `onActivityResult`, processando o resultado do escâner da câmera, validando a resposta e invocando o _callback_ apropriado de acordo com o resultado. + +Confira como isso ocorre a seguir. + +[[[ +```kotlin +override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + + val cameraScanner = MPManager.cameraScanner + + cameraScanner.handleScannerResponse(this, resultCode, data) { response -> + response.doIfSuccess { result -> + // Gerenciar resposta bem-sucedida + val status = result.status + val message = result.message + // ... Fazer algo com a resposta + }.doIfError { error -> + // Gerenciar o erro na resposta + val errorMessage = error.message + // ... Fazer algo com o erro + } + } +} +``` +```java +@Override +protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { + super.onActivityResult(requestCode, resultCode, data); + + final CameraScanner cameraScanner = MPManager.INSTANCE.getCameraScanner(); + final Function1, Unit> callback = (final MPResponse response) -> { + + if (response.getStatus() == ResponseStatus.SUCCESS) { + final CameraScannerResponse cameraScannerResponse = response.getData(); + // Gerenciar resposta bem-sucedida + final String result = response.getData().getMessage(); + // ... Fazer algo com a resposta + } else { + // Gerenciar o erro na resposta + final Exception errorMessage = response.getError(); + // ... Fazer algo com o erro + } + return Unit.INSTANCE; + }; + + cameraScanner.handleScannerResponse(this, resultCode, data, callback); +} +``` +]]] + +|Campo|Descrição| +|---|---| +|**resultCode (Int)**| Valor do `resultCode` em `onActivityResult`.| +|**resultData (Intent?)**|Valor de `data` em `onActivityResult`.| +|**MPResponse<CameraScannerResponse>**| Objeto `[MPResponse]` que encapsula o estado, o erro (se houver) e os dados em caso de sucesso, que contêm um objeto `CameraScannerResponse`. El callback a ser invocado con el resultado de la operación del escáner. | +|**status (CameraScannerStatus)**| Define o estado da resposta. Pode ser "Ok" (a leitura foi exitosa), **Error** (houve um erro ou a leitura foi cancelada) ou **Unknown** (ocorreu um erro indeterminado).| +|**message (String)**| Define a mensagem da resposta recebida pelo escâner. Se for "Ok", conterá o resultado da leitura do código.| \ No newline at end of file diff --git a/guides/mp-point-main-apps/start-payment-flow.en.md b/guides/mp-point-main-apps/start-payment-flow.en.md new file mode 100644 index 0000000000..5c221d731f --- /dev/null +++ b/guides/mp-point-main-apps/start-payment-flow.en.md @@ -0,0 +1,207 @@ +# Start payment flow + +To offer a fluid experience in your application, our SDK facilitates the initialization of the payment flow through the `PaymentFlow` class. Here’s how: + +[[[ +```kotlin +val paymentFlow = MPManager.paymentFlow + +val amount = "2.0" +val description = "Payment description" +val intentSuccess = paymentFlow.buildCallbackUri( +   callback = "mercadopago://smart_integrations/payment_result", +   methodCallback = "success", +   metadata = hashMapOf("message" to "testSuccess"), +   appID = "demo.app" +) +val intentError = paymentFlow.buildCallbackUri( +   callback = "mercadopago://smart_integrations/payment_result", +   methodCallback = "error", +   metadata = hashMapOf("message" to "testError"), +   appID = "demo.app" +) + +val paymentFlowData = PaymentFlowData( +   amount = amount, +   description = description, +   intentSuccess = intentSuccess, +   intentError = intentError, +   paymentMethod = PaymentMethod.CREDIT_CARD.name, +   installments = 6 +) +paymentFlow.launchPaymentFlowActivity( +   paymentFlowData = paymentFlowData, +   context = context +) { response -> +   response.doIfSuccess { message -> +       // Success management with a message +   }.doIfError { error -> +       // Error management +   } +} +``` +```java +final PaymentFlow paymentFlow = MPManager.INSTANCE.getPaymentFlow(); + +final HashMap successMetadata = new HashMap<>(); +successMetadata.put("success", "testSuccess"); + +final HashMap errorMetadata = new HashMap<>(); +successMetadata.put("message", "testError"); + +final String amount = "2.0"; +final String description = "Payment description"; +final Uri intentSuccess = paymentFlow.buildCallbackUri( +   "mercadopago://smart_integrations/payment_result", +   "success", +   successMetadata, +   "demo.app" +); +final Uri intentError = paymentFlow.buildCallbackUri( +   "mercadopago://smart_integrations/payment_result", +   "error", +   errorMetadata, +   "demo.app" +); + +final PaymentFlowData paymentFlowData = new PaymentFlowData( +   amount, +   description, +   intentSuccess, +   intentError, +   PaymentMethod.CREDIT_CARD.name(), +   6 +); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Success management with a message + } else { +   // Error management + } + return Unit.INSTANCE; +}; + +paymentFlow.launchPaymentFlowActivity(paymentFlowData, context, callback); +``` +]]] + +|Field|Description| +|---|---| +|**amount (String)**| The amount used to start the payment flow.| +|**description (String)**| The description used to start the payment flow. Using it is optional.| +|**intentSuccess (Uri)**| URI that requests the success screen. It’s used to create a deeplink that leads to the success activity.| +|**intentError (Uri)**| URI that requests the error screen. It’s used to create a deeplink that leads to the error activity.| +|**paymentMethod (String)**| The payment method to complete the transaction. Using it is optional.| +|**installments (Int)**| The number of installments used to start the payment flow, Available only for Brazil. Using it is optional.| +|**launchPaymentFlowActivity**| This method starts the payment flow using the SmartPOS app.| +|**paymentFlowData (PaymentFlowData)**| Detail model necessary to open the flow.| +|**context (Context)**| Context from where the flow will begin.| +|**allback (MPResponse<String> -> Unit)**| Provides the result of the opening of the payment flow.| + +## Build a URI to open the payment flow + +The feature `buildCallbackUri` is designed to build a valid URI that allows you to open a specific activity, based on the deeplink strategy. To access, use the `PaymentFlow` instance through the `MPManager` object. + +> WARNING +> +> Attention +> +> Correctly set up your deeplink in your `AndroidManifest` so that the corresponding activity leads to the request. + +Check how to implement this feature: + +[[[ +```kotlin +val paymentFlow = MPManager.paymentFlow + +val uriResult = paymentFlow.buildCallbackUri( +   callback = "tuHost://tuApp/result", +   methodCallback = "error", +   metadata = hashMapOf("message" to "result"), +   appID = "demo.app" +) +``` +```java +final PaymentFlow paymentFlow = MPManager.INSTANCE.getPaymentFlow(); + +final HashMap resultMetadata = new HashMap<>(); +resultMetadata.put("message", "result"); + +final Uri uriResult = paymentFlow.buildCallbackUri( +   "tuHost://tuApp/result", +   "error", +   resultMetadata, +   "demo.app" +); +``` +]]] + +|Field|Description| +|---|---| +|**callback (String)**| The value of the URI to request the deeplink. E.g.: `yourHost://tuApp/test`.| +|**methodCallback (String)**| Identifies if the URI is for a success, error or another custom response. | +|**metadata (HashMap<String, String>)**| Optional field to send information to the response screen, in case it’s necessary to show additional details, like the name of the customer or the summary of the products that were purchased.| +|**appID (String)**| Identifier of the main app. We use the package name. E.g.: `com.yourcompany.yourapp`.| +|**Uri**| the URI defined with the information provided.| + +## Get the payment response + +The feature `parseResponse` of the `PaymentFlow` class is used to receive the result of the payment flow, which is delivered as the `PaymentResponse` object ready for its handling. In this process, the following information is provided: + +- **Payment method used;** +- **Payment reference;** +- **Creation date;** +- **Payment amount;** +- **Serial number of the POS machine;** +- **Card brand;** +- **Number of installments;** +- **Last four digits of the card;** +- **Any errors associated with the transaction.** + +Check how to implement this feature: + +[[[ +```kotlin +intent.data?.let { data -> +   val response = paymentFlow.parseResponse(data) +   if (response.paymentReference.isNotEmpty()) { +       // Payment management with success case +   } else { +       // Payment management with an error +   } +} +``` +```java +final PaymentFlow paymentFlow = MPManager.INSTANCE.getPaymentFlow(); + +final Uri resultUri = getIntent().getData(); +final PaymentResponse response = paymentFlow.parseResponse(resultUri); + +if (!response.getPaymentReference().isEmpty()) { + // Payment management with success case +} else { + // Payment management with an error +} +``` +]]] + +|Field|Description| +|---|---| +|**response (Uri)**| The response received by the [SmartPOS](/developers/en/docs/mp-point/landing). To find it, use `intent.data` of the Activity in charge of opening the deeplink set within the `buildCallbackUri` feature.| +|**PaymentResponse**| Object that contains transaction details. If the response is null, it brings a `PaymentResponse` object with a `paymentStatusError`.| +|**paymentMethod**| Payment method used to complete the transaction. E.g.: credit card, debit card, QR code, payment link. | +|**paymentReference**| Unique transaction identifying number.| +|**paymentCreationDate**| Creation date of the transaction.| +|**paymentAmount**| Payment amount.| +|**paymentSnDevice**| Serial number of the POS machine with which the transaction was done.| +|**paymentBrandName**| User name registered in the POS machine.| +|**paymentInstallments**| Number of installments that a person selected when completing the payment. | +|**paymentLastFourDigits**| Last four digits of the card used for the payment.| +|**paymentStatusError**| Field to register transaction problems or errors.| + +> WARNING +> +> Attention +> +> Make sure that the response of the payment flow is valid and contains the necessary information. \ No newline at end of file diff --git a/guides/mp-point-main-apps/start-payment-flow.es.md b/guides/mp-point-main-apps/start-payment-flow.es.md new file mode 100644 index 0000000000..5bafdf2370 --- /dev/null +++ b/guides/mp-point-main-apps/start-payment-flow.es.md @@ -0,0 +1,207 @@ +# Iniciar el flujo de pago + +Para ofrecer una experiencia fluida en tu app, nuestro SDK facilita la inicialización del flujo de pago a través de la clase `PaymentFlow`. De esta forma: + +[[[ +```kotlin +val paymentFlow = MPManager.paymentFlow + +val amount = "2.0" +val description = "Payment description" +val intentSuccess = paymentFlow.buildCallbackUri( +   callback = "mercadopago://smart_integrations/payment_result", +   methodCallback = "success", +   metadata = hashMapOf("message" to "testSuccess"), +   appID = "demo.app" +) +val intentError = paymentFlow.buildCallbackUri( +   callback = "mercadopago://smart_integrations/payment_result", +   methodCallback = "error", +   metadata = hashMapOf("message" to "testError"), +   appID = "demo.app" +) + +val paymentFlowData = PaymentFlowData( +   amount = amount, +   description = description, +   intentSuccess = intentSuccess, +   intentError = intentError, +   paymentMethod = PaymentMethod.CREDIT_CARD.name, +   installments = 6 +) +paymentFlow.launchPaymentFlowActivity( +   paymentFlowData = paymentFlowData, +   context = context +) { response -> +   response.doIfSuccess { message -> +       // Manejo de éxito utilizando un mensaje +   }.doIfError { error -> +       // Manejo del error +   } +} +``` +```java +final PaymentFlow paymentFlow = MPManager.INSTANCE.getPaymentFlow(); + +final HashMap successMetadata = new HashMap<>(); +successMetadata.put("success", "testSuccess"); + +final HashMap errorMetadata = new HashMap<>(); +successMetadata.put("message", "testError"); + +final String amount = "2.0"; +final String description = "Payment description"; +final Uri intentSuccess = paymentFlow.buildCallbackUri( +   "mercadopago://smart_integrations/payment_result", +   "success", +   successMetadata, +   "demo.app" +); +final Uri intentError = paymentFlow.buildCallbackUri( +   "mercadopago://smart_integrations/payment_result", +   "error", +   errorMetadata, +   "demo.app" +); + +final PaymentFlowData paymentFlowData = new PaymentFlowData( +   amount, +   description, +   intentSuccess, +   intentError, +   PaymentMethod.CREDIT_CARD.name(), +   6 +); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Manejo de éxito utilizando un mensaje + } else { +   // Manejo del error + } + return Unit.INSTANCE; +}; + +paymentFlow.launchPaymentFlowActivity(paymentFlowData, context, callback); +``` +]]] + +|Campo|Descripción| +|---|---| +|**amount (String)**|E l monto usado para iniciar el flujo de pago.| +|**description (String)**| La descripción usada para iniciar el flujo de pago. Su uso es opcional.| +|**intentSuccess (Uri)**| URI que llama la pantalla de éxito. Se usa para formar un deeplink que envía la actividad de éxito.| +|**intentError (Uri)**| URI que llama la pantalla de error. Se usa para formar un deeplink que envía la actividad de error.| +|**paymentMethod (String)**| El medio de pago para realizar la operación. Su uso es opcional.| +|**installments (Int)**| El número de cuotas usado para iniciar el flujo de pago. Está disponible solo para Brasil, y su uso es opcional.| +|**launchPaymentFlowActivity**| Este método inicia el flujo de pago usando la app SmartPOS.| +|**paymentFlowData (PaymentFlowData)**| Modelo de datos necesario para la apertura del flujo.| +|**context (Context)**| Contexto de dónde se inciará el flujo.| +|**allback (MPResponse<String> -> Unit)**| Ofrece el resultado de la apertura del flujo de pago.| + +## Construir una URI para apertura del flujo de pago + +La función `buildCallbackUri` está diseñada para construir una URI válida que permita abrir una actividad específica, con base en la estrategia del _deeplink_. Para acceder a ella, usa la función `PaymentFlow` a través del objeto `MPManager`. + +> WARNING +> +> Atención +> +> Configura correctamente el deeplink en tu `AndroidManifest` para que la actividad correspondiente direccione el llamado. + +Consulta cómo implementar esta funcionalidad: + +[[[ +```kotlin +val paymentFlow = MPManager.paymentFlow + +val uriResult = paymentFlow.buildCallbackUri( +   callback = "tuHost://tuApp/result", +   methodCallback = "error", +   metadata = hashMapOf("message" to "result"), +   appID = "demo.app" +) +``` +```java +final PaymentFlow paymentFlow = MPManager.INSTANCE.getPaymentFlow(); + +final HashMap resultMetadata = new HashMap<>(); +resultMetadata.put("message", "result"); + +final Uri uriResult = paymentFlow.buildCallbackUri( +   "tuHost://tuApp/result", +   "error", +   resultMetadata, +   "demo.app" +); +``` +]]] + +|Campo|Descripción| +|---|---| +|**callback (String)**| El monto de la URI para llamar el _deeplink_. Ejemplo: `tuHost://tuApp/prueba`.| +|**methodCallback (String)**| Identifica si la URI es para un caso de éxito, de error u otra respuesta personalizada.| +|**metadata (HashMap<String, String>)**| Campo opcional para enviar información a la pantalla de respuesta, en caso de que sea necesario mostrar detalles adicionales, como el nombre del cliente o el resumen de los productos comprados. | +|**appID (String)**|  Identificador de la app principal. Usamos el nombre del paquete. Ejemplo: `com.tuempresa.tuapp`.| +|**Uri**| La URI definida con la información ingresada.| + +## Obtener el resultado del pago + +La función `parseResponse` de la clase `PaymentFlow` se usa para recibir el resultado del flujo de pago, que se entrega en forma de objeto `PaymentResponse` listo para su manipulación. En este proceso, la siguiente información se ofrece: + +- **Medio de pago usado;** +- **Referencia de pago;** +- **Fecha de creación;** +- **Monto del pago;** +- **Número de serie del lector;** +- **Marca de la tarjeta;** +- **Cantidad de cuotas;** +- **Últimos cuatro números de la tarjeta;** +- **Cualquier error asociado a la operación.** + +Consulta cómo implementar esta funcionalidad: + +[[[ +```kotlin +intent.data?.let { data -> +   val response = paymentFlow.parseResponse(data) +   if (response.paymentReference.isNotEmpty()) { +       // Manejo de pago con un resultado de éxito +   } else { +       // Manejo de pago con un resultado de error +   } +} +``` +```java +final PaymentFlow paymentFlow = MPManager.INSTANCE.getPaymentFlow(); + +final Uri resultUri = getIntent().getData(); +final PaymentResponse response = paymentFlow.parseResponse(resultUri); + +if (!response.getPaymentReference().isEmpty()) { + // Manejo de pago con un resultado de éxito +} else { + // Manejo de pago con un resultado de error +} +``` +]]] + +|Campo|Descripción| +|---|---| +|**response (Uri)**| La respuesta recibida de [SmartPOS](/developers/es/docs/mp-point/landing). Para encontrarla, usa `intent.data` de la _Activity_ encargada de abrir el _deeplink_ configurado dentro de la función `buildCallbackUri`.| +|**PaymentResponse**| Objeto que contiene detalles de la operación. Si la respuesta es nula, se devuelve un `PaymentResponse` con un `paymentStatusError`.| +|**paymentMethod**| Medio de pago usado para hacer la operación. Ejemplos: crédito, débito, código QR, link de pago. | +|**paymentReference**| Número identificador único de la operación.| +|**paymentCreationDate**| Fecha de creación de la operación.| +|**paymentAmount**|  Monto del pago.| +|**paymentSnDevice**| Número de serie del lector donde se hizo la operación.| +|**paymentBrandName**| Nombre de usuario registrado en el lector.| +|**paymentInstallments**| Número de cuotas que la persona seleccionó al hacer el pago.| +|**paymentLastFourDigits**| Últimos cuatro números de la tarjeta usada en el pago.| +|**paymentStatusError**| Campo para registrar problemas y errores de la operación.| + +> WARNING +> +> Atención +> +> Asegúrate de que la respuesta del flujo de pago sea válida y tenga la información necesaria. \ No newline at end of file diff --git a/guides/mp-point-main-apps/start-payment-flow.pt.md b/guides/mp-point-main-apps/start-payment-flow.pt.md new file mode 100644 index 0000000000..e9ba563856 --- /dev/null +++ b/guides/mp-point-main-apps/start-payment-flow.pt.md @@ -0,0 +1,207 @@ +# Iniciar o fluxo de pagamento + +Para oferecer uma experiência fluida no seu aplicativo, nosso SDK facilita a inicialização do fluxo de pagamento através da classe `PaymentFlow`. Desta forma: + +[[[ +```kotlin +val paymentFlow = MPManager.paymentFlow + +val amount = "2.0" +val description = "Payment description" +val intentSuccess = paymentFlow.buildCallbackUri( +   callback = "mercadopago://smart_integrations/payment_result", +   methodCallback = "success", +   metadata = hashMapOf("message" to "testSuccess"), +   appID = "demo.app" +) +val intentError = paymentFlow.buildCallbackUri( +   callback = "mercadopago://smart_integrations/payment_result", +   methodCallback = "error", +   metadata = hashMapOf("message" to "testError"), +   appID = "demo.app" +) + +val paymentFlowData = PaymentFlowData( +   amount = amount, +   description = description, +   intentSuccess = intentSuccess, +   intentError = intentError, +   paymentMethod = PaymentMethod.CREDIT_CARD.name, +   installments = 6 +) +paymentFlow.launchPaymentFlowActivity( +   paymentFlowData = paymentFlowData, +   context = context +) { response -> +   response.doIfSuccess { message -> +       // Gerenciamento bem-sucedido usando uma mensagem +   }.doIfError { error -> +       // Gerenciamento do erro +   } +} +``` +```java +final PaymentFlow paymentFlow = MPManager.INSTANCE.getPaymentFlow(); + +final HashMap successMetadata = new HashMap<>(); +successMetadata.put("success", "testSuccess"); + +final HashMap errorMetadata = new HashMap<>(); +successMetadata.put("message", "testError"); + +final String amount = "2.0"; +final String description = "Payment description"; +final Uri intentSuccess = paymentFlow.buildCallbackUri( +   "mercadopago://smart_integrations/payment_result", +   "success", +   successMetadata, +   "demo.app" +); +final Uri intentError = paymentFlow.buildCallbackUri( +   "mercadopago://smart_integrations/payment_result", +   "error", +   errorMetadata, +   "demo.app" +); + +final PaymentFlowData paymentFlowData = new PaymentFlowData( +   amount, +   description, +   intentSuccess, +   intentError, +   PaymentMethod.CREDIT_CARD.name(), +   6 +); + +final Function1, Unit> callback = (final MPResponse response) -> { + if (response.getStatus() == ResponseStatus.SUCCESS) { +   // Gerenciamento bem-sucedido usando uma mensagem + } else { +   // Gerenciamento do erro + } + return Unit.INSTANCE; +}; + +paymentFlow.launchPaymentFlowActivity(paymentFlowData, context, callback); +``` +]]] + +|Campo|Descrição| +|---|---| +|**amount (String)**| O valor usado para iniciar o fluxo de pagamento.| +|**description (String)**| A descrição usada para iniciar o fluxo de pagamento. Seu uso é opcional.| +|**intentSuccess (Uri)**| URI que chama a tela de sucesso. É usada para formar um deeplink que envia a atividade de sucesso.| +|**intentError (Uri)**| URI que chama a tela de erro. É usada para formar um deeplink que envia a atividade de erro.| +|**paymentMethod (String)**| O meio de pagamento para realizar a transação. Seu uso é opcional.| +|**installments (Int)**| O número de parcelas usado para iniciar o fluxo de pagamento. Está disponível apenas para o Brasil e seu uso é opcional.| +|**launchPaymentFlowActivity**| Esse método inicia o fluxo de pagamento usando o aplicativo SmartPOS.| +|**paymentFlowData (PaymentFlowData)**| Modelo de dados necessário para a abertura do fluxo.| +|**context (Context)**| Contexto de onde será iniciado o fluxo.| +|**Callback (MPResponse<String> -> Unit)**| Proporciona o resultado da abertura do fluxo de pagamento.| + +## Construir uma URI para abertura do fluxo de pagamento + +A função `buildCallbackUri` está desenhada para construir uma URI válida que permita abrir uma atividade específica, com base na estratégia do _deeplink_. Para acessar, use a instância `PaymentFlow` através do objeto `MPManager`. + +> WARNING +> +> Atenção +> +> Configure corretamente o _deeplink_ no seu `AndroidManifest` para que a atividade correspondente direcione a chamada. + +Confira como implementar essa funcionalidade: + +[[[ +```kotlin +val paymentFlow = MPManager.paymentFlow + +val uriResult = paymentFlow.buildCallbackUri( +   callback = "tuHost://tuApp/result", +   methodCallback = "error", +   metadata = hashMapOf("message" to "result"), +   appID = "demo.app" +) +``` +```java +final PaymentFlow paymentFlow = MPManager.INSTANCE.getPaymentFlow(); + +final HashMap resultMetadata = new HashMap<>(); +resultMetadata.put("message", "result"); + +final Uri uriResult = paymentFlow.buildCallbackUri( +   "tuHost://tuApp/result", +   "error", +   resultMetadata, +   "demo.app" +); +``` +]]] + +|Campo|Descrição| +|---|---| +|**callback (String)**| O valor da URI para chamar o _deeplink_. Exemplo: `tuHost://tuApp/prueba`.| +|**methodCallback (String)**| Identifica se a URI é para um caso de sucesso, erro ou outra resposta personalizada.| +|**metadata (HashMap<String, String>)**| Campo opcional para enviar informação à tela de resposta, caso seja necessário mostrar detalhes adicionais, como o nome do cliente ou o resumo dos produtos comprados. | +|**appID (String)**| Identificador do aplicativo principal. Usamos o nome do pacote. Exemplo: `com.tuempresa.tuapp`.| +|**Uri**| A URI definida com a informação proporcionada.| + +## Obter o resultado do pagamento + +A função `parseResponse` da classe `PaymentFlow` é usada para receber o resultado do fluxo de pagamento, sendo entregue na forma de objeto `PaymentResponse` pronto para a sua manipulação. Nesse processo, as seguintes informações são proporcionadas: + +- **Meio de pagamento usado;** +- **Referência de pagamento;** +- **Data de criação;** +- **Valor do pagamento;** +- **Número de série da maquininha;** +- **Bandeira do cartão;** +- **Quantidade de parcelas;** +- **Últimos quatro dígitos do cartão;** +- **Qualquer erro associado à transação.** + +Confira como implementar esta funcionalidade: + +[[[ +```kotlin +intent.data?.let { data -> +   val response = paymentFlow.parseResponse(data) +   if (response.paymentReference.isNotEmpty()) { +       // Gerenciamento de pagamento com um resultado de sucesso +   } else { +       // Gerenciamento de pagamento com um resultado de erro +   } +} +``` +```java +final PaymentFlow paymentFlow = MPManager.INSTANCE.getPaymentFlow(); + +final Uri resultUri = getIntent().getData(); +final PaymentResponse response = paymentFlow.parseResponse(resultUri); + +if (!response.getPaymentReference().isEmpty()) { + // Gerenciamento de pagamento com um resultado de sucesso +} else { + // Gerenciamento de pagamento com um resultado de erro +} +``` +]]] + +|Campo|Descrição| +|---|---| +|**response (Uri)**| A resposta recebida da [SmartPOS](/developers/pt/docs/mp-point/landing). Para encontrá-la, use `intent.data` da _Activity_ encarregada de abrir o _deeplink_ configurado dentro da função `buildCallbackUri`.| +|**PaymentResponse**| Objeto que contém detalhes da transação. Se a resposta é nula, é devolvido um objeto `PaymentResponse` com um `paymentStatusError`.| +|**paymentMethod**| Meio de pagamento usado para fazer a transação. Exemplos: crédito, débito, código QR, link de pagamento etc. | +|**paymentReference**| Número identificador único da transação.| +|**paymentCreationDate**| Data de criação da transação.| +|**paymentAmount**| Valor pago.| +|**paymentSnDevice**| Número de série da maquininha em que a transação foi feita.| +|**paymentBrandName**| Nome do usuário registrado na maquininha.| +|**aymentInstallments**| Número de parcelas que a pessoa selecionou ao fazer o pagamento.| +|**paymentLastFourDigits**| Últimos quatro dígitos do cartão usado no pagamento.| +|**paymentStatusError**| Campo para registrar problemas e erros da transação.| + +> WARNING +> +> Atenção +> +> Certifique-se de que a resposta do fluxo de pagamento seja válida e contenha a informação necessária. \ No newline at end of file diff --git a/images/main-apps/landing2-all.png b/images/main-apps/landing2-all.png new file mode 100644 index 0000000000..a8bc35d6c0 Binary files /dev/null and b/images/main-apps/landing2-all.png differ