2017-06-28 50 views
0

我想通過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,所以我需要大圖解釋。謝謝你的耐心!!

+2

注意,[不要爲每個請求創建一個新的HttpClient](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/)。 – maccettura

回答

1

對不起,在這裏發佈答案,但我目前沒有足夠的聲望發表評論。但是如果你仍然在尋找如何完成這個任務的一般想法,那麼我可以提供一個簡單的例子。既然你使用WinForms和PayPal的API,我假設你已經設置了你的App.Config文件了?

例 -

<!-- PayPal SDK settings --> 
    <paypal> 
    <settings> 
     <add name="mode" value="sandbox" /> 
     <add name="clientId" value="insert_clientid_key_here" /> 
     <add name="clientSecret" value="Insert_client_secret_key_here" /> 
    </settings> 
    </paypal> 

一旦這已得到解決,那麼你可以用自己的方式到你的表單和輸入你要使用什麼。例如:

using System; 
using System.Windows.Forms; 
using PayPal.Api; 
using System.Collections.Generic; 

現在完成後,您可以創建一個按鈕來進行API調用。

例子:

 private void button1_Click_1(object sender, EventArgs e) 
     { 


      // Authenticate with PayPal 
var config = ConfigManager.Instance.GetProperties(); 
var accessToken = new OAuthTokenCredential(config).GetAccessToken(); 
var apiContext = new APIContext(accessToken); 


// Make an API call 
var payment = Payment.Create(apiContext, new Payment 
{ 
    intent = "sale", 
    payer = new Payer 
    { 
     payment_method = "paypal" 
    }, 
    transactions = new List<Transaction> 
    { 
     new Transaction 
     { 
      description = "Transaction description.", 
      invoice_number = "001", 
      amount = new Amount 
      { 
       currency = "USD", 
       total = "100.00", 
       details = new Details 
       { 
        tax = "15", 
        shipping = "10", 
        subtotal = "75" 
       } 
      }, 
      item_list = new ItemList 
      { 
       items = new List<Item> 
       { 
        new Item 
        { 
         name = "Item Name", 
         currency = "USD", 
         price = "15", 
         quantity = "5", 
         sku = "sku" 
        } 

       } 
      } 
     } 
    }, 
    redirect_urls = new RedirectUrls 
    { 
     return_url = "http://x.com/return", 
     cancel_url = "http://x.com/cancel" 
    } 

}); 
      MessageBox.Show("API Request Sent to Paypal");  

     } 

一旦完成,測試它,你應該有一個沙箱呼叫等待你。

相關問題