Giter VIP home page Giter VIP logo

react-native-adyen-dropin's Introduction

[DEPRECATED] Use Adyen's official React Native implementation instead! https://github.com/Adyen/adyen-react-native

react-native-adyen-dropin

React Native bridge for Adyen drop-in

๐Ÿ Adyen iOS SDK v4.8.0 ๐Ÿค– Adyen Android SDK v4.7.1

Installation

yarn add @ancon/react-native-adyen-dropin

Android

Add Kotlin v1.5 as a dependency in android/build.gradle:

buildscript {
  ext {
    buildToolsVersion           = "30.0.0"
    minSdkVersion               = 21
    compileSdkVersion           = 30
    targetSdkVersion            = 30
+   kotlinVersion               = "1.5.31"
  }

Add Kotlin as a dependency in android/app/build.gradle

dependencies {
  implementation fileTree(dir: "libs", include: ["*.jar"])
  //noinspection GradleDynamicVersion
  implementation("com.facebook.react:react-native:+")

+ implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion")
}

Replace name in /android/app/src/main/res/values/styles.xml:

<resources>
  <!-- Base application theme. -->
-  <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
+  <style name="CustomAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
      <!-- Customize your theme here. -->
      <item name="android:textColor">#000000</item>
  </style>
</resources>

Also update theme in /android/app/src/main/AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.reactnativeadyendropin">

    <application
-      android:theme="@style/AppTheme">
+      android:theme="@style/CustomAppTheme">

Add the following into onCreate() in MainApplication.java:

+import static com.reactnativeadyendropin.AdyenDropIn.setup;
// ...
@Override
public void onCreate() {
  super.onCreate();
  SoLoader.init(this, /* native exopackage */ false);
  initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
+ setup(this);
}

iOS

Install pods:

cd ios && pod install

Add this to your project's swift file to be able to handle redirect actions (or create one and generate a bridging header file):

import Foundation
import Adyen

@objc class AdyenObjectiveCBridge: NSObject {

  @objc(applicationDidOpenURL:)
  static func applicationDidOpen(_ url: URL) -> Bool {
     let adyenHandled = RedirectComponent.applicationDidOpen(from : url)
     return adyenHandled
  }
}

Usage

See example at example/src/App.tsx

import AdyenDropIn, {
  isCancelledError,
  isSuccessResult,
  PaymentResult,
} from '@ancon/react-native-adyen-dropin';

// ...

async function handlePress() {
  if (!loading) {
    setLoading(true);

    const adyenDropIn = AdyenDropIn.setModuleConfig({
      // Required API base URL
      baseUrl: 'http://192.168.1.74:3000/api/',
      // Optional to view more native logs
      debug: true,
      // Optional custom headers
      headers: {
        Authorization: 'Bearer 123',
      },
      // Optional custom endpoints
      endpoints: {
        makePayment: '/payments',
        makeDetailsCall: '/details',
      },
    }).setDropInConfig({
      // Required
      clientKey: config.clientKey,
      // Required
      environment: config.environment,
      // Required
      countryCode: config.countryCode,
      // Required
      amount: { value: 100, currencyCode: 'SEK' },
      // Optional
      applePay: {
        label: 'Example Company',
        amount: { value: 1, currencyCode: 'SEK' },
        configuration: {
          merchantId: config.applePay?.configuration?.merchantId,
        },
      },
      // Optional
      showRemovePaymentMethodButton: config.showRemovePaymentMethodButton,
      // Optional, required for recurring payments/saved payment method
      shopperReference: config.shopperReference,
    });

    // Fetch payment methods
    const response = await services.getPaymentMethods();

    // Start the drop-in flow
    adyenDropIn
      .start(response)
      .then((res: PaymentResult) => {
        if (isSuccessResult(res)) {
          Alert.alert('Success', `Payment success: ${res.resultCode}`);
        } else {
          Alert.alert('Refused', `Payment refused: ${res.refusalReason}`);
        }
      })
      .catch((err: Error) => {
        if (isCancelledError(err)) {
          console.log('Cancelled');
        } else {
          Alert.alert('Error', `Payment error: ${err.message}`);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }
}

// ...

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

License

MIT

react-native-adyen-dropin's People

Contributors

jesperjohansson avatar mortend avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-native-adyen-dropin's Issues

Android: Invariant Violation: requireNativeComponent: "AdyenDropIn" was not found in the UIManager.

Hello @jesperjohansson @mortend I am getting this specific error for Android. Below are my logs:

adb logcat

10-14 02:53:24.329 12079 12119 D EGL_emulation: app_time_stats: avg=231.98ms min=2.97ms max=8388.39ms count=37
10-14 02:53:26.035 12079 12119 D EGL_emulation: app_time_stats: avg=23.22ms min=3.17ms max=812.85ms count=46
10-14 02:53:26.880 12079 12079 I ReactNative: [GESTURE HANDLER] Tearing down gesture handler registered for root view com.facebook.react.ReactRootView{4dd532c V.E...... ......ID 0,0-1080,2082 #1}
10-14 02:53:26.888 701 924 D EGL_emulation: app_time_stats: avg=2686.11ms min=14.25ms max=26363.93ms count=10
10-14 02:53:27.005 524 682 D CompatibilityChangeReporter: Compat change id reported: 168419799; UID 10147; state: DISABLED
10-14 02:53:27.012 329 382 D goldfish-address-space: claimShared: Ask to claim region [0x1f1a44000 0x1f23ac000]
10-14 02:53:27.014 329 382 D goldfish-address-space: claimShared: Ask to claim region [0x1f2c0c000 0x1f3574000]
10-14 02:53:27.014 329 382 D goldfish-address-space: claimShared: Ask to claim region [0x1f3574000 0x1f3edc000]
10-14 02:53:27.042 1251 1251 I GoogleInputMethodService: GoogleInputMethodService.onFinishInput():3420
10-14 02:53:27.042 1251 1251 I GoogleInputMethodService: GoogleInputMethodService.onStartInput():2002
10-14 02:53:27.042 1251 1251 I DeviceUnlockedTag: DeviceUnlockedTag.notifyDeviceLockStatusChanged():31 Notify device unlocked.
10-14 02:53:27.089 12079 12079 E unknown:FabricViewStateManager: setState called without a StateWrapper
10-14 02:53:28.684 12079 12119 D EGL_emulation: app_time_stats: avg=73.30ms min=2.68ms max=1245.14ms count=19

Do you guys have any idea about this issue?
image

Missing Implementation

Hi Buddy,

Thanks a lot for this work when Adyen's official Lib is not available, really appreciate it.

When I was integrating your lib with my project, I found that some implementation is missing.

Below is the list of missing implementation:

  1. reference : You forgot to add reference, which is mandatory for Adyen payments api.
  2. paywithgoogle : You have not implemented Google Pay.

For now, I was able to found above two points. Will share more if found any.

I have fixed these issues in my local system, let me know if you want me to create a PR.

Getting blank "Payment Methods" modal.

Hello @jesperjohansson , While I am initiating the Adyen Drop In module I am getting below blank modal UI:

image

In Xcode logger I am getting last log as "Called start" message. Can you please help me out with this? I am not able to proceed further.

Http 403 error

Hello @jesperjohansson @mortend

After selecting the "Credit Card" payment method, I am filling the card details and when I press on "Pay" button it got failed and stopped the process with just this message: "Http 403 error". I have debug the code and it goes in rejectCallback:

AdyenDropInModule.start(
          cleanedPaymentMethodsResponse,
          resolveCallback,
          rejectCallback
        );

My implementation:

import AdyenDropIn, { isCancelledError, isSuccessResult, PaymentResult, } from '@ancon/react-native-adyen-dropin';

 const adyenDropIn = AdyenDropIn.setModuleConfig({
        // Required
        baseUrl: "API_BASE_URL",
        // Optional
        debug: true,
        // Optional
        // headers: {
        //   Authorization: 'Bearer 123',
        // },
        // // Optional
        endpoints: {
          makePayment: '/makePayment',
          makeDetailsCall: '/details',
          disableStoredPaymentMethod: '/disable',
        },
      }).setDropInConfig({
        // Required
        clientKey: ADYEN_CLIENT_KEY,
        // Required
        environment: ADYEN_ENV,
        // Required
        countryCode: COUNTRY_CODE,
        // Required
        amount: {
          value: payableAmount,
          currencyCode:
            _.get(paymentDetails, "currency", DEFAULT_CURRENCY_CODE) ||
            DEFAULT_CURRENCY_CODE,
        },
        // Optional
        // applePay: {
        //   label: 'Example Company',
        //   amount: { value: 1, currencyCode: 'SEK' },
        //   configuration: {
        //     merchantId: config.applePay?.configuration?.merchantId,
        //   },
        // },
        // // Optional
        // showRemovePaymentMethodButton: config.showRemovePaymentMethodButton,
        // // Optional, required for recurring payments/saved payment method
        // shopperReference: config.shopperReference,
      });
      
     const tempMethods = await getPaymentMethods();

      adyenDropIn
        .start(tempMethods)
        .then((res: PaymentResult) => {
          console.log('result:');
          console.log(res);
          if (isSuccessResult(res)) {
            console.log('Success', `Payment success: ${res.resultCode}`);
          } else {
            console.log('Refused', `Payment refused: ${res.refusalReason}`);
          }
        })
        .catch((err: Error) => {
          if (isCancelledError(err)) {
            console.log('Cancelled');
          } else {
            console.log('Error', `Payment error: ${err.message}`, JSON.stringify(err));
            console.error(err);
          }
        })
        .finally(() => {
          setIsLoading(false);
        });

Can you please help me with this issue?

Apple Pay Amount 'null'

I'm trying to add ApplePay to my proof of concept, having issues with their not being an amount passed through on the make-payment request. I've scoured through the files to confirm that the amount is being set in config as requested but still it passes through as null.

Confirmed that the standard card integration is still passing through the amount and payments go through fine. It's just apple pay being a pain. Do you have any ideas?

Config:

         const adyenDropIn = AdyenDropIn.setModuleConfig({
            baseUrl: baseUrl,
            debug: true,
            endpoints: {
              makePayment: '/make-payment',
              makeDetailsCall: '/details',
            },
          }).setDropInConfig({
            clientKey: res.data.clientKey,
            environment: 'test', // [test/live]
            countryCode: 'GB',
            amount: {
              value: +data.amount * 100,
              currencyCode: 'GBP',
            },
            applePay: {
              label: 'Purchase',
              amount: {
                value: +data.amount,
                currencyCode: 'GBP',
              },
              configuration: {
                merchantId:
                  '******', // this is correct in app.
              },
            },
          });

Generated request:

POST /api/make-payment?clientKey=test_7LDREFIMKFESDBR5QZCVA37JZUJEYPRW 500 87.781 ms - 689
body {
  amount: null,
  shopperLocale: 'en_US',
  storePaymentMethod: false,
  channel: 'iOS',
  shopperReference: null,
  additionalData: { executeThreeD: true, allow3DS2: true },
  returnUrl: null,
  countryCode: 'GB',
  paymentMethod: { applePayCardNetwork: 'Visa', applePayToken: '', type: 'applepay' }
}
HttpClientException {
  statusCode: 422,
  name: 'HttpClientException',
  message: "HTTP Exception: 422. : Required object 'amount' is not provided.",
  responseHeaders: {
    traceparent: '00-a6b8c97015b24b579d269a54cb7a067a-c40c6d58bf0e1764-01',
    'set-cookie': [
      'JSESSIONID=6D2DC38A12EFE1BABFA259BD68979F99.test3e; Path=/checkout; Secure; HttpOnly'
    ],
    pspreference: 'W9QTRXSXZHHKGK82',
    'content-type': 'application/json;charset=UTF-8',
    'transfer-encoding': 'chunked',
    date: 'Tue, 09 Aug 2022 06:08:48 GMT',
    connection: 'close'
  },
  responseBody: `{"status":422,"errorCode":"100","message":"Required object 'amount' is not provided.","errorType":"validation","pspReference":"W9QTRXSXZHHKGK82"}`,
  errorCode: '100'
}

Response:

[Error: HTTP Exception: 422. : Required object 'amount' is not provided.]

Android App crash on "Card" option selection

Hello @jesperjohansson

Thank you so much for the much awaited library. I am trying to use your library in one of my project. I have performed steps as you mentioned on README file. But when I initiate Adyen Payment on Android it shows small modal with option for "Card" payment. On tapping of that menu item, my app is crashing and it closes again and again.

Can you please help me with this?

Not able to view Adyen Drop-In view

@jesperjohansson First of all, thanx a lot for this library.

I have configured the library in my project as per the instruction and example, but I am not able to see Adyen Drop-In screen:

Getting below log messages:

Initializing drop-in
Open was called
Skipping initialization

After this nothing happens. Can you please help me with this issue?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.