0

I'm trying to access PayPal's API to submit invoices to clients through a C#.NET Winforms app, but I am terribly confused. Another user posted this code as a solution to connect:

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; }
}

I'm afraid this is at least one step ahead of me as I can't figure out where in my project it is appropriate to paste the code. Let's just say you created a brand new C# Winforms app. Without getting into the specifics of creating an invoice, etc. What code would I need to support the PayPal API and where in the project does it go? I know I need to get authorization for the app from PayPal, but I'm having trouble finding a good "Getting Started" guide for C# and PayPal. I've created a REST API app on PayPal, so I do have a client ID and "secret" to pass for Oauth authorization - I just can't find a place to do that.

Thanks in advance. I have some C#.net programming experience, but honestly my programming experience mostly goes back to VB6 so I kind of need the big picture explanation. Thanks for your patience!!

Alan Denke
  • 67
  • 9
  • 2
    Side note, [don't create a new HttpClient for every request](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/). – maccettura Jun 28 '17 at 20:47

1 Answers1

1

Sorry for posting an answer here but I currently do not have enough reputation to post comment. However if you are still looking for a general idea on how to get this done then I can provide a brief example. Since you are using WinForms and PayPal's API, I am assuming you have setup your App.Config file already?

Example-

  <!-- 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>

Once this has been addressed then you can make your way over to your form and input what you are going to use. Example:

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

Now that is completed you can create a button to make the API Call.

Example:

        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");     

        }

Once completed, test it out and you should have a sandbox call waiting for you.

Michael Lewis
  • 147
  • 1
  • 1
  • 15