[英]How to get access token from httpcontext using owin and Mvc 5
[英]How to get access token from PayPal in MVC
我正在嘗試從 PayPal 獲取訪問令牌。
我已將其設置為 PayPal 中的應用程序,我可以看到我的客戶端 ID 和密碼
我假設我不想在 javascript 前端公開我的秘密,所以我試圖從 C# 獲取訪問代碼,將令牌傳遞給前端,以便我可以制作 ZA34A6659BCEAE779F28185E757ABFCA 帖子。
但是,它總是以未經授權的方式返回
這是我的努力
var url = "https://api.paypal.com/v1/oauth2/token";
var clientId = "myClientId";
var pwrd = "mySecret";
var client = new WebClient();
client.Credentials = new NetworkCredential(clientId, pwrd);
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.Headers.Add("Accept: application/json");
var result = "";
using (var httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(url, null);
result = response.StatusCode.ToString();
}
return View(model: result);
我不明白為什么,當我從我的實時應用程序運行它時,它會失敗
編輯
我換了
using (var httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(url, null);
result = response.StatusCode.ToString();
}
和
var clientId = "myClientId";
var seceret = "mySecret";
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"{clientId}:{seceret}")));
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
var response = await client.SendAsync(req);
同樣的問題仍然存在。 我得到一個 401
而且它永遠不會授權,因為 HttpClient 變量對您的憑據一無所知。 您在 WebClient 中對其進行了初始化,但您沒有使用它。
為了詳細說明評論和其他答案,您在這里創建了一個名為client
的變量
var client = new WebClient();
client.Credentials = new NetworkCredential(clientId, pwrd);
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.Headers.Add("Accept: application/json");
在接下來的代碼中,您不使用該client
變量執行任何操作。 以上內容完全被忽略,與此無關:
using (var httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(url, null);
result = response.StatusCode.ToString();
}
return View(model: result);
因此,請使用您創建的client
object - 可能使用UploadValues
或類似的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.