1.0.1 • Published 1 year ago

manan-react-native-expo-authorize-net v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

React Native Authorize.net for Expo SDK v49

  • Fetch token by sending card details to AcceptSDK for iOS and Android.

Android

Package is using auto-linking

iOS

Package is using autolinking with Cocoapods

pod install

Request

Required arguments:

LOGIN_ID : "login_id of authorize.net in which the card will be added."
CLIENT_KEY : "client_key of authorize.net in which the card will be added."
CARD_NO : "card no"
EXPIRATION_MONTH : "expiration month of the card."
EXPIRATION_YEAR : "expiration year of the card."
CVV_NO : "cvc no of the card."

Response

DATA_DESCRIPTOR = "card data descriptor"
DATA_VALUE = "card data value"

note: these values will be used to add card on server using Accept.js from authorize.net

Usage

Import

import { NativeModules } from 'react-native';
const { RNAuthorizeNet } = NativeModules;

Implementation

// note: object properties must be exactly like they are shown here
const isProduction = process.env.NODE_ENV === 'production'; // true | false
const cardValues = {
  LOGIN_ID: 'XXXX', // AUTH.NET LOGIN_ID
  CLIENT_KEY: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', // AUTH.NET PUBLIC/CLIENT KEY
  CARD_NO: '4111111111111111',
  CVV_NO: '000',
  EXPIRATION_MONTH: '11',
  EXPIRATION_YEAR: '23',
};

/**
 * Authorizes a credit card transaction using Authorize.Net AcceptJS Native Module
 *
 * @param {Object} cardValues - An object containing card info and auth.net credentials.
 * @param {boolean} isProduction - A flag indicating whether the production environment should be used.
 * @returns {Promise} A promise that resolves with the payment token or rejects with an error
 */

RNAuthorizeNet.getTokenWithRequestForCard(cardValues, isProduction)
  .then(response => {
    console.log(response);
  })
  .catch((error: any) => {
    if (Platform.OS === 'ios') {
      const { code, message } = error;
      const alertMsg: string = `${message}\n\nError Code: ${code}`;
      Alert.alert('Error', alertMsg, [{ text: 'OK' }], {
        cancelable: false,
      });
    } else if (Platform.OS === 'android') {
      const { userInfo } = error;
      const { ERROR_TEXT, ERROR_CODE } = userInfo;
      const alertMsg: string = `${ERROR_TEXT}\n\nError Code: ${ERROR_CODE}`;
      Alert.alert('Error', alertMsg, [{ text: 'OK' }], {
        cancelable: false,
      });
    }
  });

Note: The error handling is different on each platform

The above implementation worked for me on both platforms. I hope this example code saves someone the countless hours it took me to promisify Peter's original code and get error handling working as expected.

expo-build-properties

Please note, the Android module includes some code that requires minSdkVersion 21, but Expo allows us to configure this in app.json via expo-build-properties.

