Skip to main content

Using DyScanView

The DyScanView is a more complicated integration strategy that gives you more control over the user experience in your app, for example by reserving parts of the screen for other Views, or even drawing Views on top of the DyScanView. In exchange, you will be responsible for many things that DyScanActivity normally takes care of for you, such as requesting permissions, providing callbacks, and notifying the View of when certain events occur. We assume in this guide that you have already imported the library into your project.

info

For the default integration methodology, see the Android Integration Guide.

Adding DyScanView to a layout

To incorporate the View into a layout, you should first add a new namespace just below the android namespace to be able to set the attributes in the layout:

xmlns:dyneti="http://schemas.android.com/apk/res-auto"

After this, you can add a DyScanView to the layout. You must use the fully qualified class name in the layout file. The example below shows one attribute set on the View; a complete list of available attributes appears in Customizing the Layout.

<com.dyneti.android.dyscan.DyScanView
android:id="@+id/dyscanview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
dyneti:showResultOverlay="true"
/>
info

We recommend using a RelativeLayout as the parent to the DyScanView. You can then use the layout attributes such as android:layout_aboveand android:layout_below in order to dictate the relationship between the DyScanView and the other Views.

danger

The DyScanView currently does not support being used in landscape activities. All activities that use the DyScanView should set the screenOrientation attribute on the activity tag to "portrait". If the activity is used in landscape mode it will crash.

Setting up DyScanView in the code

Listening for the result

Now you'll want to provide a callback implementing the DyScanView.DyScanResultListener interface by passing it into setResultListener(). This call should happen as early as possible, ideally immediately after setting the API key. As an example, the following code will progress to the EnterCardActivity when scanning is complete, passing along the card details if we got them.

dyScanView.setResultListener(new DyScanView.DyScanResultListener() {
public void onSuccess(CreditCard card) {
Intent intent = new Intent(MainActivity.this, EnterCardActivity.class);
intent.putExtra("cardNumber", card.getCardNumber());
intent.putExtra("expiryMonth", card.getExpiryMonth());
intent.putExtra("expiryYear", card.getExpiryYear());
finish();
startActivity(intent);
}

public void onFailure(int reason) {
Intent intent = new Intent(MainActivity.this, EnterCardActivity.class);
finish();
startActivity(intent);
}

// Implement functionality to use this info mid-scan
public void onProgressUpdate(DyScanProgressUpdate dyScanProgressUpdate) {
String network = dyScanProgressUpdate.getNetwork();
String lastFourDigits = dyScanProgressUpdate.getLastFourDigits();
}
});

onSuccess() will be called when we successfully scan a card, and onFailure() is called when we were not able to scan a card.

Optionally, you can implement the function onProgressUpdate to access information about the card being scanned while the scan is ongoing (available for version 1.6.6 of DyScan and up). The DyScanProgressUpdate class has two attributes (both of string type): lastFourDigits and network, which correspond to the last four digits and network of the credit card (e.g., Visa or Mastercard) being scanned, respectively. You may choose to surface this information to your users to give them more feedback as they are waiting for their card to scan.

The CreditCard object is basically the same as mentioned in DyScanActivity, but will also contain the bounding boxes of where the card number and expiration date were found. The integer passed in to onFailure() is an indicator of why things failed; the various values that can be passed in are provided here:

Exit ReasonExplanation
EXIT_REASON_AUTH_FAILUREOur servers are indicating that the API key provided is not valid. You should check that you have set this value by calling setApiKey() and that it is the correct value.
EXIT_REASON_PERMISSIONS_NOT_GRANTEDThe system indicated that we do not have permissions to access the camera. You should make sure that you have requested camera permissions from the user prior to calling onPermissionsGranted().
EXIT_REASON_CAMERA_ERRORWe were not able to access the camera properly. It may be the case that another app (or your app) has failed to release the camera.
EXIT_REASON_USER_REQUESTED_MANUAL_ENTRYIf you have opted to have the manual entry button shown in the UI, this is the code that will be returned when the user presses that button.
EXIT_REASON_SCAN_LOG_ERRORThe scan data upload to the backend has failed. This is only returned when awaitScanStorage is set to true

You do not have to explicitly check for these codes, but you may find it valuable to do so.

Camera Permissions

It is your responsibility to check for and, if necessary, request camera permissions. This can be done in the Activity (or Fragment) containing this View, or in a prior Activity. In either case, once you have verified that the user has granted permission to use the camera, you should make a call to onPermissionsGranted(), which takes no parameters. We will not attempt to start up any camera functionality prior to being told that permissions were granted.

Lifecycle Callbacks

We finally depend on your notifying us of certain Activity (or Fragment) lifecycle events. This is largely for resource management reasons. In your onResume(), onPause(), and onDestroy() functions you must make a call into our function of the exact same name with no arguments. We will not start up our preview until we have been informed that onResume() has been called.

Additional Important Considerations

When adding credit card scanning to your app, you are asking your users to point their phone camera at their credit cards. You should be sure to reduce their risk by prohibiting screenshots in your Activity by marking the window as secure. This is done by setting FLAG_SECURE on the window. For example:

getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);

This should be done prior to calling setContentView().

warning

Do not forget to set this flag; without it the preview may be shown on non-secure screens and the contents may be captured.

Debugging

By default, we only log ERROR level logs. If you want additional logging, you can get WARN and INFO level logs to help in debugging by making the following call:

dyScanView.setDebugLog(true);

Customizing the Layout

