Skip to content

Instantly share code, notes, and snippets.

@jeancroy
Created June 25, 2016 19:26
Show Gist options
  • Save jeancroy/c71f8a710734a7d13248f968c778d428 to your computer and use it in GitHub Desktop.
Save jeancroy/c71f8a710734a7d13248f968c778d428 to your computer and use it in GitHub Desktop.
public static T HttpUploadFile<T>(string url, string fileName, byte[] fileBytes, string fileContentType = null, string fileFieldName = "file", Dictionary<string, string> extraFields = null)
where T : class
{
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
var boundary = "Upload----" + DateTime.UtcNow.Ticks.ToString("x");
var multiPartContent = new MultipartFormDataContent(boundary);
//Add parameters
if(extraFields != null) {
foreach (var field in extraFields)
{
multiPartContent.Add(new StringContent(field.Value), '"' + field.Key + '"'); //Extra quotes are needed for stripe API
}
}
//Add file upload
var byteContent = new ByteArrayContent(fileBytes);
byteContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = '"' + fileName + '"',
Name = '"' + fileFieldName + '"' //Extra quotes are needed for stripe API
};
if(!string.IsNullOrEmpty(fileContentType))
byteContent.Headers.ContentType = new MediaTypeHeaderValue(fileContentType);
multiPartContent.Add(byteContent);
//Set content
request.Content = multiPartContent;
//Add Authorization Header
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", StripeSecretKey);
//
// Handle response
//
var response = client.SendAsync(request).Result;
var responseFromServer = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
return JsonConvert.DeserializeObject<T>(responseFromServer);
throw CustomStripeApi.BuildStripeException(response.StatusCode, responseFromServer);
}
public static DocumentUpload UploadIdentityPhoto(IdentityPhoto idPhoto)
{
var fields = new Dictionary<string, string>() { { "purpose", "identity_document" } };
try
{
return HttpUploadFile<DocumentUpload>(
url: "https://uploads.stripe.com/v1/files",
fileName: idPhoto.FileNameWithExtension,
fileBytes: idPhoto.Content,
fileContentType: idPhoto.ContentType,
fileFieldName: "file", extraFields: fields);
}
catch(StripeException ex){
//Log error
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment