import os
import requests
response = requests.post(
"https://api.stripe.com/v1/refunds",
headers={
"Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}",
"Content-Type": "application/x-www-form-urlencoded"
},
data={
"charge": "ch_1234567890",
"amount": "1000"
}
)
if response.status_code >= 400:
raise Exception(f"Request failed with status {response.status_code}: {response.text}")
print(response.json())
import os
import httpx
with httpx.Client() as client:
response = client.post(
"https://api.stripe.com/v1/refunds",
headers={
"Authorization": f"Bearer {os.environ['STRIPE_SECRET_KEY']}",
"Content-Type": "application/x-www-form-urlencoded"
},
data={
"charge": "ch_1234567890",
"amount": "1000"
}
)
if response.status_code >= 400:
raise Exception(f"Request failed with status {response.status_code}: {response.text}")
print(response.json())
import fetch from 'node-fetch';
import { env } from 'process';
const response = await fetch('https://api.stripe.com/v1/refunds', {
method: 'POST',
headers: {
'Authorization': `Bearer ${env.STRIPE_SECRET_KEY}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
charge: 'ch_1234567890',
amount: '1000'
})
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}: ${await response.text()}`);
}
console.log(await response.json());
import axios from 'axios';
import { env } from 'process';
const response = await axios.post('https://api.stripe.com/v1/refunds', new URLSearchParams({
charge: 'ch_1234567890',
amount: '1000'
}), {
headers: {
'Authorization': `Bearer ${env.STRIPE_SECRET_KEY}`,
'Content-Type': 'application/x-www-form-urlencoded'
}
});
if (response.status >= 400) {
throw new Error(`Request failed with status ${response.status}: ${response.statusText}`);
}
console.log(response.data);
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
)
func main() {
client := &http.Client{}
form := url.Values{}
form.Add("charge", "ch_1234567890")
form.Add("amount", "1000")
req, err := http.NewRequest(
"POST",
"https://api.stripe.com/v1/refunds",
strings.NewReader(form.Encode()),
)
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("STRIPE_SECRET_KEY"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(resp.Body)
panic(fmt.Sprintf("Request failed with status %d: %s", resp.StatusCode, string(body)))
}
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/refunds');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'charge' => 'ch_1234567890',
'amount' => '1000'
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . getenv('STRIPE_SECRET_KEY'),
'Content-Type: application/x-www-form-urlencoded'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
throw new Exception("Request failed with status $httpCode: $response");
}
print_r(json_decode($response, true));
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse('https://api.stripe.com/v1/refunds')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "Bearer #{ENV['STRIPE_SECRET_KEY']}"
request['Content-Type'] = 'application/x-www-form-urlencoded'
request.set_form_data({
charge: 'ch_1234567890',
amount: '1000'
})
response = http.request(request)
if response.code.to_i >= 400
raise "Request failed with status #{response.code}: #{response.body}"
end
puts JSON.parse(response.body)
import Foundation
let url = URL(string: "https://api.stripe.com/v1/refunds")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["STRIPE_SECRET_KEY"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let body = "charge=ch_1234567890&amount=1000"
request.httpBody = body.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
fatalError("Request failed: \(error?.localizedDescription ?? "Unknown error")")
}
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 400 {
fatalError("Request failed with status \(httpResponse.statusCode): \(String(data: data, encoding: .utf8) ?? "")")
}
if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
}
task.resume()
RunLoop.main.run()
use std::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::header;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new();
let mut headers = header::HeaderMap::new();
headers.insert(
"Authorization",
format!("Bearer {}", env::var("STRIPE_SECRET_KEY")?).parse()?,
);
headers.insert(
"Content-Type",
"application/x-www-form-urlencoded".parse()?,
);
let mut form = HashMap::new();
form.insert("charge", "ch_1234567890");
form.insert("amount", "1000");
let response = client
.post("https://api.stripe.com/v1/refunds")
.headers(headers)
.form(&form)
.send()?;
if !response.status().is_success() {
return Err(format!(
"Request failed with status {}: {}",
response.status(),
response.text()?
).into());
}
println!("{:?}", response.json::<serde_json::Value>()?);
Ok(())
}
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var client = new HttpClient();
var formData = new Dictionary<string, string>
{
{"charge", "ch_1234567890"},
{"amount", "1000"}
};
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.stripe.com/v1/refunds")
{
Content = new FormUrlEncodedContent(formData)
};
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
"Bearer",
Environment.GetEnvironmentVariable("STRIPE_SECRET_KEY")
);
var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
var errorContent = await response.Content.ReadAsStringAsync();
throw new Exception($"Request failed with status {response.StatusCode}: {errorContent}");
}
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}