1

我收到以下错误:“远程服务器返回错误:(401)未经授权”在这一行:

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

这是完整的代码:

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 text@example.com") );
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 */} 

一开始我以为是token不能使用超过一次导致的错误,但是我改了,还是一样的错误。我不确定是什么导致了错误。

4

2 回答 2

2

这里的问题是您正在传递 API 密钥,但没有使用 Stripe 的 API 所期望的 Bearer 身份验证。您需要像这样更改Authorization标题:

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

我知道您在评论中提到您不能使用第三方库,但我想提一个以防万一。Stripe.net让您可以轻松地在 .Net 中使用 Stripe 的 API,而无需自己重写逻辑。正确处理错误、编码参数和子哈希、管理身份验证和 JSON 解码,所有这些都需要大量时间和反复试验才能从头开始构建,而这个库会为您处理所有这些。

于 2017-05-25T12:41:26.760 回答
1

您正在为密钥初始化一个变量,但没有使用它。尝试修改请求 url 以开始"https://" + clientSecretKey + ":@api..."

当然,这是假设clientSecretKey是 Stripe 键。

小心将密钥放在服务器上的某个位置,该密钥不会对用户/客户端隐藏。

于 2017-06-15T20:18:40.827 回答