0.1.5 • Published 8 months ago

react-native-superapis-transbank-pos v0.1.5

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

Ejemplo de Uso para react-native-superapis-transbank-pos

Este es un ejemplo básico de cómo usar el módulo react-native-superapis-transbank-pos en una aplicación de React Native para conectar con dispositivos Transbank a través de una conexión USB RS232 en Android.

Instalación

Asegúrate de haber instalado y enlazado el módulo siguiendo los pasos en la documentación principal del paquete.

Descargar el Ejemplo

Para descargar y ejecutar el ejemplo, sigue estos pasos:

  1. Clona el repositorio o crea un nuevo proyecto de React Native:

    npx react-native init TransbankExample
    cd TransbankExample
  2. Instala el módulo react-native-superapis-transbank-pos:

    npm install react-native-superapis-transbank-pos
    # o con Yarn
    yarn add react-native-superapis-transbank-pos
  3. Configura el enlace (si es necesario) y sigue los pasos adicionales de la documentación del paquete para Android.

  4. Crea el archivo App.js en la raíz del proyecto con el siguiente código de ejemplo:

Código de Ejemplo

import React, { useEffect, useState } from 'react';
import { StyleSheet, View, Text, TouchableHighlight } from 'react-native';
import { 
  status, 
  polling, 
  loadKeys, 
  initTransbank, 
  newTransaction, 
  lastTransaction, 
  closeTotem, 
  transbankEmitter 
} from 'react-native-superapis-transbank-pos';

export default function App() {
  const [result, setResult] = useState(null);

  // Configura el listener para recibir eventos de datos
  useEffect(() => {
    const subscription = transbankEmitter.addListener('onDataReceived', (event) => {
      setResult(event.data); // Actualiza el estado con los datos recibidos
    });

    // Limpia el listener al desmontar el componente
    return () => subscription.remove();
  }, []);

  const getStatus = async () => {
    const response = await status();
    setResult(response);
  };

  const getPolling = async () => {
    const response = await polling();
    setResult(response);
  };

  const getLastTransaction = async () => {
    const response = await lastTransaction();
    setResult(response);
  };

  const getLoadKeys = async () => {
    const response = await loadKeys();
    setResult(response);
  };

  const getInit = async () => {
    const response = await initTransbank();
    setResult(response);
  };

  const sendPayments = async (value, ticket) => {
    const response = await newTransaction(value, ticket);
    setResult(response);
  };

  const getClose = async () => {
    const response = await closeTotem();
    setResult(response);
  };

  return (
    <View style={styles.container}>
      <Text>Conectar: {result}</Text>

      <TouchableHighlight onPress={getStatus}>
        <View style={styles.box}>
          <Text>Status</Text>
        </View>
      </TouchableHighlight>

      <TouchableHighlight onPress={getPolling}>
        <View style={styles.box}>
          <Text>Polling</Text>
        </View>
      </TouchableHighlight>

      <TouchableHighlight onPress={getLastTransaction}>
        <View style={styles.box}>
          <Text>Get Last Transaction</Text>
        </View>
      </TouchableHighlight>

      <TouchableHighlight onPress={getLoadKeys}>
        <View style={styles.box}>
          <Text>Load Keys</Text>
        </View>
      </TouchableHighlight>

      <TouchableHighlight onPress={getInit}>
        <View style={styles.box}>
          <Text>Init Transbank</Text>
        </View>
      </TouchableHighlight>

      <TouchableHighlight onPress={() => sendPayments('100000', '12345678901234567890123456789012')}>
        <View style={styles.box}>
          <Text>Venta</Text>
        </View>
      </TouchableHighlight>

      <TouchableHighlight onPress={getClose}>
        <View style={styles.box}>
          <Text>Close Totem</Text>
        </View>
      </TouchableHighlight>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  box: {
    width: 100,
    height: 60,
    backgroundColor: '#DDDDDD',
    alignItems: 'center',
    justifyContent: 'center',
    marginVertical: 20,
  },
});

Descripción de las Funcionalidades

Cada botón en el ejemplo ejecuta una función diferente:

  • Status: Obtiene el estado del dispositivo.
  • Polling: Realiza una verificación de polling en el dispositivo.
  • Get Last Transaction: Recupera la última transacción.
  • Load Keys: Carga las llaves en el dispositivo Transbank.
  • Init Transbank: Inicializa la conexión con Transbank.
  • Venta: Envía un comando de transacción con un valor y un ticket.
  • Close Totem: Cierra la conexión con el dispositivo.

