我想通過C#.NET Winforms應用程序訪問PayPal的API來向客戶端提交發票,但我非常困惑。另一位用戶發佈這個代碼的解決方案來連接:授權代碼在C#PayPal REST API Winforms應用程序中出現在哪裏?
public class PayPalClient
{
public async Task RequestPayPalToken()
{
// Discussion about SSL secure channel
// http://stackoverflow.com/questions/32994464/could-not-create-ssl-tls-secure-channel-despite-setting-servercertificatevalida
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
try
{
// ClientId of your Paypal app API
string APIClientId = "**_[your_API_Client_Id]_**";
// secret key of you Paypal app API
string APISecret = "**_[your_API_secret]_**";
using (var client = new System.Net.Http.HttpClient())
{
var byteArray = Encoding.UTF8.GetBytes(APIClientId + ":" + APISecret);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var url = new Uri("https://api.sandbox.paypal.com/v1/oauth2/token", UriKind.Absolute);
client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var content = new FormUrlEncodedContent(requestParams);
var webresponse = await client.PostAsync(url, content);
var jsonString = await webresponse.Content.ReadAsStringAsync();
// response will deserialized using Jsonconver
var payPalTokenModel = JsonConvert.DeserializeObject<PayPalTokenModel>(jsonString);
}
}
catch (System.Exception ex)
{
//TODO: Log connection error
}
}
}
public class PayPalTokenModel
{
public string scope { get; set; }
public string nonce { get; set; }
public string access_token { get; set; }
public string token_type { get; set; }
public string app_id { get; set; }
public int expires_in { get; set; }
}
這恐怕是至少領先一步我的,因爲我無法揣摩出在我的項目是適當的粘貼代碼。我們只是說你創建了一個全新的C#Winforms應用程序。沒有深入瞭解創建發票的具體細節等。我需要哪些代碼來支持PayPal API以及該項目在哪裏執行?我知道我需要從PayPal獲得應用程序的授權,但我無法爲C#和PayPal找到一本好的「入門指南」。我在PayPal上創建了一個REST API應用程序,所以我確實有一個客戶端ID和「祕密」來通過Oauth授權 - 我只是找不到一個地方這樣做。
在此先感謝。我有一些C#.net編程經驗,但老實說,我的編程經驗大多返回到VB6,所以我需要大圖解釋。謝謝你的耐心!!
注意,[不要爲每個請求創建一個新的HttpClient](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/)。 – maccettura