There are myriad attributes that can be set on the DyScanView in order to customize its appearance and behavior. You must have added the dyneti namespace as mentioned at the top of this page in order to use the custom attributes we provide.

AttributeDescriptionDefault Value
showCornersWhether to show the scan area outline.true
cornerThicknessHow thick to make the lines outlining the scan area, indicating to the user where to place their credit card.15f
cornerInactiveColorThe color to use in drawing the outline of the scan region when nothing of interest is detected.Color.GRAY
cornerActiveColorThe color to use in drawing the outline of the scan region when corners are detected.Color.CYAN
cornerCompletedColorThe color to use in drawing the outline of the scan region when we have successfully scanned a card.Color.GREEN
roundCornersWhether the scan region has round corners resembling the credit-card outline. If set to false, the scan region becomes a rectangle.true
expandCornersWhether to show the corners expanded outward with respect to the scan frame.false
chopCornersWhether to show the corners with limited length instead of having them expand all the way until they intersect.false
bgColorThe color to use to obscure everything outside the scan region in order to draw the user’s attention to the scan region.Color.GRAY
bgOpacityThe opacity to use when obscuring everything outside the scan region, as an integer ranging from 0 (transparent) to 255 (opaque).115
showResultOverlayWhether to briefly show the scanned card number (and date, if present) as an overlay over the screen after a successful scan.false
showDynetiLogoWhether to show the Dyneti logo and wordmark above the scan region.true
resultOverlayAnimationMsHow long to spend animating a fade-in of the detected card number and date, in milliseconds.1000
resultOverlayAlwaysHorizontalWhether to display number on completion horizontally in fixed position.false
showCardOverlayWhether to show the overlay displaying a sample card number and expiration date hinting at the user to place their card in the scan region.true
cardOverlayColorThe color to use in displaying the card overlay.Color.WHITE
cardOverlayOpacityThe opacity to use in displaying the card overlay.0.4f
cardOverlayNumberThe String to use as the credit card number displayed in the card overlay. Note that the text will be scaled to fit a region in the display, which may have strange results if the String is too long or too short."4242 4242 4242 4242"
cardOverlayDateThe String to use as the expiration date displayed in the card overlay. Note that the text will be scaled to fit a region in the display, which may have strange results if the String is too long or too short."11/11"
lightTorchWhenDarkWhether the phone will turn on the flashlight if multiple frames have appeared to be too dark. If set to false, torch toggle button will appear.true
vibrateOnCompletionWhether the device will vibrate once it has successfully extracted the credit card data from the images provided by the camera.true
cardFrameContentDescriptionThe content description of card scan frame."Align your card to this frame"
isChallengeWhether DyScanView is being used as a fraud check. This is currently only used for logging purposes, but in the future may impact behavior.false
enableSidewaysScanning:BoolWhether to allow cards to scan in sideways orientation. If set to true, vertical cards will be able to be scanned when positioned in the horizontal scan window. Note that enableSidewaysScanning and showRotateButton should not simultaneously be set to true when using the view controller, and that isVertical should not be used when enableSidewaysScanning is set to true when using DyScan as a view.false
awaitScanStorage:BoolWhether to strictly wait for the scan data to be successfully uploaded to the backend before returning a scan resultfalse

Additionally, there are some public functions you can use to easily add buttons with additional functionality to your scan screen. These are described below:

Public functions

NameDescription
NameDescription
setVertical(boolean)

Sets scan region orientation

  • true - vertical card
  • false - horizontal card
isVertical()Returns a boolean whether scan region is set to vertical card orientation (true when vertical)
setTorchEnabled(boolean)Turns torch on or off
isTorchEnabled()Returns a boolean whether torch is currently turned on (true when torch is on)
setDetectWrongCard(boolean)Whether to detect when the end-user is scanning the wrong card (when using DyScan for verification). If set to true and the string parameters expectedBIN and expectedLastFourDigits (which correspond to the first six and last four digits of the expected credit card number) are provided, when the end user attempts to scan the wrong card, the onProgressUpdate callback returns a boolean numberMismatch with true value (which can be used to signal the end user that they are not scanning the expected card) and the scan continues. Upon scanning the expected card, the scan completes.

Troubleshooting

Below we have explanations of the solutions to the most common situations where the DyScanView is not working as expected. Look for the issue you're having below.

The app crashes

This happens when the result listener has not been set and our code wants to return a result. If the result listener is not set, there is no point in running our code since your code will not be able to receive the results we provide. We don't prevent the crash so that this issue is caught quickly. There will be a warning printed out to the logs (only visible if you've enabled debug logging) if this has not been set by the time our View is attached to a window. The solution is to add the result listener; see the section on listening for a result for details on how to add the listener.

onFailure() is called unexpectedly

This happens when we are not able to scan a card. This may happen for reasons such as another app still having possession of the camera, the auth check on the API key indicating the key is invalid, or the system telling us that the user has not granted camera permissions. You should look at the integer argument provided in order to get more details on what is happening and how to resolve the issue; a table explaining them is present in the section on listening for a result.

No preview shows up

There are three reasons that the preview may not show up in your activity despite the DyScanView taking up space in the layout. In each case it is a missing call on our View; check that you are making all 3 calls and add any that may be missing. The first is that you need to set the API key. The second is that you need to inform us that camera permissions have been granted. And finally, our View needs to be lifecycle-aware, and so depends on you forwarding us lifecycle events.

Something else

Reach out to us on the communication channel we already have open. We're happy to get to the bottom of this issue together.