This guide covers integrating Braintree with CoCart Preview API. Requires CoCart v4.6+ and a configured Braintree payment gateway.
Overview
Braintree integration with CoCart uses Hosted Fields for secure tokenization of payment data. This ensures sensitive card information never touches your server while providing PCI DSS SAQ A compliance and PayPal’s fraud protection. Braintree (owned by PayPal) supports multiple payment methods including credit cards, PayPal, Venmo, Apple Pay, and Google Pay.Prerequisites
Before implementing Braintree checkout, ensure you have:- Braintree payment gateway configured in WooCommerce
- Braintree JavaScript SDK (v3) loaded in your frontend
- A valid cart with items added
- Customer billing address information
- Braintree sandbox or production credentials
Integration Flow
1
Load Braintree SDK
Initialize the Braintree JavaScript SDK
2
Request Client Token
Obtain a client authorization token from your server
3
Initialize Hosted Fields
Create secure iframe-based payment input fields
4
Collect Payment Details
Securely collect card information from customers
5
Tokenize Payment Data
Generate a payment method nonce (temporary token)
6
Complete Checkout
Submit checkout with payment nonce to CoCart for processing
Step 1: Load Braintree SDK
Include the Braintree Web SDK in your checkout page:Step 2: Request Client Token
Request a client authorization token from CoCart:Step 3: HTML Structure
Create a checkout form with containers for Hosted Fields:Step 4: Initialize Braintree Client
Initialize the Braintree client with your authorization token:Step 5: Initialize Hosted Fields
Configure and create Hosted Fields for secure payment input:Step 6: Handle Form Submission
Process the checkout when the user submits the form:Step 7: Tokenize Payment Data
Request a payment method nonce from Braintree:Step 8: Process Checkout
Submit the checkout with tokenized payment data:Complete Integration Example
Here’s a complete working implementation:Styling Hosted Fields
Add CSS to style the Hosted Fields containers and validation states:Error Handling
Handle common Braintree error scenarios:Testing
For development and testing with Braintree:Test Card Numbers
Use these test cards in the sandbox environment:- Visa:
4111111111111111 - Visa (Declined):
4000111111111115 - MasterCard:
5555555555554444 - American Express:
378282246310005 - Discover:
6011111111111117 - JCB:
3530111333300000
Test Scenarios
- Any CVV: Use any 3-digit (or 4-digit for Amex) number
- Any Expiration: Use any future date
- Declined Transaction: Use card number ending in
0002 - Processor Declined: Use amount
2000.00or higher in cents
Testing 3D Secure
Best Practices
Security
- Always use Hosted Fields for tokenization
- Never store raw card data
- Use HTTPS for all requests
- Implement proper form validation
- Enable 3D Secure for high-value transactions
- Use device data collection for fraud detection
User Experience
- Show real-time field validation
- Display card brand icons
- Provide clear error messages
- Handle declined cards gracefully
- Support keyboard navigation
- Auto-focus next field when complete
Compliance
- Follow PCI DSS SAQ A guidelines
- Use Hosted Fields for PCI compliance
- Implement proper error handling
- Log transactions for auditing
- Test with various card types
- Include PayPal privacy notice
Performance
- Load SDK from CDN
- Use specific version numbers
- Cache client tokens appropriately
- Implement proper timeouts
- Handle network failures
- Monitor transaction success rates
Advanced Features
PayPal Integration
Add PayPal as an additional payment option:Venmo Integration
Add Venmo support for mobile users:Vaulting Payment Methods
Save customer payment methods for future use:Privacy Notice Requirement
Troubleshooting
Common Issues
Hosted Fields Not Loading
Hosted Fields Not Loading
Problem: Braintree Hosted Fields don’t appear on the page.Solution: Check these common issues:Common causes:
- Braintree SDK script not loaded or failed to load
- Invalid or expired client token
- Container elements missing from DOM
- CORS issues (check browser console)
- JavaScript errors preventing initialization
Tokenization Fails
Tokenization Fails
Problem: Getting errors when trying to tokenize card data.Solution: Debug the tokenization process:Verification steps:
- Ensure all required fields are filled
- Validate card number, expiration, CVV are correct
- Check for duplicate tokenization attempts
- Verify no JavaScript errors in console
3D Secure Authentication Not Working
3D Secure Authentication Not Working
Problem: 3D Secure modal doesn’t appear or fails.Solution: Ensure proper 3DS configuration:Common issues:
- Missing or invalid amount parameter
- Incomplete billing address
- Popup blockers preventing 3DS modal
- Test cards not triggering 3DS in sandbox
- Network timeout during verification
Styling Not Applied to Hosted Fields
Styling Not Applied to Hosted Fields
Problem: Custom styles not appearing on card fields.Solution: Verify style configuration:Important notes:
- Styles must be in the
stylesproperty at root level - Use CSS property names in kebab-case (e.g.,
'font-size') - Cannot use external stylesheets (security restriction)
- Test in multiple browsers as rendering may differ
- Some CSS properties are restricted for security
Payment Method Not Accepted
Payment Method Not Accepted
Problem: Backend doesn’t recognize Braintree payment method.Solution: Verify configuration:Checklist:
- Use
'braintree_credit_card'as payment_method - Verify Braintree gateway is active in WooCommerce
- Check Braintree credentials in WooCommerce settings
- Ensure nonce is fresh (expires after ~3 minutes)
- Include device_data if Advanced Fraud Tools enabled
Client Token Expired or Invalid
Client Token Expired or Invalid
Problem: “Authorization is invalid” or token expired errors.Solution: Generate fresh tokens:Notes:
- Client tokens typically last 24 hours
- Payment nonces expire after ~3 minutes
- Regenerate token if page has been open for extended period
- Always use fresh token for new sessions
Checkout Completes But Order Not Created
Checkout Completes But Order Not Created
Problem: Braintree payment succeeds but WooCommerce order fails.Solution: Debug checkout flow:Check these:
- Browser console for errors
- PHP error logs on server
- WooCommerce Status → Logs
- Braintree dashboard for transaction status
- Cart hasn’t been emptied prematurely
Network or CORS Errors
Network or CORS Errors
Problem: CORS errors or network failures when loading Braintree.Solution: Verify server configuration:Common causes:
- Firewall blocking Braintree endpoints
- Content Security Policy (CSP) restrictions
- Ad blockers interfering with payment scripts
- Invalid merchant ID or credentials
- Network proxy or VPN interference
Sandbox vs Production Issues
Sandbox vs Production Issues
Problem: Works in sandbox but fails in production.Solution: Verify production configuration:Pre-launch checklist:
- Switch to production credentials in WooCommerce
- Update Braintree merchant ID to production
- Enable production mode in Braintree settings
- Test with real card (small amount)
- Verify webhook URL is accessible from internet
- Enable production fraud protection
- Test 3D Secure with production cards
- Monitor first few transactions closely
Device Data Not Collecting
Device Data Not Collecting
Problem: Advanced Fraud Tools not working, device data missing.Solution: Properly initialize data collector:Notes:
- Device data improves fraud detection
- May increase page load time slightly
- Optional but recommended for production
- Check Braintree dashboard to verify data is being received
Debug Mode
Enable comprehensive logging for troubleshooting:- Go to WooCommerce → Settings → Payments → Braintree
- Enable “Debug mode” or “Logging”
- Check logs at WooCommerce → Status → Logs
Getting Help
If issues persist:- Braintree Support Portal: Visit Braintree Developer Documentation
- Braintree Community: Check Braintree Community Forums
- WooCommerce Logs: Review logs at WooCommerce → Status → Logs
- Braintree Dashboard: Monitor transactions and error logs in your Braintree account
- Browser Console: Always check for JavaScript errors and network issues
Always test your Braintree integration thoroughly using the sandbox environment before going live. Ensure your webhook endpoints are configured to handle transaction notifications and updates. Monitor your Braintree dashboard for declined transactions and implement appropriate retry logic.