授权代码在C#PayPal REST API Winforms应用程序中的位置?

时间:2017-06-28 20:46:16

标签: c# winforms rest paypal

我正在尝试访问PayPal的API,通过C#.NET 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,所以我需要大局解释。谢谢你的耐心等待!

1 个答案:

答案 0 :(得分: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");     

        }

完成后,测试一下,你应该有一个沙箱呼叫等着你。