11using System ;
2- using System . IO ;
3- using System . Net . Http ;
4- using System . Text ;
2+ using System . Collections . Generic ;
53using System . Threading . Tasks ;
64using Microsoft . AspNetCore . Builder ;
75using Microsoft . AspNetCore . Hosting ;
8- using Microsoft . AspNetCore . Http ;
96using Microsoft . AspNetCore . Mvc ;
10- using Microsoft . Extensions . Configuration ;
117using Microsoft . Extensions . DependencyInjection ;
128using Microsoft . Extensions . Hosting ;
13- using Newtonsoft . Json ;
9+ using Microsoft . Extensions . Logging ;
10+ using PaypalServerSDK . Standard ;
11+ using PaypalServerSDK . Standard . Authentication ;
12+ using PaypalServerSDK . Standard . Controllers ;
13+ using PaypalServerSDK . Standard . Http . Response ;
14+ using PaypalServerSDK . Standard . Models ;
15+ using IConfiguration = Microsoft . Extensions . Configuration . IConfiguration ;
1416
1517namespace PayPalAdvancedIntegration ;
1618
@@ -56,22 +58,42 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
5658[ ApiController ]
5759public class CheckoutController : Controller
5860{
59- private readonly IHttpClientFactory _httpClientFactory ;
61+ private readonly OrdersController _ordersController ;
62+ private readonly PaymentsController _paymentsController ;
63+
6064 private IConfiguration _configuration { get ; }
6165 private string _paypalClientId
6266 {
63- get { return Environment . GetEnvironmentVariable ( "PAYPAL_CLIENT_ID" ) ; }
67+ get { return System . Environment . GetEnvironmentVariable ( "PAYPAL_CLIENT_ID" ) ; }
6468 }
6569 private string _paypalClientSecret
6670 {
67- get { return Environment . GetEnvironmentVariable ( "PAYPAL_CLIENT_SECRET" ) ; }
71+ get { return System . Environment . GetEnvironmentVariable ( "PAYPAL_CLIENT_SECRET" ) ; }
6872 }
69- private readonly string _base = "https://api-m.sandbox.paypal.com" ;
7073
71- public CheckoutController ( IHttpClientFactory httpClientFactory , IConfiguration configuration )
74+ private readonly ILogger < CheckoutController > _logger ;
75+
76+ public CheckoutController ( IConfiguration configuration , ILogger < CheckoutController > logger )
7277 {
73- _httpClientFactory = httpClientFactory ;
7478 _configuration = configuration ;
79+ _logger = logger ;
80+
81+ // Initialize the PayPal SDK client
82+ PaypalServerSDKClient client = new PaypalServerSDKClient . Builder ( )
83+ . Environment ( PaypalServerSDK . Standard . Environment . Sandbox )
84+ . ClientCredentialsAuth (
85+ new ClientCredentialsAuthModel . Builder ( _paypalClientId , _paypalClientSecret ) . Build ( )
86+ )
87+ . LoggingConfig ( config =>
88+ config
89+ . LogLevel ( LogLevel . Information )
90+ . RequestConfig ( reqConfig => reqConfig . Body ( true ) )
91+ . ResponseConfig ( respConfig => respConfig . Headers ( true ) )
92+ )
93+ . Build ( ) ;
94+
95+ _ordersController = client . OrdersController ;
96+ _paymentsController = client . PaymentsController ;
7597 }
7698
7799 [ HttpPost ( "api/orders" ) ]
@@ -80,7 +102,7 @@ public async Task<IActionResult> CreateOrder([FromBody] dynamic cart)
80102 try
81103 {
82104 var result = await _CreateOrder ( cart ) ;
83- return StatusCode ( ( int ) result . httpStatusCode , result . jsonResponse ) ;
105+ return StatusCode ( ( int ) result . StatusCode , result . Data ) ;
84106 }
85107 catch ( Exception ex )
86108 {
@@ -89,13 +111,37 @@ public async Task<IActionResult> CreateOrder([FromBody] dynamic cart)
89111 }
90112 }
91113
114+ private async Task < dynamic > _CreateOrder ( dynamic cart )
115+ {
116+ CheckoutPaymentIntent intent = ( CheckoutPaymentIntent )
117+ Enum . Parse ( typeof ( CheckoutPaymentIntent ) , "CAPTURE" , true ) ;
118+
119+ OrdersCreateInput ordersCreateInput = new OrdersCreateInput
120+ {
121+ Body = new OrderRequest
122+ {
123+ Intent = intent ,
124+ PurchaseUnits = new List < PurchaseUnitRequest >
125+ {
126+ new PurchaseUnitRequest
127+ {
128+ Amount = new AmountWithBreakdown { CurrencyCode = "USD" , MValue = "100" , } ,
129+ } ,
130+ } ,
131+ } ,
132+ } ;
133+
134+ ApiResponse < Order > result = await _ordersController . OrdersCreateAsync ( ordersCreateInput ) ;
135+ return result ;
136+ }
137+
92138 [ HttpPost ( "api/orders/{orderID}/capture" ) ]
93139 public async Task < IActionResult > CaptureOrder ( string orderID )
94140 {
95141 try
96142 {
97143 var result = await _CaptureOrder ( orderID ) ;
98- return StatusCode ( ( int ) result . httpStatusCode , result . jsonResponse ) ;
144+ return StatusCode ( ( int ) result . StatusCode , result . Data ) ;
99145 }
100146 catch ( Exception ex )
101147 {
@@ -104,91 +150,12 @@ public async Task<IActionResult> CaptureOrder(string orderID)
104150 }
105151 }
106152
107- private async Task < string > GenerateAccessToken ( )
108- {
109- if ( string . IsNullOrEmpty ( _paypalClientId ) || string . IsNullOrEmpty ( _paypalClientSecret ) )
110- {
111- throw new Exception ( "MISSING_API_CREDENTIALS" ) ;
112- }
113-
114- var auth = Convert . ToBase64String (
115- Encoding . UTF8 . GetBytes ( $ "{ _paypalClientId } :{ _paypalClientSecret } ")
116- ) ;
117- var client = _httpClientFactory . CreateClient ( ) ;
118- var request = new HttpRequestMessage ( HttpMethod . Post , $ "{ _base } /v1/oauth2/token")
119- {
120- Content = new StringContent (
121- "grant_type=client_credentials" ,
122- Encoding . UTF8 ,
123- "application/x-www-form-urlencoded"
124- )
125- } ;
126- request . Headers . Add ( "Authorization" , $ "Basic { auth } ") ;
127-
128- var response = await client . SendAsync ( request ) ;
129- var data = JsonConvert . DeserializeObject < dynamic > (
130- await response . Content . ReadAsStringAsync ( )
131- ) ;
132- return data . access_token ;
133- }
134-
135- private async Task < dynamic > _CreateOrder ( dynamic cart )
136- {
137- var accessToken = await GenerateAccessToken ( ) ;
138- var url = $ "{ _base } /v2/checkout/orders";
139- var payload = new
140- {
141- intent = "CAPTURE" ,
142- purchase_units = new [ ]
143- {
144- new { amount = new { currency_code = "USD" , value = "100.00" } }
145- }
146- } ;
147-
148- var client = _httpClientFactory . CreateClient ( ) ;
149- var request = new HttpRequestMessage ( HttpMethod . Post , url )
150- {
151- Content = new StringContent (
152- JsonConvert . SerializeObject ( payload ) ,
153- Encoding . UTF8 ,
154- "application/json"
155- )
156- } ;
157- request . Headers . Add ( "Authorization" , $ "Bearer { accessToken } ") ;
158-
159- var response = await client . SendAsync ( request ) ;
160- return await HandleResponse ( response ) ;
161- }
162-
163153 private async Task < dynamic > _CaptureOrder ( string orderID )
164154 {
165- var accessToken = await GenerateAccessToken ( ) ;
166- var url = $ "{ _base } /v2/checkout/orders/{ orderID } /capture";
167-
168- var client = _httpClientFactory . CreateClient ( ) ;
169- var request = new HttpRequestMessage ( HttpMethod . Post , url )
170- {
171- Content = new StringContent ( "" , Encoding . UTF8 , "application/json" )
172- } ;
173- request . Headers . Add ( "Authorization" , $ "Bearer { accessToken } ") ;
155+ OrdersCaptureInput ordersCaptureInput = new OrdersCaptureInput { Id = orderID , } ;
174156
175- var response = await client . SendAsync ( request ) ;
176- return await HandleResponse ( response ) ;
177- }
157+ ApiResponse < Order > result = await _ordersController . OrdersCaptureAsync ( ordersCaptureInput ) ;
178158
179- private async Task < dynamic > HandleResponse ( HttpResponseMessage response )
180- {
181- try
182- {
183- var jsonResponse = JsonConvert . DeserializeObject < dynamic > (
184- await response . Content . ReadAsStringAsync ( )
185- ) ;
186- return new { jsonResponse , httpStatusCode = response . StatusCode } ;
187- }
188- catch ( Exception )
189- {
190- var errorMessage = await response . Content . ReadAsStringAsync ( ) ;
191- throw new Exception ( errorMessage ) ;
192- }
159+ return result ;
193160 }
194161}
0 commit comments