El listener onDataReceived actualiza automáticamente el estado result con los datos recibidos del dispositivo USB, y se muestra en el componente Text.

Estilos

Los estilos en el ejemplo proporcionan un diseño simple para los botones y el contenedor principal.


Este ejemplo de uso te permite conectarte a un dispositivo Transbank y realizar operaciones básicas directamente desde una aplicación de React Native en Android. Asegúrate de probar en un dispositivo físico, ya que el emulador no soporta conexiones USB RS232.

JSONStreamabbrevabort-controlleracceptsacornacorn-jsxacorn-walkadd-streamagent-baseaggregate-errorajvanseransi-alignansi-escapesansi-fragmentsansi-regexansi-stylesanymatchappdirsjsargargparsearray-buffer-byte-lengtharray-ifyarray-includesarray-unionarray.prototype.findlastarray.prototype.flatarray.prototype.flatmaparray.prototype.maparray.prototype.tosortedarraybuffer.prototype.slicearrifyasapast-typesastral-regexasync-limiterasync-retryavailable-typed-arraysbabel-corebabel-jestbabel-plugin-istanbulbabel-plugin-jest-hoistbabel-plugin-module-resolverbabel-plugin-polyfill-corejs2babel-plugin-polyfill-corejs3babel-plugin-polyfill-regeneratorbabel-plugin-syntax-hermes-parserbabel-plugin-transform-flow-enumsbabel-preset-current-node-syntaxbabel-preset-jestbalanced-matchbase64-jsbasic-ftpbefore-after-hookbig-integerblboxenbplist-parserbrace-expansionbracesbrowserslistbserbufferbuffer-frombundle-namebytescacachecacheable-lookupcacheable-requestcall-bindcaller-callsitecaller-pathcallsitescamelcasecamelcase-keyscaniuse-litechalkchar-regexchardetchownrchrome-launcherchromium-edge-launcherci-infocjs-module-lexerclean-stackcli-boxescli-cursorcli-spinnerscli-widthcliuicloneclone-deepcocollect-v8-coveragecolor-convertcolor-namecolorettecommand-existscommandercommondircompare-funccompressiblecompressionconcat-mapconcat-streamconfig-chainconfigstoreconnectconventional-changelogconventional-changelog-angularconventional-changelog-atomconventional-changelog-codemirrorconventional-changelog-conventionalcommitsconventional-changelog-coreconventional-changelog-emberconventional-changelog-eslintconventional-changelog-expressconventional-changelog-jqueryconventional-changelog-jshintconventional-changelog-preset-loaderconventional-changelog-writerconventional-commits-filterconventional-commits-parserconventional-recommended-bumpconvert-source-mapcore-js-compatcore-util-iscosmiconfigcosmiconfig-typescript-loadercreate-jestcreate-requirecross-spawncrypto-random-stringcsstypedargsdata-uri-to-bufferdata-view-bufferdata-view-byte-lengthdata-view-byte-offsetdateformatdayjsdebugdecamelizedecamelize-keysdecompress-responsededentdeep-extenddeep-isdeepmergedefault-browserdefault-browser-iddefaultsdefer-to-connectdefine-data-propertydefine-lazy-propdefine-propertiesdegeneratordeldenodeifydepddeprecationdestroydetect-newlinediffdiff-sequencesdir-globdoctrinedot-propeastasianwidthee-firstelectron-to-chromiumemitteryemoji-regexencodeurlencodingend-of-streamenv-pathsenvinfoerr-codeerror-exerror-stack-parsererrorhandleres-abstractes-array-method-boxes-properlyes-define-propertyes-errorses-get-iteratores-iterator-helperses-object-atomses-set-tostringtages-shim-unscopableses-to-primitiveescaladeescape-goatescape-htmlescape-string-regexpescodegeneslint-plugin-eslint-commentseslint-plugin-ft-floweslint-plugin-jesteslint-plugin-reacteslint-plugin-react-hookseslint-plugin-react-nativeeslint-plugin-react-native-globalseslint-scopeeslint-visitor-keysespreeesprimaesqueryesrecurseestraverseesutilsetagevent-target-shimexecaexitexpectexponential-backoffexternal-editorfast-deep-equalfast-difffast-globfast-json-stable-stringifyfast-levenshteinfast-urifast-xml-parserfastqfb-watchmanfetch-blobfiguresfile-entry-cachefill-rangefinalhandlerfind-babel-configfind-cache-dirfind-upflat-cacheflattedflow-enums-runtimeflow-parserfor-eachforeground-childform-data-encoderformdata-polyfillfreshfs-extrafs-minipassfs.realpathfseventsfunction-bindfunction.prototype.namefunctions-have-namesgensyncget-caller-fileget-intrinsicget-package-typeget-pkg-repoget-streamget-symbol-descriptionget-urigit-raw-commitsgit-remote-origin-urlgit-semver-tagsgit-upgit-url-parsegitconfiglocalglobglob-parentglobal-dirsglobalsglobalthisglobbygopdgotgraceful-fsgraphemerhandlebarshard-rejectionhas-bigintshas-flaghas-property-descriptorshas-protohas-symbolshas-tostringtaghas-yarnhasownhermes-estreehermes-parserhosted-git-infohtml-escaperhttp-cache-semanticshttp-errorshttp-proxy-agenthttp2-wrapperhttps-proxy-agenthuman-signalsiconv-liteieee754ignoreimage-sizeimport-freshimport-lazyimport-localimurmurhashindent-stringinflightinheritsiniinquirerinternal-slotinterpretinvariantipip-addressis-absoluteis-argumentsis-array-bufferis-arrayishis-async-functionis-bigintis-boolean-objectis-callableis-ciis-core-moduleis-data-viewis-date-objectis-directoryis-dockeris-extglobis-finalizationregistryis-fullwidth-code-pointis-generator-fnis-generator-functionis-git-dirtyis-git-repositoryis-globis-inside-containeris-installed-globallyis-interactiveis-lambdais-mapis-negative-zerois-npmis-numberis-number-objectis-objis-path-cwdis-path-insideis-plain-objis-plain-objectis-regexis-relativeis-setis-shared-array-bufferis-sshis-streamis-stringis-symbolis-text-pathis-typed-arrayis-typedarrayis-unc-pathis-unicode-supportedis-weakmapis-weakrefis-weaksetis-windowsis-wslis-yarn-globalisarrayisexeisobjectissue-parseristanbul-lib-coverageistanbul-lib-instrumentistanbul-lib-reportistanbul-lib-source-mapsistanbul-reportsiterate-iteratoriterate-valueiterator.prototypejackspeakjest-changed-filesjest-circusjest-clijest-configjest-diffjest-docblockjest-eachjest-environment-nodejest-get-typejest-haste-mapjest-leak-detectorjest-matcher-utilsjest-message-utiljest-mockjest-pnp-resolverjest-regex-utiljest-resolvejest-resolve-dependenciesjest-runnerjest-runtimejest-snapshotjest-utiljest-validatejest-watcherjest-workerjoijs-tokensjs-yamljsbnjsc-androidjsc-safe-urljscodeshiftjsescjson-bufferjson-parse-better-errorsjson-parse-even-better-errorsjson-schema-traversejson-stable-stringify-without-jsonifyjson-stringify-safejson5jsonfilejsonparsejsx-ast-utilskeyvkind-ofkleurlatest-versionlevenlevnlighthouse-loggerlines-and-columnsload-json-filelocate-pathlodashlodash.camelcaselodash.capitalizelodash.debouncelodash.escaperegexplodash.isfunctionlodash.ismatchlodash.isplainobjectlodash.isstringlodash.kebabcaselodash.mergelodash.mergewithlodash.snakecaselodash.startcaselodash.throttlelodash.uniqlodash.uniqbylodash.upperfirstlog-symbolslogkittyloose-envifylowercase-keyslru-cachemacos-releasemake-dirmake-errormake-fetch-happenmakeerrormap-objmarkymemoize-onemeowmerge-streammerge2metrometro-babel-transformermetro-cachemetro-cache-keymetro-configmetro-coremetro-file-mapmetro-minify-tersermetro-resolvermetro-runtimemetro-source-mapmetro-symbolicatemetro-transform-pluginsmetro-transform-workermicromatchmimemime-dbmime-typesmimic-fnmimic-responsemin-indentminimatchminimistminimist-optionsminipassminipass-collectminipass-fetchminipass-flushminipass-pipelineminipass-sizedminizlibmkdirpmodify-valuesmsmute-streamnatural-comparenatural-compare-litenegotiatorneo-asyncnetmasknew-github-release-urlnocachenode-abort-controllernode-dirnode-domexceptionnode-fetchnode-forgenode-gypnode-int64node-releasesnode-stream-zipnoptnormalize-package-datanormalize-pathnormalize-urlnpm-run-pathnullthrowsob1object-assignobject-inspectobject-keysobject.assignobject.entriesobject.fromentriesobject.valueson-finishedon-headersonceonetimeopenoptionatororaos-nameos-tmpdirp-cancelablep-limitp-locatep-mapp-trypac-proxy-agentpac-resolverpackage-jsonpackage-json-from-distparent-moduleparse-jsonparse-pathparse-urlparseurlpath-existspath-is-absolutepath-keypath-parsepath-scurrypath-typepicocolorspicomatchpifypiratespkg-dirpkg-uppossible-typed-array-namesprelude-lsprettier-linter-helperspretty-formatproc-logprocess-nextick-argspromisepromise-retrypromise.allsettledpromptsprop-typesproto-listprotocolsproxy-agentproxy-from-envpumppunycodepupapure-randqqueuequeue-microtaskquick-lrurange-parserrcreact-devtools-corereact-isreact-refreshread-pkgread-pkg-upreadable-streamreadlinerecastrechoirredentreflect.getprototypeofregenerateregenerate-unicode-propertiesregenerator-runtimeregenerator-transformregexp.prototype.flagsregexpu-coreregistry-auth-tokenregistry-urlregjsgenregjsparserrequire-directoryrequire-from-stringrequire-main-filenamereselectresolveresolve-alpnresolve-cwdresolve-fromresolve-globalresolve.exportsresponselikerestore-cursorretryreusifyrimrafrun-applescriptrun-asyncrun-parallelrxjssafe-array-concatsafe-buffersafe-regex-testsafer-bufferschedulerselfsignedsemversemver-diffsendserialize-errorserve-staticset-blockingset-function-lengthset-function-namesetprototypeofshallow-cloneshebang-commandshebang-regexshell-quoteshelljsside-channelsignal-exitsisteransislashslice-ansismart-buffersockssocks-proxy-agentsource-mapsource-map-supportspdx-correctspdx-exceptionsspdx-expression-parsespdx-license-idssplitsplit2sprintf-jsssristack-utilsstackframestacktrace-parserstatusesstdin-discarderstop-iteration-iteratorstring-lengthstring-natural-comparestring-widthstring-width-cjsstring.prototype.matchallstring.prototype.repeatstring.prototype.trimstring.prototype.trimendstring.prototype.trimstartstring_decoderstrip-ansistrip-ansi-cjsstrip-bomstrip-final-newlinestrip-indentstrip-json-commentsstrnumsudo-promptsupports-colorsupports-preserve-symlinks-flagsynckittartemptersertest-excludetext-extensionstext-tablethroatthroughthrough2titleizetmptmplto-regex-rangetoidentifiertr46trim-newlinests-nodetslibtsutilsturbo-darwin-arm64type-checktype-detecttype-festtyped-array-buffertyped-array-byte-lengthtyped-array-byte-offsettyped-array-lengthtypedarraytypedarray-to-bufferuglify-jsunbox-primitiveunc-path-regexundici-typesunicode-canonical-property-names-ecmascriptunicode-match-property-ecmascriptunicode-match-property-value-ecmascriptunicode-property-aliases-ecmascriptunique-filenameunique-slugunique-stringuniversal-user-agentuniversalifyunpipeuntildifyupdate-browserslist-dbupdate-notifieruri-jsurl-joinutil-deprecateutils-mergev8-compile-cache-libv8-to-istanbulvalidate-npm-package-licensevaryvlqvm2walkerwcwidthweb-streams-polyfillwebidl-conversionswhatwg-fetchwhatwg-urlwhichwhich-boxed-primitivewhich-builtin-typewhich-collectionwhich-modulewhich-typed-arraywidest-linewildcard-matchwindows-releaseword-wrapwordwrapwrap-ansiwrap-ansi-cjswrappywrite-file-atomicwsxdg-basedirxtendy18nyallistyamlyargsyargs-parserynyocto-queue
0.1.5

8 months ago

0.1.4

8 months ago

0.1.3

8 months ago

0.1.2

8 months ago

0.1.1

8 months ago

0.1.0

8 months ago