You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Braintree支付沙箱令牌生成及JMeter性能脚本传参解决方案咨询

Got it, let's walk through solving this Braintree token problem for your JMeter performance tests— I’ve tackled similar scenarios before, so here’s a practical, step-by-step breakdown:

1. First, Understand the Token Flow

Braintree’s GraphQL sandbox requires an Auth Bearer Token for authentication, which you get via their OAuth 2.0 endpoint. For client tokens (used in frontend integrations), you’ll need to call their merchant API with your sandbox credentials. Let’s start with the Bearer Token since that’s what you need for GraphQL requests.

2. Generate Auth Bearer Token in JMeter

I recommend two approaches— pick the one that fits your workflow:

Option 1: Simple HTTP Sampler + JSON Extractor (No Code Needed)

This is the easiest way for most cases:

  • Add an HTTP Request Sampler to your test plan, configure it like this:
    • Method: POST
    • URL: https://auth.sandbox.braintreegateway.com/oauth2/token
    • Under "Parameters" tab, add these key-value pairs (x-www-form-urlencoded):
      • grant_type: client_credentials
      • client_id: Your sandbox client ID
      • client_secret: Your sandbox client secret
    • Add a HTTP Header Manager to this sampler, set:
      • Key: Content-Type
      • Value: application/x-www-form-urlencoded
  • Next, add a JSON Extractor as a child of this sampler to pull out the token:
    • Reference Name: braintree_bearer_token
    • JSON Path Expression: $.access_token
    • Match No.: 1

Now the token is stored in ${braintree_bearer_token} for use in later requests.

Option 2: JSR223 Sampler (Groovy) for Custom Logic

If you need flexibility (like retries, logging, or dynamic credential handling), use Groovy (it’s faster than BeanShell):

  • Add a JSR223 Sampler and paste this code, replacing the placeholder credentials:
import groovy.json.JsonSlurper
import java.net.URLEncoder

// Sandbox OAuth token endpoint
def tokenUrl = "https://auth.sandbox.braintreegateway.com/oauth2/token"

// Replace with your sandbox credentials
def clientId = "YOUR_SANDBOX_CLIENT_ID"
def clientSecret = "YOUR_SANDBOX_CLIENT_SECRET"

// Build form data for request
def formData = [
    grant_type: "client_credentials",
    client_id: clientId,
    client_secret: clientSecret
].collect { k, v -> "${URLEncoder.encode(k, 'UTF-8')}=${URLEncoder.encode(v, 'UTF-8')}" }.join('&')

// Send POST request
def connection = new URL(tokenUrl).openConnection()
connection.setRequestMethod("POST")
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
connection.setDoOutput(true)
connection.getOutputStream().write(formData.getBytes("UTF-8"))

// Handle response
def responseCode = connection.getResponseCode()
if (responseCode == 200) {
    def responseBody = connection.getInputStream().text
    def json = new JsonSlurper().parseText(responseBody)
    def bearerToken = json.access_token
    
    // Store token in JMeter variable
    vars.put("braintree_bearer_token", bearerToken)
    log.info("Successfully fetched Braintree Bearer Token: ${bearerToken.take(20)}...")
} else {
    def errorBody = connection.getErrorStream().text
    log.error("Token fetch failed! Response code: ${responseCode}, Error: ${errorBody}")
    throw new Exception("Failed to retrieve Braintree token (code ${responseCode})")
}
3. Generate Client Token (If Required)

If your test needs a client token (for frontend-like flows), use this approach:

  • Add an HTTP Request Sampler with:
    • Method: POST
    • URL: https://api.sandbox.braintreegateway.com/merchants/YOUR_MERCHANT_ID/client_token
    • Add a HTTP Header Manager with:
      • Key: Authorization
      • Value: Basic ${base64_credentials} (encode your public key + private key as Base64: public_key:private_key → base64 string)
      • Key: Content-Type
      • Value: application/json
    • Body Data: {} (empty JSON object)
  • Add a JSON Extractor to pull $.client_token into a variable like ${braintree_client_token}.

Or use Groovy to handle the Base64 encoding automatically:

import groovy.json.JsonSlurper

def merchantId = "YOUR_MERCHANT_ID"
def publicKey = "YOUR_PUBLIC_KEY"
def privateKey = "YOUR_PRIVATE_KEY"

// Encode credentials for Basic Auth
def authString = "${publicKey}:${privateKey}"
def encodedAuth = authString.bytes.encodeBase64().toString()

def clientTokenUrl = "https://api.sandbox.braintreegateway.com/merchants/${merchantId}/client_token"

def connection = new URL(clientTokenUrl).openConnection()
connection.setRequestMethod("POST")
connection.setRequestProperty("Authorization", "Basic ${encodedAuth}")
connection.setRequestProperty("Content-Type", "application/json")
connection.setDoOutput(true)
connection.getOutputStream().write("{}".getBytes("UTF-8"))

def responseCode = connection.getResponseCode()
if (responseCode == 200) {
    def responseBody = connection.getInputStream().text
    def json = new JsonSlurper().parseText(responseBody)
    vars.put("braintree_client_token", json.client_token)
    log.info("Client token generated successfully")
} else {
    def errorBody = connection.getErrorStream().text
    log.error("Client token fetch failed: ${errorBody}")
    throw new Exception("Failed to get client token")
}
4. Use Tokens in Your GraphQL Request

Now, in your Braintree GraphQL HTTP Request Sampler:

  • Add a HTTP Header Manager and include:
    • Key: Authorization
    • Value: Bearer ${braintree_bearer_token}
  • Ensure this sampler runs after the token generation samplers— JMeter executes elements in order, so the variable will be populated when the GraphQL request runs.
5. Performance Testing Best Practices
  • Token Expiry: Braintree’s Bearer Tokens typically expire after 1 hour. Add logic to refresh them: use an If Controller to check if the token is still valid (or re-generate it every 50 minutes with a Loop Controller).
  • Secure Credentials: Never hardcode credentials in your script. Use JMeter’s User Defined Variables or encrypted properties (use the __encrypt function to secure sensitive data).
  • Error Handling: Add Response Assertions to verify token retrieval succeeds, and set up retry logic (e.g., a Loop Controller with a condition to retry if the token fetch fails).

内容的提问来源于stack exchange,提问作者Manav Chopra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:37:57