# App-to-App Integration Guide for Third Party Developers

## Overview

This document provides comprehensive guidance for third-party developers who want to integrate with the Shukria Payment Application through App-to-App calls. The payment application provides a dedicated `ThirdActivity` that serves as the entry point for external applications to initiate payment transactions.

## Integration Methods

The payment application supports two primary integration methods:

### 1. URI-based Integration
Use custom URI schemes to launch the payment application with transaction parameters.

### 2. Bundle-based Integration  
Use Android Intent extras (Bundle) to pass transaction parameters directly.

## URI-Based Integration

### URI Scheme Configuration
The payment application is configured to respond to the following URI scheme:
```
shukria://acquire/transaction
```

### Basic URI Integration Example
```java
Intent intent = new Intent();
intent.setData(Uri.parse("shukria://acquire/transaction?transType=Sale&amount=1000&outOrderNo=20210425001"));
intent.setAction("android.intent.action.SHUKRIA.PAYMENT.URI");
startActivity(intent);
```

### URI Parameters
You can pass the following parameters via URI query parameters:

| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `transType` | String | Transaction type (Sale, Refund, Balance, etc.) | `Sale` |
| `amount` | Long | Transaction amount in cents | `1000` (for $10.00) |
| `tip` | Long | Tip amount in cents | `200` (for $2.00) |
| `outOrderNo` | String | External order number for reference | `ORDER123456` |
| `remark` | String | Transaction remark/notes | `Customer purchase` |
| `payCode` | String | Payment QR code (if applicable) | `QR_CODE_STRING` |

### Complete URI Example
```java
String uriString = "shukria://acquire/transaction?" +
    "transType=Sale&" +
    "amount=1500&" +
    "tip=300&" +
    "outOrderNo=ORD001&" +
    "remark=Coffee Purchase";

Intent intent = new Intent();
intent.setData(Uri.parse(uriString));
intent.setAction("android.intent.action.SHUKRIA.PAYMENT.URI");
startActivity(intent);
```

## Bundle-Based Integration

### Basic Bundle Integration Example
```java
Intent intent = new Intent();
intent.putExtra("transType", "Sale");
intent.putExtra("amount", 1500L);  // Amount in cents
intent.putExtra("tip", 300L);      // Tip in cents  
intent.putExtra("outOrderNo", "ORDER123456");
intent.putExtra("remark", "Customer purchase");
intent.setAction("android.intent.action.SHUKRIA.PAYMENT");
intent.setPackage("com.newland.template"); // Replace with actual package name
startActivityForResult(intent, REQUEST_CODE);
```

### Bundle Parameters
All parameters from the URI method can be used as Intent extras:

```java
Intent intent = new Intent();
intent.putExtra(TransTag.TRANS_TYPE, "Sale");
intent.putExtra(TransTag.AMOUNT, 1500L);
intent.putExtra(TransTag.TIP, 300L);
intent.putExtra(TransTag.OUT_ORDER_NO, "ORDER123456");
intent.putExtra(TransTag.REMARK, "Coffee and pastry");
intent.setAction("android.intent.action.SHUKRIA.PAYMENT");
intent.setPackage("YOUR_PAYMENT_APP_PACKAGE");
startActivityForResult(intent, REQUEST_CODE);
```

## Transaction Types

The following transaction types are supported:

| Transaction Type | Description |
|------------------|-------------|
| `Sale` | Standard payment transaction |
| `Refund` | Refund a previous transaction |
| `VoidSale` | Void a sale transaction |
| `Balance` | Check card balance |
| `Topup` | Add funds to account |
| `PreAuth` | Pre-authorization |
| `VoidPreAuth` | Void pre-authorization |
| `AuthComplete` | Complete pre-authorization |
| `VoidAuthComplete` | Void auth completion |

## Response Handling

### Response Codes
The payment application returns the following result codes:

| Code | Value | Description |
|------|-------|-------------|
| `THIRD_OK` | 2700 | Transaction successful |
| `THIRD_FAIL` | 2701 | Transaction failed |
| `THIRD_CANCEL` | 2702 | Transaction cancelled by user |

For legacy compatibility, the application also supports standard result codes:
- `OK` - Success
- `FL` - Failed  
- `UC` - User cancelled

### Handling Results
```java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    
    if (requestCode == REQUEST_CODE && data != null) {
        String resultCode = data.getStringExtra("resultCode");
        String message = data.getStringExtra("message");
        
        switch (resultCode) {
            case "2700": // THIRD_OK
                // Transaction successful
                handleSuccessfulTransaction(data);
                break;
            case "2701": // THIRD_FAIL
                // Transaction failed
                handleFailedTransaction(message);
                break;
            case "2702": // THIRD_CANCEL
                // Transaction cancelled
                handleCancelledTransaction();
                break;
        }
    }
}
```

### Response Data Fields
Successful transactions return the following data:

| Field | Type | Description |
|-------|------|-------------|
| `resultCode` | String | Result code (2700, 2701, 2702) |
| `message` | String | Result message |
| `mid` | String | Merchant ID |
| `tid` | String | Terminal ID |
| `cardNo` | String | Masked card number |
| `traceNo` | String | Transaction trace number |
| `batchNo` | String | Batch number |
| `authCode` | String | Authorization code |
| `referenceNo` | String | Reference number |
| `organization` | String | Card organization |
| `amount` | Long | Transaction amount in cents |
| `tip` | Long | Tip amount in cents |
| `balance` | Long | Remaining balance (if applicable) |

