# Query and script parameters

Pass additional data to PayPal to further configure your Android integration.

## Overview

You can include the optional `queryParams` and `scriptParams` options in the `PayPalComponentConfig` to personalise your setup and help PayPal determine which funding sources and buttons to display to your shoppers.

Query parameters help define specific content or actions based on the data being passed, while script parameters allow you to provide information you need for your integration to work, a single-use token, or information you'd like to capture for analytics reasons.

## Query parameters

```kotlin
import com.pxp.checkout.components.paypal.types.PayPalQueryParams

queryParams = PayPalQueryParams(
    buyerCountry = "US",
    debug = false,
    integrationDate = "2025-07-01",
    merchantId = "ABC123"
)
```

### Configuration parameters

| Parameter | Description |
|  --- | --- |
| `queryParams`PayPalQueryParams? | Details about the optional query parameters. |
| `queryParams.buyerCountry`String? | The country code for the buyer's country, in ISO-3166-1 alpha-2 format. This determines the eligible funding sources for a given buyer. Any country that you can pass as a locale is a valid buyer country. Defaults to the buyer's IP geolocation.`buyerCountry` is only used in the sandbox. Don't pass this query parameter in production. |
| `queryParams.debug`Boolean | Whether to use debug mode. Debug mode is recommended only for testing and debugging, because it increases the size of the script and negatively impacts performance. Defaults to `false`.Always set `debug = false` for release builds. Debug mode increases script size and impacts performance. |
| `queryParams.integrationDate`String? | The date when your PayPal client ID was created (`YYYY-MM-DD`). This helps the PayPal script automatically apply any backward-compatible updates introduced after that date. |
| `queryParams.merchantId`String? | The merchant ID of the merchant for whom you're facilitating a transaction. Use this parameter only for partner, marketplaces, and cart solutions when you are acting on behalf of another merchant to facilitate their PayPal transactions. |


### Debug mode for Android

Enable debug mode during development to get detailed logs. You can configure this automatically based on your build type:

```kotlin
val paypalConfig = PayPalComponentConfig(
    queryParams = PayPalQueryParams(
        debug = BuildConfig.DEBUG // Automatically use debug mode for debug builds
    )
)
```

You can filter debug logs in logcat:

```bash
# Filter PayPal debug logs
adb logcat | grep -E "(PayPal|PxpCheckout)"
```

### Environment-based configuration

Configure query parameters based on your build environment:

```kotlin
val paypalConfig = PayPalComponentConfig(
    queryParams = PayPalQueryParams(
        debug = BuildConfig.DEBUG,
        integrationDate = BuildConfig.PAYPAL_INTEGRATION_DATE,
        merchantId = if (BuildConfig.DEBUG) "TEST_MERCHANT_ID" else "PROD_MERCHANT_ID"
    )
)
```

## Script parameters

Script parameters provide additional context and tokens that PayPal uses to optimise the payment experience, enable advanced features like one-click payments, and ensure secure integration with your Android app.

```kotlin
import com.pxp.checkout.components.paypal.types.PayPalScriptParams

scriptParams = PayPalScriptParams(
    cspNonce = "YOUR_CSP_NONCE",
    clientToken = "abc123xyz==",
    pageType = "checkout",
    userIdToken = "YOUR_USER_ID_TOKEN"
)
```

### Configuration parameters

| Parameter | Description |
|  --- | --- |
| `scriptParams`PayPalScriptParams? | Details about the optional script parameters. |
| `scriptParams.cspNonce`String? | A single-use Content Security Policy (CSP) token, if you use them in your WebView. This is required if your app implements CSP for WebView security. |
| `scriptParams.clientToken`String? | The client token used to identify your shoppers. |
| `scriptParams.pageType`String? | The type of page or screen. Use this to log page type and interactions.Possible values:`product-listing``search-results``product-details``mini-cart``cart``checkout` |
| `scriptParams.userIdToken`String? | Your user ID token. **Required for one-click payment functionality with vaulting.** Obtain this token from the vault status check. |


### CSP nonce for WebView security

If your app uses Content Security Policy for WebView security, provide a CSP nonce:

```kotlin
import java.security.SecureRandom
import java.util.Base64

fun generateCSPNonce(): String {
    val random = SecureRandom()
    val bytes = ByteArray(32)
    random.nextBytes(bytes)
    return Base64.getEncoder().encodeToString(bytes)
}

val paypalConfig = PayPalComponentConfig(
    scriptParams = PayPalScriptParams(
        cspNonce = generateCSPNonce()
    )
)
```

### Page type tracking in Android

Use the `pageType` parameter to track user flow through your app. Set different values for different screens:

```kotlin
@Composable
fun ProductDetailsPayPal() {
    val paypalConfig = remember {
        PayPalComponentConfig(
            scriptParams = PayPalScriptParams(
                pageType = "product-details"
            )
        )
    }
    
    // ... component rendering
}

@Composable
fun CheckoutPayPal() {
    val paypalConfig = remember {
        PayPalComponentConfig(
            scriptParams = PayPalScriptParams(
                pageType = "checkout"
            )
        )
    }
    
    // ... component rendering
}
```

