Bouw een aangepaste Postman-integratie voor automatisering van externe API's
description
Maakt het mogelijk om complexe workflows met externe API's binnen Postman te automatiseren, waardoor handmatig werk en fouten worden verminderd. Biedt op maat gemaakte scripting- en integratieadviezen die zich aanpassen aan verschillende authenticatiemethoden en gegevensverwerking, iets wat bestaande prompts niet specifiek behandelen. Helpt gebruikers om API-interacties te stroomlijnen en herbruikbare geautomatiseerde processen te bouwen, wat de productiviteit en testdekking verbetert.
prompt
Help me een aangepaste integratieworkflow in Postman te bouwen voor het automatiseren van interacties met een externe API. Naam van de externe API: <voer de naam van de externe API in> Authenticatiemethode: <beschrijf de gebruikte authenticatiemethode, bijvoorbeeld OAuth2, API-sleutel> Belangrijke API-eindpunten: <lijst de hoofdeindpunten die je wilt automatiseren> Gegevensstroomvereis ...
try_prompt
generate_helper
disclaimerOnPageApi
tags
ai_answers
provider: openai
model: gpt-4.1-nano
Zeker! Hier is een stapsgewijze handleiding en de benodigde scripts om een aangepaste integratieworkflow in Postman te maken voor de Stripe API met OAuth2 client credentials authenticatie, inclusief foutafhandeling en e-mailmeldingen.
---
**1. Set-up OAuth2 Authenticatie in Postman**
- Ga naar je Postman-collectie of environment.
- Voeg een nieuwe environment toe, bijvoorbeeld `Stripe_env`.
- Voeg de volgende variabelen toe:
- `client_id` : jouw client ID
- `client_secret` : jouw client secret
- `access_token` : (wordt automatisch opgehaald)
- `token_expiry` : timestamp van token vervaltijd
- `fout_melding_email` : e-mail adres voor meldingen
**2. Maak een OAuth2 Token Request**
- Voeg een nieuwe request toe: `Get OAuth2 Token`.
- Method: POST
- URL: `https://connect.stripe.com/oauth/token`
- Body (x-www-form-urlencoded):
| Key | Value |
|-----------------|------------------------|
| grant_type | client_credentials |
| client_id | {{client_id}} |
| client_secret | {{client_secret}} |
- Verzoek sturen en het access token opslaan:
**Pre-request script:**
```javascript
// Check of token nog geldig is
if (!pm.environment.get('access_token') ||
(pm.environment.get('token_expiry') && Date.now() > pm.environment.get('token_expiry'))) {
// Token ophalen
pm.sendRequest({
url: 'https://connect.stripe.com/oauth/token',
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {
mode: 'urlencoded',
urlencoded: [
{ key: 'grant_type', value: 'client_credentials' },
{ key: 'client_id', value: pm.environment.get('client_id') },
{ key: 'client_secret', value: pm.environment.get('client_secret') }
]
}
}, function (err, res) {
if (err || res.code !== 200) {
console.error('OAuth token ophalen mislukt:', err || res);
// Mogelijkheid tot e-mail notificatie
// (Zie onderaan voor script)
return;
}
const json = res.json();
pm.environment.set('access_token', json.access_token);
// Stel vervaltijd in (bijvoorbeeld 1 uur)
const expiry = Date.now() + (json.expires_in * 1000);
pm.environment.set('token_expiry', expiry);
});
}
```
---
**3. API Requests: `/customers` en `/charges`**
Voor beide endpoints maak je een nieuwe request:
- URL: `https://api.stripe.com/v1/` + endpoint
- Method: GET
- Headers:
```plaintext
Authorization: Bearer {{access_token}}
```
**4. Automatische invoer van klant-ID in `/charges`**
In de `/charges` request:
- Gebruik de klant-ID uit `/customers` response (bijvoorbeeld opgeslagen in variabele `customer_id`).
- Stel een variabele in na `/customers`:
**Test script na `/customers` request:**
```javascript
if (pm.response.code === 200) {
const json = pm.response.json();
// Neem bijvoorbeeld eerste klant ID
if (json.data && json.data.length > 0) {
pm.environment.set('customer_id', json.data[0].id);
}
}
```
- In `/charges` request zet je de klant-ID in de body of URL:
```plaintext
?customer={{customer_id}}
```
---
**5. Foutafhandeling en herhaalpoging**
Voor elke API request:
**Test script:**
```javascript
if (pm.response.code >= 400) {
console.error('Fout bij API verzoek:', pm.response.code, pm.response.body);
// Log fout, probeer één keer opnieuw
if (!pm.variables.get('retry_attempt')) {
pm.variables.set('retry_attempt', '1');
// Herhaal request
postman.setNextRequest(pm.info.requestName);
} else {
// Fout herhaald, geen verdere pogingen
pm.variables.unset('retry_attempt');
// Mogelijkheid tot e-mail notificatie
// (Zie onderaan)
}
} else {
pm.variables.unset('retry_attempt');
}
```
**6. E-mail notificatie bij fouten**
In Postman zelf kan je geen e-mails sturen, maar je kan dit doen via een externe service zoals SendGrid of via een webhook.
Bijvoorbeeld, voeg in een `Test` script onder je API request:
```javascript
if (pm.response.code >= 400) {
// Verstuur e-mail via webhook of externe API
const emailWebhookUrl = 'https://your-email-service.com/send';
pm.sendRequest({
url: emailWebhookUrl,
method: 'POST',
header: {
'Content-Type': 'application/json'
},
body: {
mode: 'raw',
raw: JSON.stringify({
to: pm.environment.get('fout_melding_email'),
subject: 'Stripe API Foutmelding',
message: `Foutcode: ${pm.response.code}\nResponse: ${pm.response.body}`
})
}
});
}
```
---
**7. Automatiseringsflow overzicht**
- Start met `Get OAuth2 Token` request.
- Gebruik de `access_token` en `token_expiry` uit environment.
- Voer `/customers` request uit:
- Sla klant-ID op.
- Voer `/charges` request uit:
- Gebruik opgeslagen klant-ID.
- Bij fouten:
- Log en probeer één keer opnieuw.
- Indien na herhaling nog fout, stuur een e-mailmelding.
---
**Opmerking:** Voor volledige automatisering moet je mogelijk je request flow in een Postman Collection automatiseren en met `setNextRequest` werken om de flow te beheersen.
---
**Samenvatting**
Deze setup bevat:
- OAuth2 token management met caching en vervaltijd.
- Automatisch ophalen van klant-ID en hergebruik in `/charges`.
- Foutafhandeling met één herhaalpoging.
- E-mail notificatie bij fouten via externe webhook.
Je kunt deze scripts en setup direct toepassen in Postman en aanpassen aan je specifieke behoeften.
---
Heb je nog aanvullende vragen of hulp nodig bij het instellen?
provider: deepseek
model: deepseek-chat
Hier is een complete Postman setup voor je Stripe API integratieworkflow:
## 1. Postman Environment Variabelen
Maak een nieuwe environment aan met deze variabelen:
```javascript
{
"stripe_base_url": "https://api.stripe.com/v1",
"client_id": "uw_stripe_client_id",
"client_secret": "uw_stripe_client_secret",
"access_token": "",
"customer_id": "",
"last_error": "",
"notification_email": "uw-email@voorbeeld.nl"
}
```
## 2. Pre-request Script voor OAuth2 Token
**Script naam:** `Get OAuth2 Token`
```javascript
// Pre-request script voor OAuth2 authenticatie
const clientId = pm.environment.get("client_id");
const clientSecret = pm.environment.get("client_secret");
const tokenUrl = "https://connect.stripe.com/oauth/token";
const getTokenRequest = {
url: tokenUrl,
method: "POST",
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: {
mode: "urlencoded",
urlencoded: [
{ key: "grant_type", value: "client_credentials" },
{ key: "client_id", value: clientId },
{ key: "client_secret", value: clientSecret }
]
}
};
pm.sendRequest(getTokenRequest, function (err, response) {
if (!err && response.code === 200) {
const token = response.json().access_token;
pm.environment.set("access_token", token);
console.log("OAuth2 token succesvol verkregen");
} else {
console.error("Fout bij ophalen OAuth2 token:", err ? err.message : response.json());
pm.environment.set("last_error", "OAuth2 authenticatie mislukt");
}
});
```
## 3. Collection Workflow
### Request 1: Create Customer
**Method:** POST
**URL:** `{{stripe_base_url}}/customers`
**Headers:**
```
Authorization: Bearer {{access_token}}
Content-Type: application/x-www-form-urlencoded
```
**Body (form-data):**
```javascript
{
"email": "klant@voorbeeld.nl",
"name": "Test Klant",
"description": "Test klant voor integratie"
}
```
**Tests Script voor Create Customer:**
```javascript
// Verwerk response en sla customer ID op
if (pm.response.code === 200) {
const responseData = pm.response.json();
pm.environment.set("customer_id", responseData.id);
console.log("Customer aangemaakt met ID:", responseData.id);
pm.test("Customer succesvol aangemaakt", function () {
pm.expect(pm.response.code).to.equal(200);
pm.expect(responseData.id).to.not.be.undefined;
});
} else {
const errorMsg = `Customer aanmaken mislukt: ${pm.response.code} - ${pm.response.text()}`;
pm.environment.set("last_error", errorMsg);
console.error(errorMsg);
// Voer retry logica uit
handleErrorWithRetry("Create Customer", pm.request, pm.response);
}
```
### Request 2: Create Charge
**Method:** POST
**URL:** `{{stripe_base_url}}/charges`
**Headers:**
```
Authorization: Bearer {{access_token}}
Content-Type: application/x-www-form-urlencoded
```
**Body (form-data):**
```javascript
{
"amount": "2000", // 20.00 EUR in centen
"currency": "eur",
"customer": "{{customer_id}}",
"description": "Test betaling voor klant {{customer_id}}"
}
```
**Tests Script voor Create Charge:**
```javascript
// Verwerk charge response
if (pm.response.code === 200) {
const responseData = pm.response.json();
console.log("Charge succesvol aangemaakt:", responseData.id);
pm.test("Charge succesvol verwerkt", function () {
pm.expect(pm.response.code).to.equal(200);
pm.expect(responseData.status).to.equal("succeeded");
});
} else {
const errorMsg = `Charge aanmaken mislukt: ${pm.response.code} - ${pm.response.text()}`;
pm.environment.set("last_error", errorMsg);
console.error(errorMsg);
// Voer retry logica uit
handleErrorWithRetry("Create Charge", pm.request, pm.response);
}
```
## 4. Globale Foutafhandeling Scripts
### Collection-level Pre-request Script:
```javascript
// Initialiseer retry counter als deze niet bestaat
if (!pm.collectionVariables.get("retry_count")) {
pm.collectionVariables.set("retry_count", 0);
}
```
### Collection-level Tests Script:
```javascript
// Globale foutafhandeling met retry logica
function handleErrorWithRetry(operation, request, response) {
const maxRetries = 1;
let retryCount = parseInt(pm.collectionVariables.get("retry_count") || 0);
if (retryCount < maxRetries) {
console.log(`Retry poging ${retryCount + 1} voor ${operation}`);
pm.collectionVariables.set("retry_count", retryCount + 1);
// Wacht 2 seconden voordat retry wordt uitgevoerd
setTimeout(() => {
pm.sendRequest(request, function (err, res) {
if (err || res.code !== 200) {
// Als retry ook mislukt, stuur e-mailmelding
sendErrorNotification(operation, err ? err.message : res.text());
}
});
}, 2000);
} else {
// Stuur e-mailmelding bij definitieve fout
sendErrorNotification(operation, response.text());
}
}
// E-mail notificatie functie (vereist Postman monitoring)
function sendErrorNotification(operation, errorDetails) {
const notificationEmail = pm.environment.get("notification_email");
const errorMessage = `Fout in Stripe integratie:
Operation: ${operation}
Tijd: ${new Date().toISOString()}
Fout details: ${errorDetails}
Customer ID: ${pm.environment.get("customer_id") || 'N/A'}`;
// Postman native e-mail (vereist Postman Pro/Enterprise)
pm.sendRequest({
url: 'https://api.postman.com/notifications',
method: 'POST',
header: {
'Content-Type': 'application/json',
'X-API-Key': 'uw_postman_api_key'
},
body: {
mode: 'raw',
raw: JSON.stringify({
to: notificationEmail,
subject: `Stripe API Fout - ${operation}`,
text: errorMessage
})
}
});
console.log(`E-mail notificatie verzonden voor: ${operation}`);
}
// Reset retry counter bij succesvolle requests
if (pm.response.code === 200) {
pm.collectionVariables.set("retry_count", 0);
}
```
## 5. Workflow Automation
### Collection Runner Configuratie:
```javascript
{
"iterationCount": 1,
"delay": 1000,
"persistGlobals": false,
"data": [],
"environment": {
"stripe_base_url": "https://api.stripe.com/v1",
"client_id": "uw_client_id",
"client_secret": "uw_client_secret",
"notification_email": "uw-email@voorbeeld.nl"
},
"globals": {},
"folder": "",
"timeout": 0
}
```
## Implementatiestappen:
1. **Importeer** deze requests in een nieuwe Postman collection
2. **Configureer** de environment variabelen met je Stripe credentials
3. **Test** individueel elke request
4. **Voer** de complete workflow uit via Collection Runner
5. **Monitor** fouten via de console logs en e-mailnotificaties
Deze setup zorgt voor automatische OAuth2 authenticatie, foutafhandeling met één retry poging, en e-mailnotificaties bij permanente fouten.