Skip to content

Commit

Permalink
Merge pull request #3 from cjavilla-stripe/final
Browse files Browse the repository at this point in the history
Completed demo
  • Loading branch information
cecilphillip committed Sep 25, 2021
2 parents 02bbd0d + 60b8ec7 commit e1d64cf
Show file tree
Hide file tree
Showing 20 changed files with 116 additions and 105 deletions.
5 changes: 4 additions & 1 deletion src/ContosoCrafts.Web.Client/Pages/Checkout.razor
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
@if (CheckoutSessionInfo != null)
{
<div>
@CheckoutSessionInfo.CustomerEmail
Thank you, @CheckoutSessionInfo.CustomerEmail!
</div>
<div>
Total: @string.Format("{0:C}", CheckoutSessionInfo.AmountTotal / 100)
</div>
}

Expand Down
4 changes: 2 additions & 2 deletions src/ContosoCrafts.Web.Client/Pages/IndexBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ protected override async Task OnInitializedAsync()
if (module == null)
{
module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/stripe.js");
module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/checkout.js");
}
await module.InvokeVoidAsync("checkout", pubKey, chkResp.CheckoutSessionID);
Expand All @@ -63,4 +63,4 @@ public async ValueTask DisposeAsync()
}
}
}
}
}
21 changes: 10 additions & 11 deletions src/ContosoCrafts.Web.Client/Shared/CheckoutModal.razor
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,14 @@
<tbody>
@if (Items != null)
{
@foreach (var item in Items)
{
<tr>
<td>@item.Title</td>
<td>@item.Quantity</td>
</tr>
}}
@foreach (var item in Items)
{
<tr>
<td>@item.Title</td>
<td>@item.Quantity</td>
</tr>
}
}
</tbody>
</table>
</div>
Expand Down Expand Up @@ -65,12 +66,10 @@
if (Items == null || !Items.Any()) return;

var client = ClientFactory.CreateClient("localapi");
await LocalStorage.RemoveItemAsync("state.cart");
await client.PostAsJsonAsync($"api/checkout", Items);
await LocalStorage.RemoveItemAsync("state.cart");

Items = null;
await Aggregator.PublishAsync(new ShoppingCartUpdated { ItemCount = 0 });

}

}
}
6 changes: 3 additions & 3 deletions src/ContosoCrafts.Web.Client/Shared/ProductListBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,12 @@ protected async Task AddToCart(string productId, string title)
else
{
// Add product to cart
state[productId] = new CartItem { Title = title, Quantity = 1 };
state[productId] = new CartItem { Id = productId, Title = title, Quantity = 1 };
}

// persist state in dapr
// persist state in dapr
await LocalStorage.SetItemAsync("state.cart", state);
await EventAggregator.PublishAsync(new ShoppingCartUpdated { ItemCount = state.Keys.Count });
}
}
}
}
4 changes: 2 additions & 2 deletions src/ContosoCrafts.Web.Client/Shared/ProductModal.razor
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@
}
}

protected Task SubmitRating(MouseEventArgs eventArgs, int rating)
protected Task SubmitRating(MouseEventArgs eventArgs, int rating)
{
return OnSubmitRating.InvokeAsync(rating);
}
}
}
4 changes: 2 additions & 2 deletions src/ContosoCrafts.Web.Client/wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
<div id="app">Loading...</div>

<script src="_framework/blazor.webassembly.js"></script>
<script src="https://js.stripe.com/v3/"></script>
<script src="lib/jquery/dist/jquery.min.js"></script>
<script src="lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://js.stripe.com/v3/"></script>
</body>

</html>
</html>
5 changes: 5 additions & 0 deletions src/ContosoCrafts.Web.Client/wwwroot/js/checkout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export function checkout(pubKey, sessionId) {
console.log(`Checking out with session: ${sessionId}`);
const stripe = Stripe(pubKey);
stripe.redirectToCheckout({ sessionId });
}
6 changes: 0 additions & 6 deletions src/ContosoCrafts.Web.Client/wwwroot/js/stripe.js

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="5.0.5" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="5.0.5" />
<PackageReference Include="Stripe.net" Version="39.45.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="5.0.0" />
<PackageReference Include="Stripe.net" Version="39.63.0" />
</ItemGroup>

<ItemGroup>
Expand Down
22 changes: 9 additions & 13 deletions src/ContosoCrafts.Web.Server/Controllers/CheckoutController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using Microsoft.AspNetCore.Mvc;
using Stripe.Checkout;
using Stripe;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using ContosoCrafts.Web.Server.Hubs;
Expand Down Expand Up @@ -42,15 +40,16 @@ public CheckoutController(IProductService productService,
}