### One-click payment configuration

For one-click payment functionality, you need to provide a `userIdToken` obtained from the vault status check:

```kotlin
val paypalConfig = PayPalComponentConfig(
    enableOneClickPayment = true,
    scriptParams = PayPalScriptParams(
        userIdToken = getUserIdTokenFromVaultStatus()
    )
)
```

To obtain the `userIdToken`:

```kotlin
import kotlinx.coroutines.launch

suspend fun getUserIdTokenFromVaultStatus(): String? {
    return try {
        val vaultStatus = checkPayPalVaultStatus(merchantShopperId)
        vaultStatus.userIdToken
    } catch (e: Exception) {
        Log.e("PayPal", "Failed to get vault status", e)
        null
    }
}
```

## Examples

### Basic configuration example

Here's a simple example showing how to use query and script parameters:

```kotlin
import com.pxp.checkout.components.paypal.PayPalComponentConfig
import com.pxp.checkout.components.paypal.types.*

val paypalConfig = PayPalComponentConfig(
    renderType = "standalone",
    fundingSources = "paypal",
    queryParams = PayPalQueryParams(
        buyerCountry = "US",
        debug = false,
        integrationDate = "2025-07-01",
        merchantId = "ABC123"
    ),
    scriptParams = PayPalScriptParams(
        cspNonce = "YOUR_CSP_NONCE",
        clientToken = "abc123xyz==",
        pageType = "checkout",
        userIdToken = "YOUR_USER_ID_TOKEN"
    )
)
```

### Complete Android implementation

Here's a complete example showing how to configure all parameters in a production Android app:

```kotlin
import com.pxp.checkout.components.paypal.PayPalComponentConfig
import com.pxp.checkout.components.paypal.types.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext

@Composable
fun CompletePayPalConfiguration(
    viewModel: PaymentViewModel
) {
    val context = LocalContext.current
    val isDebugBuild = BuildConfig.DEBUG
    
    val paypalConfig = remember {
        PayPalComponentConfig(
            // Basic configuration
            renderType = "standalone",
            fundingSources = "paypal",
            payeeEmailAddress = "merchant@example.com",
            paymentDescription = "Order payment",
            shippingPreference = "NoShipping",
            userAction = "PayNow",
            locale = "en-US",
            
            // Query parameters
            queryParams = PayPalQueryParams(
                buyerCountry = if (isDebugBuild) "US" else null,
                debug = isDebugBuild,
                integrationDate = "2025-07-01",
                merchantId = viewModel.getMerchantId()
            ),
            
            // Script parameters
            scriptParams = PayPalScriptParams(
                cspNonce = generateCSPNonce(),
                clientToken = viewModel.getClientToken(),
                pageType = "checkout",
                userIdToken = viewModel.getUserIdToken()
            ),
            
            // Enable one-click if user token is available
            enableOneClickPayment = viewModel.getUserIdToken() != null,
            
            // Event callbacks
            onSuccess = { data -> viewModel.handlePaymentSuccess(data) },
            onError = { error -> viewModel.handlePaymentError(error) },
            onCancel = { viewModel.handlePaymentCancel() }
        )
    }
    
    val paypalComponent = remember(paypalConfig) {
        pxpCheckout.createComponent(
            type = ComponentType.PAYPAL,
            config = paypalConfig
        )
    }
    
    pxpCheckout.buildComponentView(
        component = paypalComponent,
        modifier = Modifier.fillMaxWidth()
    )
}
```

## Best practices

### Use BuildConfig for environment-specific settings

Configure parameters based on your build variant to ensure debug settings don't leak into production:

```kotlin
queryParams = PayPalQueryParams(
    debug = BuildConfig.DEBUG,
    buyerCountry = if (BuildConfig.DEBUG) "US" else null
)
```

### Dynamically set page type

Track user flow by setting the appropriate `pageType` for each screen:

```kotlin
fun getPageTypeForScreen(screenName: String): String {
    return when (screenName) {
        "ProductList" -> "product-listing"
        "ProductDetail" -> "product-details"
        "Cart" -> "cart"
        "Checkout" -> "checkout"
        else -> "checkout"
    }
}
```

### Securely handle tokens

Never hardcode tokens or store them insecurely. Always retrieve them from secure storage or your backend:

```kotlin
scriptParams = PayPalScriptParams(
    userIdToken = secureStorage.getUserIdToken(), // From secure storage
    clientToken = viewModel.fetchClientToken() // From backend
)
```

### Log parameters in debug builds

Add logging to help with debugging during development:

```kotlin
val config = PayPalComponentConfig(
    queryParams = PayPalQueryParams(
        debug = BuildConfig.DEBUG
    ),
    scriptParams = PayPalScriptParams(
        pageType = pageType
    )
)

if (BuildConfig.DEBUG) {
    Log.d("PayPal", "Config - Debug: ${config.queryParams?.debug}")
    Log.d("PayPal", "Config - PageType: ${config.scriptParams?.pageType}")
    Log.d("PayPal", "Config - UserIdToken available: ${config.scriptParams?.userIdToken != null}")
}
```