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:
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.
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_credentialsclient_id: Your sandbox client IDclient_secret: Your sandbox client secret
- Add a HTTP Header Manager to this sampler, set:
- Key:
Content-Type - Value:
application/x-www-form-urlencoded
- Key:
- Method:
- 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
- Reference Name:
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})") }
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
- Key:
- Body Data:
{}(empty JSON object)
- Method:
- Add a JSON Extractor to pull
$.client_tokeninto 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") }
Now, in your Braintree GraphQL HTTP Request Sampler:
- Add a HTTP Header Manager and include:
- Key:
Authorization - Value:
Bearer ${braintree_bearer_token}
- Key:
- 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.
- 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
__encryptfunction 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