## Error Handling and Edge Cases

### Duplicate Transaction Prevention
The payment application includes built-in protection against duplicate transactions. If a transaction is already in progress, subsequent calls will be rejected with an error message.

### Screen and Button Control  
During transaction processing, the payment application:
- Keeps the screen on to prevent timeout
- Disables the home and task buttons to prevent interruption
- Handles back button presses to prevent accidental cancellation

### Logging and Debugging
All third-party calls are logged for debugging purposes. You can identify your transactions in logs by the "ThirdCall>>" prefix.

## Integration Checklist

### Before Integration:
1. ✅ Determine the payment app package name
2. ✅ Choose integration method (URI vs Bundle)
3. ✅ Define your transaction parameters
4. ✅ Set up result handling in your app

### URI Integration:
1. ✅ Construct proper URI with required parameters
2. ✅ Set correct intent action: `android.intent.action.SHUKRIA.PAYMENT.URI`
3. ✅ Handle the response appropriately

### Bundle Integration:
1. ✅ Add required extras to intent
2. ✅ Set correct intent action: `android.intent.action.SHUKRIA.PAYMENT`
3. ✅ Set target package name
4. ✅ Use `startActivityForResult()` for response handling

## Sample Implementation

### Complete Example - Bundle Method
```java
public class PaymentIntegrationActivity extends AppCompatActivity {
    private static final int PAYMENT_REQUEST_CODE = 1001;
    
    private void initiatePayment() {
        Intent intent = new Intent();
        intent.putExtra("transType", "Sale");
        intent.putExtra("amount", 2500L); // $25.00
        intent.putExtra("tip", 375L);     // $3.75
        intent.putExtra("outOrderNo", "ORDER_" + System.currentTimeMillis());
        intent.putExtra("remark", "Mobile app purchase");
        
        intent.setAction("android.intent.action.SHUKRIA.PAYMENT");
        intent.setPackage("com.newland.template"); // Replace with actual package
        
        try {
            startActivityForResult(intent, PAYMENT_REQUEST_CODE);
        } catch (ActivityNotFoundException e) {
            // Payment app not installed
            showError("Payment app not found. Please install the payment application.");
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == PAYMENT_REQUEST_CODE) {
            if (data != null && data.getExtras() != null) {
                String transactionResult = data.getStringExtra("resultCode");
                String message = data.getStringExtra("message");
                
                switch (transactionResult) {
                    case "2700": // Success
                        String authCode = data.getStringExtra("authCode");
                        String traceNo = data.getStringExtra("traceNo");
                        handlePaymentSuccess(authCode, traceNo, message);
                        break;
                        
                    case "2701": // Failed
                        handlePaymentFailure(message);
                        break;
                        
                    case "2702": // Cancelled
                        handlePaymentCancelled();
                        break;
                        
                    default:
                        handleUnknownResult(transactionResult, message);
                        break;
                }
            } else {
                handlePaymentError("No response data received");
            }
        }
    }
    
    private void handlePaymentSuccess(String authCode, String traceNo, String message) {
        // Handle successful payment
        Log.i("Payment", "Success: AuthCode=" + authCode + ", Trace=" + traceNo);
        showSuccess("Payment successful!\nAuth Code: " + authCode);
    }
    
    private void handlePaymentFailure(String message) {
        // Handle payment failure
        Log.e("Payment", "Failed: " + message);
        showError("Payment failed: " + message);
    }
    
    private void handlePaymentCancelled() {
        // Handle payment cancellation
        Log.i("Payment", "Payment cancelled by user");
        showInfo("Payment was cancelled");
    }
}
```

### Complete Example - URI Method
```java
private void initiatePaymentViaURI() {
    String uriString = "shukria://acquire/transaction?" +
        "transType=Sale&" +
        "amount=2500&" +
        "tip=375&" +
        "outOrderNo=ORDER_" + System.currentTimeMillis() + "&" +
        "remark=" + URLEncoder.encode("Mobile app purchase", "UTF-8");
    
    Intent intent = new Intent();
    intent.setData(Uri.parse(uriString));
    intent.setAction("android.intent.action.SHUKRIA.PAYMENT.URI");
    
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        showError("Payment app not found. Please install the payment application.");
    }
}
```

## Security Considerations

1. **Validate Responses**: Always validate response data before processing
2. **Amount Handling**: Amounts are in cents to avoid floating-point precision issues
3. **Order Numbers**: Use unique order numbers to prevent duplicate processing
4. **Package Verification**: Verify the payment app package signature if security is critical
5. **Network Security**: The payment app handles all network communications securely

## Testing and Validation

### Test Scenarios:
1. ✅ Successful payment transaction
2. ✅ Failed payment (insufficient funds, card declined)
3. ✅ User cancellation during transaction
4. ✅ Payment app not installed
5. ✅ Invalid parameters
6. ✅ Network connectivity issues
7. ✅ Duplicate transaction attempts

### Common Issues:
- **App not found**: Payment application not installed
- **Invalid parameters**: Check parameter names and data types
- **No response**: Ensure proper result handling in `onActivityResult()`
- **Package name**: Verify correct target package name

## Support and Troubleshooting

### Debug Information:
- All transactions are logged with "ThirdCall>>" prefix
- Check device logs for detailed error information
- Verify intent filters and package names

### Contact Information:
For integration support and technical questions, please contact the payment application development team.

---

**Note**: This integration guide is based on the ThirdActivity implementation in the payment application. Always test thoroughly in a development environment before deploying to production.
