### Python Quick Start with full_scan
Source: https://context7_llms
Provides a quick start example for using the `full_scan` helper method in the Python CardScan API client. It demonstrates initializing the client with an API key.
```python
from cardscan_client import CardScanApi
# Initialize the client
client = CardScanApi(api_key="sk_test_cardscan_ai_...")
```
--------------------------------
### Getting Started with CardScan API Client in Dart
Source: https://github.com/CardScan-ai/api-clients/tree/main/clients/cardscan-dart
A basic example demonstrating how to initialize the CardScan API client and make a call to the `cardPerformance` endpoint. It includes error handling for network requests.
```dart
import 'package:cardscan_client/cardscan_client.dart';
final api = CardscanClient().getCardScanApi();
final String cardId = "38400000-8cf0-11bd-b23e-10b96e4ef00d"; // String |
final JsonObject body = Object; // JsonObject |
try {
final response = await api.cardPerformance(cardId, body);
print(response);
} catch on DioException (e) {
print("Exception when calling CardScanApi->cardPerformance: $e\n");
}
```
--------------------------------
### Install and Use CardScan Python Client
Source: https://pypi.org/project/cardscan-client
This snippet demonstrates how to install the cardscan-client using pip and provides a basic Python script to perform a full card scan using the client. It includes setup for API key authentication, client initialization, making the API call, and handling potential exceptions. The example assumes an API key is set as an environment variable.
```python
pip install cardscan-client
```
```python
from cardscan_client.api_client import ApiClient
from cardscan_client.api.card_scan_api import CardScanApi
from cardscan_client.configuration import Configuration
from cardscan_client.exceptions import ApiException
from pprint import pprint
import os
# Defining the host is optional and defaults to https://sandbox.cardscan.ai/v1
# See configuration.py for a list of all supported configuration parameters.
# The client must configure the authentication and authorization parameters
# in accordance with the API server security policy.
# Examples for each auth method are provided below, use the example that
# satisfies your auth use case.
# Configure Bearer authorization: bearerAuth
configuration = Configuration(
api_key=os.environ['API_KEY'],
environment='sandbox'
)
def main():
client = CardScanApi(api_client=ApiClient(configuration=configuration))
try:
api_response = client.full_scan(front_image_path="test/cards/front.jpg")
pprint(api_response)
except ApiException as e:
print("Exception when calling FullScan->full_scan: %s\n" % e)
if __name__ == "__main__":
main()
```
--------------------------------
### Python CardScan Client Installation and Usage
Source: https://github.com/CardScan-ai/api-clients/tree/main/clients/cardscan-python
Demonstrates how to install the CardScan Python client using pip and provides a basic example of how to initialize the client and perform a full card scan. It includes setup for API key authentication and error handling.
```python
from cardscan_client.api_client import ApiClient
from cardscan_client.api.card_scan_api import CardScanApi
from cardscan_client.configuration import Configuration
from cardscan_client.exceptions import ApiException
from pprint import pprint
import os
# Defining the host is optional and defaults to https://sandbox.cardscan.ai/v1
# See configuration.py for a list of all supported configuration parameters.
# The client must configure the authentication and authorization parameters
# in accordance with the API server security policy.
# Examples for each auth method are provided below, use the example that
# satisfies your auth use case.
# Configure Bearer authorization: bearerAuth
configuration = Configuration(
api_key=os.environ['API_KEY'],
environment='sandbox'
)
def main():
client = CardScanApi(api_client=ApiClient(configuration=configuration))
try:
api_response = client.full_scan(front_image_path="test/cards/front.jpg")
pprint(api_response)
except ApiException as e:
print("Exception when calling FullScan->full_scan: %s\n" % e)
if __name__ == "__main__":
main()
```
--------------------------------
### Installation
Source: https://www.npmjs.com/package/@cardscan.ai/cardscan-client
Instructions for installing the cardscan-client package using npm or yarn.
```APIDOC
## Installation
```bash
npm install @cardscan.ai/cardscan-client
```
```bash
yarn add @cardscan.ai/cardscan-client
```
```
--------------------------------
### Kotlin Installation
Source: https://docs.cardscan.ai/llms-full.txt
Install the official Kotlin client for the CardScan API using Gradle or Maven.
```APIDOC
# Kotlin 🟣
The official Kotlin client for the CardScan API provides a type-safe interface with coroutine support for Android and JVM applications.
## Installation
### Gradle (Kotlin DSL)
```kotlin
dependencies {
implementation("com.cardscan:api:1.0.0")
}
```
### Gradle (Groovy)
```groovy
dependencies {
implementation 'com.cardscan:api:1.0.0'
}
```
### Maven
```xml
com.cardscan
api
1.0.0
```
```
--------------------------------
### Flask Backend Example
Source: https://context7_llms
An example implementation of the /cardscan-session endpoint using Flask.
```APIDOC
## GET /cardscan-session (Flask Example)
### Description
Flask implementation to generate a CardScan.ai session token for the logged-in user.
### Method
GET
### Endpoint
/cardscan-session
### Parameters
#### Path Parameters
None
#### Query Parameters
- **user_id** (string) - Required - The unique identifier of the end user (obtained from `current_user.id`).
### Request Body
None
### Request Example
N/A (This is a server-side route)
### Response
#### Success Response (200)
- **session** (string) - The generated CardScan.ai session token.
#### Response Example
```json
{
"session": "session_token_from_cardscan_ai"
}
```
```
--------------------------------
### List Cards API Request Examples
Source: https://docs.cardscan.ai/llms-full.txt
Examples of how to call the list cards endpoint using cURL, Javascript, and Swift. These examples demonstrate authentication and basic usage.
```bash
curl --location --request GET 'https://sandbox.cardscan.ai/v1/cards' \
--header 'Authorization: Bearer endusertokenXXX'
```
```javascript
const client = new CardScanApi({
sessionToken:token,
live: false
});
client.listCards()
.then((cards) => {
//update UI.
})
.catch((error) => {
//retry or update UI
});
```
```swift
let apiClient = CardScanAPIClient(userToken: userToken, live: false)
apiClient.listCards(limit: 10) { result in
switch result {
case .failure(let error):
print("listCards error (error)")
case .success(let cards):
//update UI
}
}
```
--------------------------------
### Initialize and Use CardScan API Client in TypeScript
Source: https://context7_llms
Demonstrates initializing the CardScan API client with an API key, generating a session token for a user, and then creating a card using the generated token. This is a quick start example for TypeScript integration.
```typescript
// TypeScript example
import { CardScanApi } from '@cardscan.ai/cardscan-client';
const client = new CardScanApi({
apiKey: 'sk_test_cardscan_ai_...'
});
// Generate session token
const { Token, IdentityId, session_id } = await client.getAccessToken({
user_id: 'unique-user-id'
});
// Create a card
const card = await client.createCard({
sessionToken: Token,
enable_backside_scan: false
});
```
--------------------------------
### Node.js Express Backend Example
Source: https://context7_llms
An example implementation of the /cardscan-session endpoint using Node.js and Express.
```APIDOC
## GET /cardscan-session (Express Example)
### Description
Express.js implementation to generate a CardScan.ai session token for the authenticated user.
### Method
GET
### Endpoint
/cardscan-session
### Parameters
#### Path Parameters
None
#### Query Parameters
- **user_id** (string) - Required - The unique identifier of the end user (obtained from `req.auth.user`).
### Request Body
None
### Request Example
N/A (This is a server-side route)
### Response
#### Success Response (200)
- **session** (string) - The generated CardScan.ai session token.
#### Response Example
```json
{
"session": "session_token_from_cardscan_ai"
}
```
```
--------------------------------
### Kotlin API Client - Installation
Source: https://docs.cardscan.ai/api-clients/kotlin
Instructions on how to install the official Kotlin client for the CardScan API using Gradle (Kotlin DSL, Groovy) and Maven.
```APIDOC
## Kotlin API Client - Installation
### Gradle (Kotlin DSL)
```kotlin
dependencies {
implementation("com.cardscan:api:1.0.0")
}
```
### Gradle (Groovy)
```groovy
dependencies {
implementation 'com.cardscan:api:1.0.0'
}
```
### Maven
```xml
com.cardscan
api
1.0.0
```
```
--------------------------------
### Card Search Request in cURL
Source: https://context7_llms
Demonstrates how to perform a card search request using cURL. This example specifies the GET method, the API endpoint, the search query, the limit, and includes the necessary Authorization header with a bearer token.
```bash
curl --location --request GET 'https://sandbox.cardscan.ai/v1/cards/search?query=john%20doe&limit=10' \
--header 'Authorization: Bearer endusertokenXXX'
```
--------------------------------
### Search Cards API Request Examples
Source: https://context7_llms
Examples of how to search for cards using the CardScan AI API. Includes examples for cURL, JavaScript, and Swift, demonstrating how to authenticate and specify search parameters like query and limit. The responses shown are for a successful search and various error conditions.
```javascript
{
"cards": [
{
"card_id": "1bab2f3c-cfbe-4f22-b480-b389ece57f7e",
"state": "completed",
"created_at": "2021-07-30 19:56:40.638894+00:00",
"details": {
"member_name": {
"value": "john doe",
"scores": ["0.9974", "0.8879"]
},
"payer_name": {
"value": "unitedhealthcare",
"scores": ["0.9953", "0.9835"]
}
}
}
],
"response_metadata": {
"limit": 50,
"next_cursor": "IieuzkckWq0"
}
}
```
```javascript
{
"message": "query parameter is required",
"type": "Bad Request",
"code": 400
}
```
```javascript
{
"message": "Unknown authorization error - please check your token format and try again",
"type": "Unauthorized",
"code": 401
}
```
```javascript
{
"message": "Token is expired",
"type": "Authentication Timeout",
"code": 419
}
```
--------------------------------
### React Integration Example
Source: https://docs.cardscan.ai/advanced-features/eligibility-verification
Example of how to integrate CardScan.ai's eligibility verification callbacks into a React application.
```APIDOC
## React Integration Example
### Description
This example demonstrates how to use the `CardScanView` component in React, including handling `onEligibilitySuccess` and `onEligibilityError` callbacks for eligibility verification.
### Code
```javascript
import { CardScanView } from "@cardscan.ai/insurance-cardscan-react";
function EligibilityApp({ apiKey, ...props }) {
const eligibility = {
subscriber: {
firstName: "Joe",
lastName: "Doe",
dateOfBirth: "18020101",
},
provider: {
firstName: "John",
lastName: "Doe",
npi: "0123456789",
},
};
function cardScanSuccess(card) {
console.log(card);
}
function cardScanCancel() {
setShowScanView(false);
}
function cardScanError(error) {
console.log("Error Callback: ", error);
}
function eligibilitySuccess(eligibility) {
console.log(eligibility);
}
function eligibilityError(error) {
console.log(error);
}
return (
);
}
export default EligibilityApp;
```
### Callbacks
- **onEligibilitySuccess(eligibility)**: Triggered when an eligibility check is successful. Receives the eligibility data as an argument.
- **onEligibilityError(error)**: Triggered when an eligibility check encounters an error. Receives the error details as an argument.
```
--------------------------------
### CardScanView React Component Installation and Usage
Source: https://docs.cardscan.ai/llms-full.txt
Instructions for installing and importing the CardScanView React component and its associated model. It also shows how to import the optional CardScanApi client for custom applications.
```bash
$ npm i @cardscan.ai/insurance-cardscan-react
$ yarn add @cardscan.ai/insurance-cardscan-react
```
```javascript
import { CardScanView, CardScanModel } from "@cardscan.ai/insurance-cardscan-react";
```
```javascript
import { CardScanApi } from "@cardscan.ai/cardscan-client";
```
--------------------------------
### Basic Card Scanner Initialization in Swift
Source: https://context7_llms
Demonstrates how to instantiate and present the CardScannerViewController in an iOS application. It includes setting up user tokens, defining success and error callback handlers, and configuring the scanner with essential parameters before presenting it.
```swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var cardScanButton: UIButton!
@IBAction private func didTapScanCard(_ sender: UIButton) {
startCardScanning()
}
private func startCardScanning() {
// Replace with the user token generated from the server
// See https://docs.cardscan.ai/authentication#end-user
let userToken = ""
let onSuccessCallback: (InsuranceCard) -> Void = { card in
print("Card Scanned Successfully! - \(card)")
}
let onErrorCallback: (CardScanError) -> Void = { error in
print("Card Scanning Error: \(error.localizedDescription)")
}
// Configure and present the CardScanViewController
let config = CardScanConfig(sessionToken: userToken, live: false, onSuccess: onSuccessCallback, onError: onErrorCallback)
let cardScanViewController = CardScanViewController()
cardScanViewController.config = config
// Present the CardScanViewController
present(cardScanViewController, animated: true)
}
}
```
--------------------------------
### Card Scanner Initialization and Presentation
Source: https://docs.cardscan.ai/llms-full.txt
This section demonstrates how to import the InsuranceCardScan package, configure the CardScannerViewController with a session token and callbacks, and present it to the user.
```APIDOC
## Import Package
```swift
import InsuranceCardScan
```
## Basic Usage Example
This example shows how to create, configure, and present the `CardScannerViewController`.
### Method
N/A (This is a usage example, not a direct API endpoint)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var cardScanButton: UIButton! // Assuming this is connected in the Storyboard
@IBAction private func didTapScanCard(_ sender: UIButton) {
startCardScanning()
}
private func startCardScanning() {
// Replace with the actual user token
let userToken = ""
let onSuccessCallback: (InsuranceCard) -> Void = { card in
print("Card Scanned Successfully! - \(card)")
// Handle successful scan, e.g., dismiss the scanner and process the card data
self.dismiss(animated: true)
}
let onErrorCallback: (CardScanError) -> Void = { error in
print("Card Scanning Error: \(error.localizedDescription)")
// Handle errors, e.g., show an alert to the user
self.dismiss(animated: true)
}
// Configure the CardScanViewController
let config = CardScanConfig(
sessionToken: userToken,
live: false, // Set to true for production environment
onSuccess: onSuccessCallback,
onError: onErrorCallback
// Add other optional callbacks and configurations as needed
)
let cardScanViewController = CardScanViewController()
cardScanViewController.config = config
// Present the CardScanViewController
present(cardScanViewController, animated: true)
}
}
```
### Response
N/A (This is a client-side SDK usage example)
### Response Example
N/A
```
--------------------------------
### Rule Condition Example: String Starts With
Source: https://docs.cardscan.ai/advanced-features/overseer
This example illustrates a rule condition using the 'startsWith' operator. It verifies if the 'card.member_number' begins with the prefix '128'. This can be useful for identifying members belonging to a specific group or range.
```pseudo-code
"card.member_number" starts with "128"
```
--------------------------------
### Create a Card with Options (Swift)
Source: https://context7_llms
This Swift example illustrates how to create a new card object using the CardScan API client. It shows how to configure options such as disabling backside scanning and livescan, and attaching metadata like patient and visit IDs.
```swift
struct CardCreationExample {
let client: CardScanAPI
func createCard() async throws -> CardApiResponse {
let request = CreateCardRequest(
enableBacksideScan: false,
enableLivescan: false,
metadata: [
"patient_id": "12345",
"visit_id": "v-67890"
]
)
let card = try await client.createCard(request: request)
print("Card ID: \(card.cardId)")
print("State: \(card.state)") // .pending
return card
}
}
```
--------------------------------
### Get Access Token - Node.js
Source: https://context7_llms
This Node.js example uses the axios library to retrieve an access token for end-user authentication. It includes the required Authorization header and logs the JSON response or any errors.
```JavaScript
var axios = require('axios');
url = 'https://sandbox.cardscan.ai/v1/access-token'
var options = {
headers: {
'Authorization': 'Bearer sk_test_cardscan_ai_XXXXXXXXXXXXXXX'
}
}
axios.get(url, options)
.then(function (response) {
console.log(JSON.stringify(response.data))
})
.catch(function (error) {
console.log(error);
});
```
--------------------------------
### Flutter Card Scanner Installation and Usage
Source: https://docs.cardscan.ai/ui-components/flutter
This snippet shows how to install and use the CardScanner widget in a Flutter application. It includes adding the package to pubspec.yaml and importing the necessary libraries. The basic example demonstrates how to embed the CardScanner within a Flutter widget, configure callbacks for success, error, and cancellation, and pass necessary properties.
```yaml
dependencies:
flutter:
sdk: flutter
insurance_card_scanner: ^0.3.0
```
```dart
import 'package:insurance_card_scanner/insurance_card_scanner.dart';
class ScannerWidgetScreen extends StatelessWidget {
const ScannerWidgetScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Scanner widget'),
),
body: CardScanner(
properties: CardScanConfig(
sessionToken: '',
onSuccess: (card) {
print('Scan success');
},
onError: (message) {
print(message ?? 'Unknown Scan error');
},
onCancel: () {
Navigator.of(context).pop();
},
),
),
);
}
}
```
```dart
import 'package:insurance_card_scanner/insurance_card_scanner.dart';
import 'package:insurance_card_scanner/insurance_card_scanner_api.dart';
```
--------------------------------
### CardScan API Configuration and Initialization
Source: https://context7_llms
Demonstrates how to configure and initialize the `CardScanAPI` client. This includes setting up custom configurations such as base URL, timeouts, and retry mechanisms, along with providing an API key for authentication.
```swift
// Custom configuration
let configuration = CardScanConfiguration(
baseURL: "https://sandbox.cardscan.ai/v1",
timeout: 30,
retryCount: 3,
retryDelay: 1.0
)
let client = CardScanAPI(
apiKey: "sk_test_cardscan_ai_...",
configuration: configuration
)
```
--------------------------------
### Install and Use CardScan Python Client
Source: https://docs.cardscan.ai/api-clients/python
Install the official Python client for the CardScan API using pip. This client provides a pythonic interface for all API operations, allowing initialization with an API key or session token. It supports generating session tokens for frontend operations and includes examples for basic usage and quick scanning.
```python
from cardscan_client import CardScanApi
from cardscan_client.exceptions import ApiException
# Initialize with your API key
api_key = "sk_test_cardscan_ai_..."
client = CardScanApi(api_key=api_key)
# Generate a session token for a user
token_response = client.get_access_token(user_id="unique-user-123")
session_token = token_response["Token"]
identity_id = token_response["IdentityId"]
session_id = token_response["session_id"]
# Initialize client with session token for frontend operations
user_client = CardScanApi(session_token=session_token, live=False)
```
--------------------------------
### Dart/Flutter CardScan API Client Installation
Source: https://docs.cardscan.ai/llms-full.txt
Instructions for adding the official Dart CardScan API client to a Flutter or Dart project. It involves updating the `pubspec.yaml` file with the `cardscan_client` dependency and then running the appropriate package manager command (`flutter pub get` or `dart pub get`). This enables developers to use the CardScan API in their Dart-based applications.
```yaml
dependencies:
cardscan_client: ^1.0.0
```
```bash
flutter pub get
# or for Dart-only projects
dart pub get
```
--------------------------------
### Obtain Access Token (Bash)
Source: https://docs.cardscan.ai/authentication
Example using cURL to make a GET request to the CardScan.ai sandbox API to obtain an access token. Requires an Authorization header with a bearer token.
```bash
curl --request GET 'https://sandbox.cardscan.ai/v1/access-token' \
--header 'Authorization: Bearer sk_test_cardscan_ai_XXXXXXXXXXXXXXX'
```
--------------------------------
### Verify Svix Webhook in Node.js (Nuxt)
Source: https://docs.svix.com/receiving/verifying-payloads/how
This Node.js example for Nuxt demonstrates how to verify Svix webhook requests. It uses `getRequestHeaders` and `readRawBody` to get the necessary information and then verifies the signature.
```typescript
import { Webhook } from "svix";
const secret = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
export default defineEventHandler(async (event) => {
const headers = getRequestHeaders(event);
const payload = await readRawBody(event);
const wh = new Webhook(secret);
let msg;
try {
msg = wh.verify(payload, headers);
} catch (err) {
setResponseStatus(event, 400);
return "Bad Request";
}
// Do something with the message...
return "OK";
})
```
--------------------------------
### Quick Start with fullScan
Source: https://context7_llms
Use the `fullScan` helper method to automatically handle the entire card scanning workflow, from image upload to data extraction.
```APIDOC
## Quick Start with fullScan
The easiest way to scan cards is using the `fullScan` helper method that handles the entire workflow:
```typescript
// Initialize with websocket URL for fullScan support
const client = new CardScanApi({
apiKey: 'sk_test_cardscan_ai_...',
websocketUrl: 'wss://sandbox.cardscan.ai/v1/ws' // Required for fullScan
});
// Scan a card (front and back)
async function scanCard() {
// For Node.js - using file paths
const result = await client.fullScan({
frontImage: './front-card.jpg',
backImage: './back-card.jpg' // Optional - omit for front-only
});
// For browser - using File objects from input
const frontFile = document.getElementById('front-input').files[0];
const backFile = document.getElementById('back-input').files[0];
const result = await client.fullScan({
frontImage: frontFile,
backImage: backFile // Optional
});
// Access the results
console.log('Card ID:', result.card_id);
console.log('Member ID:', result.details.member_id);
console.log('Group:', result.details.group_number);
console.log('Payer:', result.details.payer_name);
return result;
}
```
The `fullScan` method automatically:
* Creates a card with appropriate settings
* Generates upload URLs
* Uploads images in the correct order
* Monitors processing via WebSocket
* Returns the completed card with all extracted data
```
--------------------------------
### Initiate Card Scanning Activity (Kotlin)
Source: https://context7_llms
This Kotlin code snippet demonstrates how to set up an activity to initiate the card scanning process. It registers a callback for the result of the `CardScanActivity` and sets an onClick listener for a button to first obtain a session token and then launch the scanner. This requires Android Activity and ActivityResultContracts setup.
```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_onboarding)
cardScanResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
CardScanActivity.processResult(this@OnboardingActivity, result)
}
findViewById(R.id.scanCardButton).setOnClickListener { _ ->
getSession { session ->
//trigger the loading of CardScanActivity with user's session token
CardScanActivity.start(
activity = this,
resultLauncher = cardScanResultLauncher,
sessionToken = session
)
}
}
}
```
--------------------------------
### Setup for Raw Body in Node.js (NestJS)
Source: https://docs.svix.com/receiving/verifying-payloads/how
This NestJS example demonstrates setting up the application to handle raw request bodies, which is necessary for webhook verification. The `rawBody: true` option is passed to `NestFactory.create` in `main.ts`.
```typescript
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule,
{ rawBody: true } // add rawBody flag
);
await app.listen(3000);
}
bootstrap();
```
--------------------------------
### Overseer Rules Engine - Modify Member ID (JSON)
Source: https://context7_llms
An example Overseer rule in JSON format. This rule triggers before an eligibility request and modifies the member ID by prepending '000' if the payer is 'XYZ Insurance' and the member number starts with '128'.
```json
{
"id": "rule_002",
"name": "Modify member ID for XYZ Insurance",
"trigger": "pre_eligibility_request",
"conditions": {
"all": [
{ "field": "card.payer_name", "comparison": "equals", "value": "XYZ Insurance" },
{ "field": "card.member_number", "comparison": "startsWith", "value": "128" }
]
},
"actions": [
{
"type": "prepend_value",
"field": "eligibility_request.subscriber.member_id",
"set_value": "000"
}
],
"description": "If payer is XYZ Insurance and member ID starts with '128', prepend '000' to member ID."
}
```
--------------------------------
### GET /v1/cards/{cardId}
Source: https://docs.cardscan.ai/llms-full.txt
Retrieves detailed information about a specific scanned insurance card using its unique ID. This includes pharmacy benefit manager, card identifiers, client name, plan details, coverage start date, phone numbers, and addresses.
```APIDOC
## GET /v1/cards/{cardId}
### Description
Retrieves detailed information about a specific scanned insurance card using its unique ID. This includes pharmacy benefit manager, card identifiers, client name, plan details, coverage start date, phone numbers, and addresses.
### Method
GET
### Endpoint
`/v1/cards/{cardId}`
### Parameters
#### Path Parameters
- **cardId** (string) - Required - The unique identifier of the card to retrieve.
#### Query Parameters
None
#### Request Body
None
### Request Example
```bash
curl --request GET 'https://sandbox.cardscan.ai/v1/cards/a1d743ee-3bb9-468d-a2c5-4e33fa0e1c6e' \
--header 'Authorization: Bearer endusertokenXXX'
```
### Response
#### Success Response (200)
- **details** (object) - Contains the scanned details of the insurance card.
- **pharmacy_benefit_manager** (string) - The pharmacy benefit manager (PBM) that processes prescription claims for this plan.
- **card_specific_id** (string) - A non-specific but prominent identifier found on the card.
- **client_name** (string) - The name of the employer who is contracted with the 3rd party administrator.
- **plan_details** (object) - When available a list of: deductibles, co-pays, co-insurance, PCP name.
- **start_date** (string) - The date when coverage starts.
- **phone_numbers** (array) - A list of all phone numbers found of the front and back of the card.
- **addresses** (array) - A list of all addresses found on the card.
- **payer_match** (object) - Comprehensive payer matching results including clearinghouse matches, custom matches, and confidence scores.
- **metadata** (object) - API version information including the insurance scan model version and payer match version used.
- **images** (object) - Signed URLs for accessing the uploaded card images. URLs are valid for 24 hours.
- **deleted** (boolean) - Boolean indicating whether this card has been marked as deleted.
#### Response Example
```json
{
"details": {
"pharmacy_benefit_manager": "optumrx",
"card_specific_id": "54243",
"client_name": "Apple, Inc.",
"plan_details": {
"Office": "$25",
"ER": "$300"
},
"start_date": "04/01/2021",
"phone_numbers": [
"800-400-5251"
],
"addresses": [
"UnitedHealthcare",
"P.O. Box 740800",
"Atlanta, GA 30374-0800"
]
},
"payer_match": {
"clearinghouse_matches": [],
"custom_matches": [],
"confidence_scores": {}
},
"metadata": {
"insurance_scan_version": "malbec-1.0",
"payer_match_version": "hybrid-1.2"
},
"images": {
"front": {
"url": "https://..."
}
},
"deleted": false
}
```
### Error Handling
- **401 Unauthorized**: Invalid or missing authentication token.
- **404 Not Found**: The specified card ID does not exist.
- **500 Internal Server Error**: An unexpected error occurred on the server.
```
--------------------------------
### Basic CardScanActivity Usage Example
Source: https://context7_llms
Demonstrates the basic implementation of launching CardScanActivity within an Android AppCompatActivity. It includes setting up a click listener to trigger the scan and configuring CardScanConfig with a session token, along with optional parameters for closing the activity after success or error.
```kotlin
import ai.cardscan.insurance.CardScanActivity
import ai.cardscan.insurance.data.CardScanConfig
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
class OnboardingActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById(R.id.btnScanCard).setOnClickListener {
setUpCardScanHelper()
launchCardScanActivity()
}
}
private fun launchCardScanActivity() {
CardScanActivity.launch(
// Pass an activity to the launcher
this@MainActivity,
// A CardScanConfig instance to connect to the server and customize UI
CardScanConfig(
// your token goes here
sessionToken = "xxx",
),
// And other optional parameters to alter behavior
closeAfterSuccess = true, // Close the scanner after successful scan?
// defaults to true
closeAfterSuccessDelay = 1500, // If set to close automatically,
// how long to wait after scan to close? In milliseconds
closeAfterErrorDelay = 2000 // Cardscan activity is killed automatically after an error
// You can decide between 0 and 30 seconds, how long to wait before closing
)
}
private fun setUpCardScanHelper() {
// Helper class to setup observers and create the appropiate callbacks
// CardScanHelper takes in a lifecycleOwner,
// "this" in the case of setup within an activity,
// or the host activity in the case of a fragment, or viewLifecycleOwner
cardScanHelper = CardScanHelper(this).apply {
onSuccess { card: ScannedCard ->
Toast.makeText(this@MainActivity, "Card Scanned: ${card.cardId}", Toast.LENGTH_SHORT).show()
}
onError { error: CardError? ->
Toast.makeText(this@MainActivity, "Error encountered!", Toast.LENGTH_SHORT).show()
print(error?.message)
}
onRetry {
Toast.makeText(this@MainActivity, "User retried after failed scan!", Toast.LENGTH_SHORT).show()
}
onCancel {
Toast.makeText(this@MainActivity, "User closed the scanner with close button!", Toast.LENGTH_SHORT).show()
}
onEligibilitySuccess {
Toast.makeText(this@MainActivity, "Eligibility info found!", Toast.LENGTH_SHORT).show()
}
onEligibilityError {
Toast.makeText(this@MainActivity, "Error during eligibility check!", Toast.LENGTH_SHORT).show()
}
}
}
}
```
--------------------------------
### Kotlin CardScanConfig Example
Source: https://docs.cardscan.ai/llms-full.txt
Demonstrates how to instantiate and configure CardScanConfig in Kotlin. It includes required session token, optional live mode toggle, backside support, eligibility request details, and various UI customization properties.
```kotlin
CardScanConfig(
// Required
sessionToken: token,
live: false,
// Optional
backsideSupport: scanBackside,
eligibility = EligibilityRequest( // We now support eligibility checks!
Subscriber(
firstName = "Subscriber's first name",
lastName = "Subscriber's last name",
dateOfBirth = "19020403" // Always in format YYYYMMDD
),
Provider(
firstName = "Provider's first name",
lastName = "Provider's last name",
npi = "12345677"
)
)
// UI Customization
messages = CardScanMessages(
autoCaptureTitle = "My Auto Capture Title",
manualCaptureTitle = "My Manual Capture Title",
processingTitle = "My Processing Title",
frontSideCompletedTitle = "My FrontSide Completed Title",
completedTitle = "My Completed Title",
retryTitle = "Me Retry Title",
errorTitle = "My Error Title",
cameraErrorTitle = "My Camera Error Title"
),
messageFontSize: messageFontSize, // Float
messageTextColor: messageTextColor, // Int
messageBackgroundColor: messageBackgroundColor, // Int
autoSwitchActiveColor: autoSwitchActiveColor, // Int
autoSwitchInactiveColor: autoSwitchInactiveColor, // Int
progressBarColor: progressBarColor, // Int
widgetBackgroundColor: widgetBackgroundColor, // Int
)
```
--------------------------------
### Backend Authentication Endpoint for CardScan.ai (Flask)
Source: https://context7_llms
This Flask example demonstrates how to create a backend endpoint (`/cardscan-session`) that authenticates users and retrieves a session token from the CardScan.ai API. It uses the `requests` library for API calls and `flask_login` for user authentication. Ensure you have `requests` and `Flask-Login` installed.
```python
import requests
from flask_login import login_required, current_user
@app.route('/cardscan-session')
@login_required
def session():
"""
Generates a cardscan.ai token for the logged-in user and returns it.
"""
url = "https://sandbox.cardscan.ai/v1/access-token"
params = {
'user_id': current_user.id
}
headers = {
'Authorization': 'Bearer sk_test_cardscan_ai_XXXXXXXXXXXXXXX'
}
response = requests.request("GET", url, params=params, headers=headers)
response.raise_for_status()
payload = response.json()
return jsonify(payload)
```
--------------------------------
### Kotlin CardScan Helper Setup
Source: https://docs.cardscan.ai/ui-components/android
Initializes the CardScanHelper with various callback functions for scan success, errors, cancellations, and eligibility checks. This setup ensures that the application can react to different outcomes of the card scanning process. It relies on the Activity or Fragment context for its initialization.
```kotlin
private fun setUpCardScanHelper() {
cardScanHelper = CardScanHelper(this).apply {
onSuccess { card: ScannedCard -> handleCardScanSuccess(card) }
onError { error: CardError? -> handleCardScanError(error) }
onCancel { // Handle a user closing the scanner with the close button!
}
onRetry { // Triggered after the user retried a scan
}
onEligibilitySuccess { eligibility:Eligibility -> handleEligibilitySuccess(eligibility) }
onEligibilityError { eligibilityError:EligibilityError? -> handleEligibilityError(eligibilityError) }
}
}
```
--------------------------------
### Basic Integration: CI Workflow with Watchdog
Source: https://github.com/CardScan-ai/claude-code-watchdog
This example demonstrates a common CI workflow integrating the Claude Code Watchdog. It includes checkout, Node.js setup, running tests with continue-on-error enabled, and then triggering the watchdog for analysis if tests fail. It also shows how to send critical failure notifications to Slack.
```yaml
name: CI with Watchdog
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
permissions:
contents: write # For creating fix PRs
issues: write # For creating issues
pull-requests: write # For creating PRs
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '18'
- name: Install and test
run: |
npm ci
npm test
continue-on-error: true # Let Artemis analyze failures
- name: Artemis failure analysis
if: failure()
id: watchdog
uses: cardscan-ai/claude-code-watchdog@v0.2
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
test_results_path: 'test-results/**/*.xml'
- name: Notify team on critical failures
if: failure() && steps.watchdog.outputs.severity == 'critical'
uses: 8398a7/action-slack@v3
with:
status: failure
channel: '#critical-alerts'
title: '🚨 Critical Test Failure'
message: |
Severity: ${{ steps.watchdog.outputs.severity }}
Action: ${{ steps.watchdog.outputs.action_taken }}
Issue: #${{ steps.watchdog.outputs.issue_number }}
mention: 'channel'
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
```
--------------------------------
### Get Session Token and Start CardScanActivity (Kotlin)
Source: https://docs.cardscan.ai/authentication
This Kotlin code snippet shows how to request a session token from your backend within an AppCompatActivity. It uses an extension function '.httpPost()' (assumed) for making the request and processes the JSON response to extract the session token. The CardScanActivity is then launched using an ActivityResultLauncher with the obtained session token.
```kotlin
package com.example.cardscanintegration // Replace with your actual package name
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.JsonObject // Assuming Gson is used for JSON parsing
// --- Placeholder definitions for CardScan related classes ---
// Replace these with actual imports from the CardScan SDK
// Represents the data returned after a successful scan
data class CardData(
val cardNumber: String? = null,
val expiryMonth: String? = null,
val expiryYear: String? = null,
val cvc: String? = null
// Add other relevant fields based on CardScan SDK
)
object CardScanActivity {
private const val EXTRA_SESSION_TOKEN = "sessionToken"
private const val EXTRA_LIVE_MODE = "liveMode"
fun start(
activity: Activity,
resultLauncher: ActivityResultLauncher,
sessionToken: String,
liveMode: Boolean = true // Default to true if live scanning is intended
) {
val intent = Intent(activity, CardScanActivity::class.java).apply {
putExtra(EXTRA_SESSION_TOKEN, sessionToken)
putExtra(EXTRA_LIVE_MODE, liveMode)
}
resultLauncher.launch(intent)
}
// Method to process the result returned from CardScanActivity
// This should be called within the ActivityResultLauncher's callback
fun processResult(callback: CardScanActivityResult, result: ActivityResult) {
if (result.resultCode == Activity.RESULT_OK) {
val data: Intent? = result.data
// Example: Extracting card data. Actual implementation depends on CardScan SDK.
val cardNumber = data?.getStringExtra("cardNumber")
val expiryMonth = data?.getStringExtra("expiryMonth")
val expiryYear = data?.getStringExtra("expiryYear")
val cvc = data?.getStringExtra("cvc")
if (cardNumber != null) {
val cardData = CardData(cardNumber, expiryMonth, expiryYear, cvc)
callback.scanSuccess(cardData)
} else {
callback.scanFailure(Exception("Card data missing in result"))
}
} else {
// Handle cancellation or other error codes
callback.scanCancelled() // Or a specific failure callback
}
}
}
// Interface to handle results from CardScanActivity
interface CardScanActivityResult {
fun scanSuccess(card: CardData)
fun scanFailure(exception: Exception) = Unit // Optional
fun scanCancelled() = Unit // Optional
}
// --- Extension function placeholder for httpPost ---
// You would need to implement this using a networking library like Ktor, Retrofit, or Volley.
// This is a simplified mock for demonstration.
fun String.httpPost(): HttpPostHelper {
Log.d("Network", "Making POST request to: $this")
// In a real app, this would initiate a network request.
return HttpPostHelper(this)
}
class HttpPostHelper(private val url: String) {
fun responseJson(callback: (context: Context, result: JsonObject) -> Unit): Unit {
// Simulate a network response
Log.d("Network", "Simulating network response for $url")
// Simulate successful response with JSON payload
val mockJsonResponse = JsonObject().apply {
addProperty("session", "mock_session_token_12345")
// Add other properties if needed
}
// In a real app, you'd call the callback asynchronously after the network call completes.
// For this example, we'll simulate immediate callback.
callback(ApplicationProvider.getApplicationContext(), mockJsonResponse) // Requires androidx.test.core:core-ktx dependency for ApplicationProvider
}
}
// --- Main Activity Implementation ---
// Mock ApplicationProvider for local testing without Android Test environment
object ApplicationProvider {
fun getApplicationContext(): Context {
// In a real Android project, this would return the application context.
// For standalone demo purposes, return a placeholder if possible or throw error.
throw NotImplementedError("ApplicationProvider.getApplicationContext() requires Android environment")
}
}
class OnboardingActivity : AppCompatActivity(), CardScanActivityResult {
private lateinit var cardScanResultLauncher: ActivityResultLauncher
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_onboarding) // Ensure you have this layout file
cardScanResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
result -> CardScanActivity.processResult(this@OnboardingActivity, result)
}
// Assuming you have a button with ID 'scanCardButton' in your layout
findViewById(R.id.scanCardButton).setOnClickListener {
_ -> getSession {
session ->
//trigger the loading of CardScanActivity with user's session token
CardScanActivity.start(
activity = this,
resultLauncher = cardScanResultLauncher,
sessionToken = session
)
}
}
}
private fun getSession(callback: (session: String) -> Unit) {
// Replace with your actual backend URL to get the session token
val sessionTokenUrl = "https://{{YOUR_SERVER_BASE_URL}}/cardscan-session"
// Simulate the network call using the placeholder httpPost extension
// In a real app, use Retrofit, Ktor Client, Volley, etc.
sessionTokenUrl.httpPost().responseJson { context, result ->
try {
// check for errors :)
val jsonObject = result.asJsonObject // Assuming result is JsonObject
val session = jsonObject.get("session").asString // Extract session token
callback(session)
} catch (e: Exception) {
Log.e("OnboardingActivity", "Error getting session token: ${e.message}", e)
// Handle error, e.g., show a toast or dialog to the user
}
}
}
override fun scanSuccess(card: CardData) {
Log.d("CardScan", "ScanSuccess $card")
// Handle successful scan, e.g., update UI, navigate
// Example: Toast.makeText(this, "Card Scanned: ${card.cardNumber}", Toast.LENGTH_LONG).show()
}
override fun scanFailure(exception: Exception) {
Log.e("CardScan", "ScanFailure ${exception.message}", exception)
// Handle scan failure
// Example: Toast.makeText(this, "Scan failed: ${exception.message}", Toast.LENGTH_LONG).show()
}
override fun scanCancelled() {
Log.d("CardScan", "ScanCancelled")
// Handle scan cancellation
// Example: Toast.makeText(this, "Scan cancelled", Toast.LENGTH_SHORT).show()
}
}
```