{
  "expo": {
    "plugins": [
      "expo-router",
      [
        "expo-build-properties",
        {
          "android": {
            "minSdkVersion": 26
          },
          "ios": {}
        }
      ]
    ]
  }
}
abort-controlleracceptsacornagent-baseaggregate-erroranseransi-escapesansi-fragmentsansi-regexansi-stylesany-promiseanymatchappdirsjsapplication-config-pathargargparsearray-buffer-byte-lengtharray-unionarraybuffer.prototype.sliceasapast-typesastral-regexasync-limiterasynckitat-least-nodeavailable-typed-arraysbabel-corebabel-plugin-polyfill-corejs2babel-plugin-polyfill-corejs3babel-plugin-polyfill-regeneratorbabel-plugin-react-native-webbabel-plugin-syntax-trailing-function-commasbabel-plugin-transform-flow-enumsbabel-preset-expobabel-preset-fbjsbalanced-matchbase64-jsbetter-opnbig-integerblblueimp-md5bplist-creatorbplist-parserbrace-expansionbracesbrowserslistbserbufferbuffer-allocbuffer-alloc-unsafebuffer-fillbuffer-frombuiltinsbytescacachecall-bindcaller-callsitecaller-pathcallsitescamelcasecaniuse-litechalkcharencchownrchrome-launcherchromium-edge-launcherci-infoclean-stackcli-cursorcli-spinnerscliuicloneclone-deepcolor-convertcolor-namecolorettecombined-streamcommand-existscommandercommondircomponent-typecompressiblecompressionconcat-mapconnectconvert-source-mapcore-js-compatcore-util-iscosmiconfigcross-fetchcross-spawncryptcrypto-random-stringdag-mapdata-view-bufferdata-view-byte-lengthdata-view-byte-offsetdayjsdebugdecamelizedeep-extenddeepmergedefault-gatewaydefaultsdefine-data-propertydefine-lazy-propdefine-propertiesdeldelayed-streamdenodeifydepddeprecated-react-native-prop-typesdestroydetect-libcdir-globdotenvdotenv-expandee-firstelectron-to-chromiumemoji-regexencodeurlend-of-streamenv-editorenvinfoeolerror-exerror-stack-parsererrorhandleres-abstractes-define-propertyes-errorses-object-atomses-set-tostringtages-to-primitiveescaladeescape-htmlescape-string-regexpesprimaesutilsetagevent-target-shimexec-asyncexecaexpoexpo-assetexpo-constantsexpo-file-systemexpo-fontexpo-keep-awakeexpo-modules-autolinkingexpo-modules-corefast-globfast-xml-parserfastqfb-watchmanfbemitterfbjsfbjs-css-varsfetch-retryfill-rangefinalhandlerfind-cache-dirfind-upfind-yarn-workspace-rootflow-enums-runtimeflow-parserfontfaceobserverfor-eachform-datafreeport-asyncfreshfs-extrafs-minipassfs.realpathfunction-bindfunction.prototype.namefunctions-have-namesgensyncget-caller-fileget-intrinsicget-portget-streamget-symbol-descriptiongetenvglobglob-parentglobalsglobalthisglobbygopdgraceful-fsgraphqlgraphql-taghas-bigintshas-flaghas-property-descriptorshas-protohas-symbolshas-tostringtaghasownhermes-estreehermes-parserhermes-profile-transformerhosted-git-infohttp-errorshttps-proxy-agenthuman-signalsieee754ignoreimage-sizeimport-freshimurmurhashindent-stringinfer-ownerinflightinheritsiniinternal-ipinternal-slotinvariantip-regexipaddr.jsis-array-bufferis-arrayishis-bigintis-boolean-objectis-bufferis-callableis-core-moduleis-data-viewis-date-objectis-directoryis-dockeris-extglobis-fullwidth-code-pointis-globis-interactiveis-invalid-pathis-negative-zerois-numberis-number-objectis-path-cwdis-path-insideis-plain-objectis-regexis-shared-array-bufferis-streamis-stringis-symbolis-typed-arrayis-unicode-supportedis-valid-pathis-weakrefis-wslisarrayisexeisobjectjest-environment-nodejest-get-typejest-message-utiljest-mockjest-utiljest-validatejest-workerjimp-compactjoijoin-componentjs-tokensjs-yamljsc-androidjsc-safe-urljscodeshiftjsescjson-parse-better-errorsjson-schema-deref-syncjson5jsonfilekind-ofkleurlevenlighthouse-loggerlightningcsslightningcss-darwin-arm64lines-and-columnslocate-pathlodashlodash.debouncelodash.throttlelog-symbolslogkittyloose-envifylru-cachemake-dirmakeerrormarkymd5md5-filemd5hexmemoize-onememory-cachemerge-streammerge2metrometro-babel-transformermetro-cachemetro-cache-keymetro-configmetro-coremetro-file-mapmetro-minify-tersermetro-resolvermetro-runtimemetro-source-mapmetro-symbolicatemetro-transform-pluginsmetro-transform-workermicromatchmimemime-dbmime-typesmimic-fnminimatchminimistminipassminipass-collectminipass-flushminipass-pipelineminizlibmkdirpmsmvmznanoidncpnegotiatorneo-asyncnested-error-stacksnice-trynocachenode-abort-controllernode-dirnode-fetchnode-forgenode-int64node-releasesnode-stream-zipnormalize-pathnpm-package-argnpm-run-pathnullthrowsob1object-assignobject-inspectobject-keysobject.assignon-finishedon-headersonceonetimeopenoraos-homediros-tmpdirosenvp-finallyp-limitp-locatep-mapp-tryparse-jsonparse-pngparseurlpassword-promptpath-existspath-is-absolutepath-keypath-parsepath-typepicocolorspicomatchpifypiratespkg-dirplistpngjspossible-typed-array-namespostcsspretty-bytespretty-formatprocess-nextick-argsprogresspromisepromise-inflightpromptsprop-typespumppunycodeqrcode-terminalqueuequeue-microtaskrange-parserrcreactreact-devtools-corereact-isreact-nativereact-refreshreact-shallow-rendererreadable-streamreadlinerecastregenerateregenerate-unicode-propertiesregenerator-runtimeregenerator-transformregexp.prototype.flagsregexpu-coreregjsparserremove-trailing-slashrequire-directoryrequire-from-stringrequire-main-filenamerequiregresolveresolve-fromresolve.exportsrestore-cursorreusifyrimrafrun-parallelsafe-array-concatsafe-buffersafe-json-stringifysafe-regex-testsaxschedulersemversendserialize-errorserve-staticset-blockingset-function-lengthset-function-namesetimmediatesetprototypeofshallow-cloneshebang-commandshebang-regexshell-quoteside-channelsignal-exitsimple-plistsisteransislashslice-ansislugifysource-mapsource-map-jssource-map-supportsplitsprintf-jsssristack-utilsstackframestacktrace-parserstatusesstream-buffersstring-widthstring.prototype.trimstring.prototype.trimendstring.prototype.trimstartstring_decoderstrip-ansistrip-eofstrip-final-newlinestrip-json-commentsstrnumstructured-headerssucrasesudo-promptsupports-colorsupports-hyperlinkssupports-preserve-symlinks-flagtartemptemp-dirtempyterminal-linktersertext-tablethenifythenify-allthroatthroughthrough2tmptmplto-fast-propertiesto-regex-rangetoidentifiertr46traversets-interface-checkertslibtype-detecttype-festtyped-array-buffertyped-array-byte-lengthtyped-array-byte-offsettyped-array-lengthtypedarray.prototype.sliceua-parser-jsunbox-primitiveundici-typesunicode-canonical-property-names-ecmascriptunicode-match-property-ecmascriptunicode-match-property-value-ecmascriptunicode-property-aliases-ecmascriptunique-filenameunique-slugunique-stringuniversalifyunpipeupdate-browserslist-dburl-joinutil-deprecateutils-mergeuuidvalid-urlvalidate-npm-package-namevaryvlqwalkerwcwidthwebidl-conversionswhatwg-fetchwhatwg-urlwhatwg-url-without-unicodewhichwhich-boxed-primitivewhich-modulewhich-typed-arraywonkawrap-ansiwrappywrite-file-atomicwsxcodexml2jsxmlbuilderxtendy18nyallistyamlyargsyargs-parseryocto-queue
1.0.1

1 year ago