Nil
Nil

Reputation: 139

Stripe 401 - No valid API key provided - C#

I get following error: "The remote server returned an error: (401) Unauthorized" in this line:

using (HttpWebResponse httpResponse = request.GetResponse() as HttpWebResponse) {}

Here is the complete code:

string clientSecretKey = ConfigurationManager.AppSettings["ClientSecretKey"];

const string ChargeUrl = "https://api.stripe.com/v1/charges?amount={0}&currency={1}&source={2}&description={3}"; 
string requestUrl = HttpUtility.UrlPathEncode(
String.Format(ChargeUrl, 1000, "usd", "tok_19xLu8HN9aKw9vrkUsflNWOI", "Test charge to [email protected]") );
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; 

request.Headers.Add("Authorization", "sk_test_example"); 
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";

using (HttpWebResponse httpResponse = request.GetResponse() as HttpWebResponse)
{/* some code */} 

At the beginning I thought the error was caused because the token can't used more than one time, but I changed it and got the same error. I'm not sure what is causing the error.

Upvotes: 2

Views: 2923

Answers (2)

Jake T.
Jake T.

Reputation: 4378

You're initializing a variable for the secret key but not using it. Try modifying the request url to start with "https://" + clientSecretKey + ":@api..."

This is, of course, assuming clientSecretKey is the Stripe key.

Be careful putting a secret key somewhere on your server that it isn't hidden from a user / client.

Upvotes: 1

koopajah
koopajah

Reputation: 25552

The issue here is that you are passing the API key but not using Bearer authentication which is what Stripe's API expects. You need to change your Authorization header like this:

request.Headers.Add("Authorization", "Bearer sk_test_example");

I know you mentioned in the comments that you can't use a third-party library but I wanted to mention one just in case. Stripe.net lets you use Stripe's API in .Net easily without having to rewrite the logic yourself. Handling errors, encoding parameters and sub-hashes properly, managing authentication and JSON decoding, all of this will take a lot of time and trial and error to build from scratch while this library would handle all of this for you.

Upvotes: 2

Related Questions