/// <summary> /// Get access token to PayPal api /// </summary> /// <param name="http"></param> /// <returns>PayPal access token</returns> private async Task <PayPalAPIAccessToken> GetPayPalAccessToken(HttpClient http) { try { byte[] clientCredentials = Encoding.UTF8.GetBytes($"{configuration["PayPal:clientId"]}:{configuration["PayPal:clientSecret"]}"); tokenMsg.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(clientCredentials)); var formURL = new Dictionary <string, string> { { "grant_type", "client_credentials" } }; tokenMsg.Content = new FormUrlEncodedContent(formURL); HttpResponseMessage httpResponseMsg = await http.SendAsync(tokenMsg); string responseContent = await httpResponseMsg.Content.ReadAsStringAsync(); PayPalAPIAccessToken palAcess = JsonConvert.DeserializeObject <PayPalAPIAccessToken>(responseContent); return(palAcess); }catch (Exception ex) { Console.WriteLine(ex); return(null); } }
/// <summary> /// Send payment request to PayPal api /// </summary> /// <param name="http"></param> /// <param name="acess"></param> /// <param name="total"></param> /// <param name="currency"></param> /// <returns>PayPalApi response</returns> private async Task <PayPalAPIResponse> SendPayPalPayment(HttpClient http, PayPalAPIAccessToken acess, double total, string currency) { try { paymentMsg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", acess.access_token); var payment = JObject.FromObject(new { intent = "sale", redirect_urls = new { return_url = configuration["PayPal:returnUrl"], cancel_url = configuration["PayPal:cancelUrl"] }, payer = new { payment_method = "paypal" }, transactions = JArray.FromObject(new[] { new { amount = new { total, currency } } }) }); paymentMsg.Content = new StringContent(JsonConvert.SerializeObject(payment), Encoding.UTF8, "application/json"); HttpResponseMessage responseMessage = await http.SendAsync(paymentMsg); string content = await responseMessage.Content.ReadAsStringAsync(); PayPalAPIResponse payPalPayment = JsonConvert.DeserializeObject <PayPalAPIResponse>(content); return(payPalPayment); } catch (Exception ex) { Console.WriteLine(ex); return(null); } }
/// <summary> /// Get redirected to PayPal payment page if response is successful /// </summary> /// <param name="total"></param> /// <param name="currency"></param> /// <returns>PayPal URL</returns> public async Task <string> GetRedirectURLToPayPal(double total, string currency) { try { return(Task.Run(async() => { HttpClient http = GetPayPalSandBoxAccountHttp(); PayPalAPIAccessToken accessToken = await GetPayPalAccessToken(http); PayPalAPIResponse createdPayment = await SendPayPalPayment(http, accessToken, total, currency); return createdPayment.links.First(a => a.rel == "approval_url").href; } ).Result); } catch (Exception ex) { Console.WriteLine(ex); return(null); } }