[HttpPost]
public async Task<ActionResult> CheckoutOrder(IEnumerable<CartItem> items, [FromServices] IServiceProvider sp)
public async Task<ActionResult> CheckoutOrder([FromBody]IEnumerable<CartItem> items, [FromServices] IServiceProvider sp)
{
logger.LogInformation("Order received...");

// Build the URL to which the customer will be redirected after paying.
var host = $"{Request.Scheme}://{Request.Host.ToString()}";
var server = sp.GetRequiredService<IServer>();
var address = server.Features.Get<IServerAddressesFeature>().Addresses.FirstOrDefault();
var callbackRoot = server.Features.Get<IServerAddressesFeature>().Addresses.FirstOrDefault();

var checkoutResponse = await productService.CheckOut(items, address);
var checkoutResponse = await productService.CheckOut(items, callbackRoot);
var pubKey = configuration["Stripe:PubKey"];

await eventsHub.Clients.All.SendAsync("CheckoutSessionStarted", pubKey, checkoutResponse);
Expand All @@ -60,16 +59,13 @@ public async Task<ActionResult> CheckoutOrder(IEnumerable<CartItem> items, [From
[HttpGet("session")]
public async Task<ActionResult> CheckoutSuccess(string session_id)
{
var sessionService = new SessionService();
Session session = sessionService.Get(session_id);

var customerService = new CustomerService();
Customer customer = customerService.Get(session.CustomerId);
// var sessionService = new SessionService();
// Session session = await sessionService.GetAsync(session_id);

var checkoutInfo = new CheckoutInfo
{
AmountTotal = session.AmountTotal.Value,
CustomerEmail = session.CustomerEmail
AmountTotal = 0, //session.AmountTotal.Value,
CustomerEmail = "Unknown" // session.CustomerDetails.Email
};

var checkoutStr = JsonSerializer.Serialize<CheckoutInfo>(checkoutInfo);
Expand All @@ -86,4 +82,4 @@ public async Task<ActionResult> GetCheckoutInfo()
return Ok(checkoutInfo);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,4 @@ public async Task<ActionResult> Patch([FromBody] RatingRequest request)
return Ok();
}
}
}
}
2 changes: 1 addition & 1 deletion src/ContosoCrafts.Web.Server/Services/IProductService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ public interface IProductService
Task<Product> GetProduct(string id);
Task<CheckoutResponse> CheckOut(IEnumerable<CartItem> Items, string callbackRoot);
}
}
}
62 changes: 37 additions & 25 deletions src/ContosoCrafts.Web.Server/Services/JsonFileProductService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,20 @@
using System.Threading.Tasks;
using ContosoCrafts.Web.Shared.Models;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Stripe.Checkout;

namespace ContosoCrafts.Web.Server.Services
{
public class JsonFileProductService : IProductService
{
public JsonFileProductService()

private readonly ILogger<JsonFileProductService> logger;

public JsonFileProductService(ILogger<JsonFileProductService> logger)
{
this.logger = logger;

var manifestEmbeddedProvider = new ManifestEmbeddedFileProvider(typeof(Program).Assembly);
var fileInfo = manifestEmbeddedProvider.GetFileInfo("_data/products.json");
using var reader = new StreamReader(fileInfo.CreateReadStream());
Expand Down Expand Up @@ -55,32 +61,38 @@ public async Task AddRating(string productId, int rating)

public async Task<CheckoutResponse> CheckOut(IEnumerable<CartItem> Items, string callbackRoot)
{
var sessionOptions = new SessionCreateOptions()
logger.LogInformation($"Checking out from the JsonFilePRoductService...");

// Create a payment flow from the items in the cart.
var options = new SessionCreateOptions
{
SuccessUrl = $"{callbackRoot}/api/checkout/session?session_id=" + "{CHECKOUT_SESSION_ID}", /// redirect after checkout
CancelUrl = $"{callbackRoot}/checkout/failure", /// checkout cancelled
PaymentMethodTypes = new List<string> { "card" },
CustomerEmail = "cecilphillip@yahoo.com",
LineItems = new List<SessionLineItemOptions>
{
new() {
PriceData = new() {
UnitAmount = 2000L,
ProductData = new SessionLineItemPriceDataProductDataOptions{
Name = "Stuff"
},
Currency = "USD"
},
Quantity = 100L
}
},
Mode = "payment"
SuccessUrl = $"{callbackRoot}/api/checkout/session?session_id=" + "{CHECKOUT_SESSION_ID}", /// redirect after checkout
              CancelUrl = $"{callbackRoot}/checkout/failure",  /// checkout cancelled
PaymentMethodTypes = new List<string>
{
"card",
},
LineItems = new List<SessionLineItemOptions>
              {
                new SessionLineItemOptions
                {
                  PriceData = new()
                  {
                    UnitAmount = 1000L,
                    Currency = "USD",
                    ProductData = new()
                    {
                        Name = "Example",
                    },
                  },
                  Quantity = 2,
                },
              },
Mode = "payment",
};

var checkoutService = new SessionService();
var session = await checkoutService.CreateAsync(sessionOptions);

var service = new SessionService();
var session = await service.CreateAsync(options);
return new CheckoutResponse(session.Id);
}
}
}
}
3 changes: 1 addition & 2 deletions src/ContosoCrafts.Web.Server/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
using Microsoft.Extensions.Hosting;
using ContosoCrafts.Web.Server.Services;
using System;
using Stripe;
using Microsoft.AspNetCore.Hosting.Server.Features;
using ContosoCrafts.Web.Server.Hubs;
using Microsoft.AspNetCore.ResponseCompression;
using System.Linq;
using Stripe;

namespace ContosoCrafts.Web.Server
{
Expand All @@ -25,7 +25,6 @@ public Startup(IConfiguration configuration)
public void ConfigureServices(IServiceCollection services)
{
StripeConfiguration.ApiKey = Configuration["Stripe:SecretKey"];

services.AddHttpContextAccessor();
services.AddRazorPages();
services.AddControllers();
Expand Down
Loading

0 comments on commit e1d64cf

Please sign in to comment.