mirror of
https://github.com/andwati/cymelle.git
synced 2026-11-16 05:25:13 +00:00
paystack
This commit is contained in:
@@ -10,4 +10,10 @@ FARE_MINIMUM_FARE=150.00
|
||||
FARE_DEFAULT_SURGE_MULTIPLIER=1.0
|
||||
FARE_CURRENCY=KES
|
||||
|
||||
SEED_DATA=true
|
||||
PAYSTACK_SECRET_KEY=
|
||||
PAYSTACK_PUBLIC_KEY=
|
||||
PAYSTACK_CALLBACK_URL=http://localhost:3000/payments/paystack/callback
|
||||
PAYSTACK_WEBHOOK_SECRET=
|
||||
PAYSTACK_API_BASE_URL=https://api.paystack.co
|
||||
|
||||
SEED_DATA=true
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.andwati.orders;
|
||||
|
||||
import com.andwati.orders.config.FareProperties;
|
||||
import com.andwati.orders.config.InventoryProperties;
|
||||
import com.andwati.orders.config.PaystackProperties;
|
||||
import io.github.cdimascio.dotenv.Dotenv;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
@@ -10,7 +11,8 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
|
||||
@SpringBootApplication
|
||||
@EnableConfigurationProperties({
|
||||
FareProperties.class,
|
||||
InventoryProperties.class
|
||||
InventoryProperties.class,
|
||||
PaystackProperties.class
|
||||
})
|
||||
public class OrdersBackendApplication {
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.andwati.orders.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "paystack")
|
||||
public record PaystackProperties(
|
||||
String secretKey,
|
||||
String publicKey,
|
||||
String callbackUrl,
|
||||
String webhookSecret,
|
||||
String apiBaseUrl
|
||||
) {
|
||||
public String resolvedApiBaseUrl() {
|
||||
return hasText(apiBaseUrl) ? apiBaseUrl : "https://api.paystack.co";
|
||||
}
|
||||
|
||||
public String resolvedWebhookSecret() {
|
||||
return hasText(webhookSecret) ? webhookSecret : secretKey;
|
||||
}
|
||||
|
||||
public boolean hasSecretKey() {
|
||||
return hasText(secretKey);
|
||||
}
|
||||
|
||||
public boolean hasCallbackUrl() {
|
||||
return hasText(callbackUrl);
|
||||
}
|
||||
|
||||
private boolean hasText(String value) {
|
||||
return value != null && !value.isBlank();
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import org.springframework.security.config.annotation.web.configurers.AbstractHt
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
|
||||
import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler;
|
||||
|
||||
@@ -31,6 +32,7 @@ public class SecurityConfig {
|
||||
.csrf(csrf -> csrf
|
||||
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
|
||||
.csrfTokenRequestHandler(csrfRequestHandler)
|
||||
.ignoringRequestMatchers(new AntPathRequestMatcher("/api/payments/paystack/webhook", "POST"))
|
||||
)
|
||||
.formLogin(AbstractHttpConfigurer::disable)
|
||||
.httpBasic(AbstractHttpConfigurer::disable)
|
||||
@@ -40,6 +42,8 @@ public class SecurityConfig {
|
||||
.requestMatchers(HttpMethod.POST, "/api/auth/login", "/api/auth/register").permitAll()
|
||||
.requestMatchers("/api-docs/**", "/swagger-ui.html", "/swagger-ui/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/checkout/quote").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/payments/paystack/webhook").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/products/**").hasRole("ADMIN")
|
||||
.requestMatchers(HttpMethod.PUT, "/api/products/**").hasRole("ADMIN")
|
||||
.requestMatchers(HttpMethod.PATCH, "/api/products/**").hasRole("ADMIN")
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.andwati.orders.controller;
|
||||
|
||||
import com.andwati.orders.dto.request.CheckoutQuoteRequest;
|
||||
import com.andwati.orders.dto.response.CheckoutQuoteResponse;
|
||||
import com.andwati.orders.services.PaymentService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "Checkout", description = "Quote ecommerce checkout totals")
|
||||
@RestController
|
||||
@RequestMapping("/api/checkout")
|
||||
public class CheckoutController {
|
||||
|
||||
private final PaymentService paymentService;
|
||||
|
||||
public CheckoutController(PaymentService paymentService) {
|
||||
this.paymentService = paymentService;
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Quote checkout totals",
|
||||
description = "Calculates product subtotal, optional delivery ride fare, and grand total from current backend data."
|
||||
)
|
||||
@PostMapping("/quote")
|
||||
public CheckoutQuoteResponse quote(@Valid @RequestBody CheckoutQuoteRequest request) {
|
||||
return paymentService.quote(request);
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.andwati.orders.controller;
|
||||
|
||||
import com.andwati.orders.dto.request.PaystackInitializeRequest;
|
||||
import com.andwati.orders.dto.response.PaystackInitializeResponse;
|
||||
import com.andwati.orders.dto.response.PaystackVerifyResponse;
|
||||
import com.andwati.orders.services.PaymentService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "Paystack Payments", description = "Initialize and verify Paystack checkout payments")
|
||||
@RestController
|
||||
@RequestMapping("/api/payments/paystack")
|
||||
public class PaystackPaymentController {
|
||||
|
||||
private final PaymentService paymentService;
|
||||
|
||||
public PaystackPaymentController(PaymentService paymentService) {
|
||||
this.paymentService = paymentService;
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Initialize Paystack checkout",
|
||||
description = "Creates pending order, optional ride, payment record, and returns a Paystack authorization URL."
|
||||
)
|
||||
@PostMapping("/initialize")
|
||||
public PaystackInitializeResponse initialize(@Valid @RequestBody PaystackInitializeRequest request) {
|
||||
return paymentService.initialize(request);
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Verify Paystack payment",
|
||||
description = "Verifies the Paystack transaction and marks the payment paid only when reference, amount, and currency match."
|
||||
)
|
||||
@PostMapping("/verify/{reference}")
|
||||
public PaystackVerifyResponse verify(@PathVariable String reference) {
|
||||
return paymentService.verify(reference);
|
||||
}
|
||||
|
||||
@Operation(summary = "Receive Paystack webhook events")
|
||||
@PostMapping("/webhook")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void webhook(
|
||||
@RequestBody String body,
|
||||
@RequestHeader(name = "x-paystack-signature", required = false) String signature
|
||||
) {
|
||||
paymentService.handleWebhook(body, signature);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.andwati.orders.dto.request;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record CheckoutQuoteRequest(
|
||||
@Valid
|
||||
@Size(min = 1, message = "items must contain at least one item")
|
||||
List<CreateOrderItemRequest> items,
|
||||
|
||||
@Valid
|
||||
CreateOrderRideRequest deliveryRide
|
||||
) {
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.andwati.orders.dto.request;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record PaystackInitializeRequest(
|
||||
@Valid
|
||||
@Size(min = 1, message = "items must contain at least one item")
|
||||
List<CreateOrderItemRequest> items,
|
||||
|
||||
@Valid
|
||||
CreateOrderRideRequest deliveryRide
|
||||
) {
|
||||
public CreateOrderRequest toCreateOrderRequest() {
|
||||
return new CreateOrderRequest(items, deliveryRide);
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.andwati.orders.dto.response;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
|
||||
public record CheckoutQuoteResponse(
|
||||
BigDecimal productSubtotal,
|
||||
BigDecimal rideFare,
|
||||
BigDecimal grandTotal,
|
||||
String currency,
|
||||
Instant expiresAt
|
||||
) {
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.andwati.orders.dto.response;
|
||||
|
||||
import com.andwati.orders.model.PaymentStatus;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.UUID;
|
||||
|
||||
public record PaystackInitializeResponse(
|
||||
String authorizationUrl,
|
||||
String accessCode,
|
||||
String reference,
|
||||
UUID orderId,
|
||||
UUID rideId,
|
||||
BigDecimal amount,
|
||||
String currency,
|
||||
PaymentStatus status
|
||||
) {
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.andwati.orders.dto.response;
|
||||
|
||||
import com.andwati.orders.model.PaymentStatus;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.UUID;
|
||||
|
||||
public record PaystackVerifyResponse(
|
||||
String reference,
|
||||
PaymentStatus status,
|
||||
UUID orderId,
|
||||
UUID rideId,
|
||||
BigDecimal amount,
|
||||
String currency,
|
||||
String message
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package com.andwati.orders.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(
|
||||
name = "payments",
|
||||
uniqueConstraints = {
|
||||
@UniqueConstraint(name = "uk_payments_reference", columnNames = "reference")
|
||||
}
|
||||
)
|
||||
public class Payment {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@OneToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "order_id", nullable = false)
|
||||
private Order order;
|
||||
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "ride_id")
|
||||
private Ride ride;
|
||||
|
||||
@Column(nullable = false, length = 80)
|
||||
private String reference;
|
||||
|
||||
@Column(nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal productSubtotal;
|
||||
|
||||
@Column(nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal rideFare;
|
||||
|
||||
@Column(nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal amountMajor;
|
||||
|
||||
@Column(nullable = false)
|
||||
private long amountSubunits;
|
||||
|
||||
@Column(nullable = false, length = 3)
|
||||
private String currency;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 30)
|
||||
private PaymentStatus status = PaymentStatus.PENDING;
|
||||
|
||||
@Column(length = 512)
|
||||
private String authorizationUrl;
|
||||
|
||||
@Column(length = 120)
|
||||
private String accessCode;
|
||||
|
||||
@Lob
|
||||
private String rawVerificationPayload;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
private Instant paidAt;
|
||||
|
||||
private Instant updatedAt;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
Instant now = Instant.now();
|
||||
if (createdAt == null) {
|
||||
createdAt = now;
|
||||
}
|
||||
if (updatedAt == null) {
|
||||
updatedAt = now;
|
||||
}
|
||||
if (status == null) {
|
||||
status = PaymentStatus.PENDING;
|
||||
}
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
public void preUpdate() {
|
||||
updatedAt = Instant.now();
|
||||
}
|
||||
|
||||
public void markPaid(String rawPayload) {
|
||||
if (status == PaymentStatus.PAID) {
|
||||
this.rawVerificationPayload = rawPayload;
|
||||
return;
|
||||
}
|
||||
|
||||
this.status = PaymentStatus.PAID;
|
||||
this.paidAt = Instant.now();
|
||||
this.rawVerificationPayload = rawPayload;
|
||||
}
|
||||
|
||||
public void markFailed(PaymentStatus status, String rawPayload) {
|
||||
if (this.status == PaymentStatus.PAID) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.status = status;
|
||||
this.rawVerificationPayload = rawPayload;
|
||||
}
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Payment setId(UUID id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Order getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public Payment setOrder(Order order) {
|
||||
this.order = order;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Ride getRide() {
|
||||
return ride;
|
||||
}
|
||||
|
||||
public Payment setRide(Ride ride) {
|
||||
this.ride = ride;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getReference() {
|
||||
return reference;
|
||||
}
|
||||
|
||||
public Payment setReference(String reference) {
|
||||
this.reference = reference;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BigDecimal getProductSubtotal() {
|
||||
return productSubtotal;
|
||||
}
|
||||
|
||||
public Payment setProductSubtotal(BigDecimal productSubtotal) {
|
||||
this.productSubtotal = productSubtotal;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BigDecimal getRideFare() {
|
||||
return rideFare;
|
||||
}
|
||||
|
||||
public Payment setRideFare(BigDecimal rideFare) {
|
||||
this.rideFare = rideFare;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BigDecimal getAmountMajor() {
|
||||
return amountMajor;
|
||||
}
|
||||
|
||||
public Payment setAmountMajor(BigDecimal amountMajor) {
|
||||
this.amountMajor = amountMajor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public long getAmountSubunits() {
|
||||
return amountSubunits;
|
||||
}
|
||||
|
||||
public Payment setAmountSubunits(long amountSubunits) {
|
||||
this.amountSubunits = amountSubunits;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public Payment setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
return this;
|
||||
}
|
||||
|
||||
public PaymentStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public Payment setStatus(PaymentStatus status) {
|
||||
this.status = status;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getAuthorizationUrl() {
|
||||
return authorizationUrl;
|
||||
}
|
||||
|
||||
public Payment setAuthorizationUrl(String authorizationUrl) {
|
||||
this.authorizationUrl = authorizationUrl;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getAccessCode() {
|
||||
return accessCode;
|
||||
}
|
||||
|
||||
public Payment setAccessCode(String accessCode) {
|
||||
this.accessCode = accessCode;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getRawVerificationPayload() {
|
||||
return rawVerificationPayload;
|
||||
}
|
||||
|
||||
public Payment setRawVerificationPayload(String rawVerificationPayload) {
|
||||
this.rawVerificationPayload = rawVerificationPayload;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public Payment setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Instant getPaidAt() {
|
||||
return paidAt;
|
||||
}
|
||||
|
||||
public Payment setPaidAt(Instant paidAt) {
|
||||
this.paidAt = paidAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Instant getUpdatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
|
||||
public Payment setUpdatedAt(Instant updatedAt) {
|
||||
this.updatedAt = updatedAt;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.andwati.orders.model;
|
||||
|
||||
public enum PaymentStatus {
|
||||
PENDING,
|
||||
PAID,
|
||||
FAILED,
|
||||
ABANDONED,
|
||||
REFUNDED
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.andwati.orders.repository;
|
||||
|
||||
import com.andwati.orders.model.Payment;
|
||||
import org.springframework.data.jpa.repository.EntityGraph;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface PaymentRepository extends JpaRepository<Payment, UUID> {
|
||||
|
||||
@EntityGraph(attributePaths = {"order", "order.customer", "ride"})
|
||||
Optional<Payment> findByReference(String reference);
|
||||
}
|
||||
@@ -57,6 +57,18 @@ public class OrderService {
|
||||
@Transactional
|
||||
public OrderResponse placeOrder(CreateOrderRequest request) {
|
||||
AppUser customer = appUserService.getCurrentUser();
|
||||
|
||||
PendingOrderResult result = createPendingOrder(customer, request, null, null);
|
||||
return orderMapper.toResponse(result.order());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public PendingOrderResult createPendingOrder(
|
||||
AppUser customer,
|
||||
CreateOrderRequest request,
|
||||
java.math.BigDecimal rideFare,
|
||||
String rideCurrency
|
||||
) {
|
||||
if (customer.getRole() != Role.CUSTOMER) {
|
||||
throw new IllegalArgumentException("Only customers can place orders");
|
||||
}
|
||||
@@ -103,6 +115,7 @@ public class OrderService {
|
||||
order.recalculateTotal();
|
||||
|
||||
Order savedOrder = orderRepository.save(order);
|
||||
Ride savedRide = null;
|
||||
|
||||
if (request.deliveryRide() != null) {
|
||||
Ride ride = new Ride()
|
||||
@@ -111,12 +124,14 @@ public class OrderService {
|
||||
.setPickupLocation(request.deliveryRide().pickupLocation().trim())
|
||||
.setDropoffLocation(request.deliveryRide().dropoffLocation().trim())
|
||||
.setDistanceKm(request.deliveryRide().distanceKm())
|
||||
.setFareAmount(rideFare)
|
||||
.setCurrency(rideCurrency == null ? "KES" : rideCurrency)
|
||||
.setStatus(RideStatus.REQUESTED);
|
||||
|
||||
rideRepository.save(ride);
|
||||
savedRide = rideRepository.save(ride);
|
||||
}
|
||||
|
||||
return orderMapper.toResponse(savedOrder);
|
||||
return new PendingOrderResult(savedOrder, savedRide);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
package com.andwati.orders.services;
|
||||
|
||||
import com.andwati.orders.config.PaystackProperties;
|
||||
import com.andwati.orders.dto.request.CheckoutQuoteRequest;
|
||||
import com.andwati.orders.dto.request.CreateOrderRequest;
|
||||
import com.andwati.orders.dto.request.PaystackInitializeRequest;
|
||||
import com.andwati.orders.dto.response.CheckoutQuoteResponse;
|
||||
import com.andwati.orders.dto.response.FareCalculationResponse;
|
||||
import com.andwati.orders.dto.response.PaystackInitializeResponse;
|
||||
import com.andwati.orders.dto.response.PaystackVerifyResponse;
|
||||
import com.andwati.orders.exception.InsufficientStockException;
|
||||
import com.andwati.orders.exception.InventoryNotFoundException;
|
||||
import com.andwati.orders.exception.ProductNotFoundException;
|
||||
import com.andwati.orders.model.*;
|
||||
import com.andwati.orders.repository.InventoryItemRepository;
|
||||
import com.andwati.orders.repository.PaymentRepository;
|
||||
import com.andwati.orders.repository.ProductRepository;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class PaymentService {
|
||||
|
||||
private static final String DEFAULT_CURRENCY = "KES";
|
||||
private static final int QUOTE_TTL_MINUTES = 15;
|
||||
|
||||
private final ProductRepository productRepository;
|
||||
private final InventoryItemRepository inventoryItemRepository;
|
||||
private final PaymentRepository paymentRepository;
|
||||
private final FareCalculationService fareCalculationService;
|
||||
private final OrderService orderService;
|
||||
private final AppUserService appUserService;
|
||||
private final PaystackClient paystackClient;
|
||||
private final PaystackProperties paystackProperties;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public PaymentService(
|
||||
ProductRepository productRepository,
|
||||
InventoryItemRepository inventoryItemRepository,
|
||||
PaymentRepository paymentRepository,
|
||||
FareCalculationService fareCalculationService,
|
||||
OrderService orderService,
|
||||
AppUserService appUserService,
|
||||
PaystackClient paystackClient,
|
||||
PaystackProperties paystackProperties,
|
||||
ObjectMapper objectMapper
|
||||
) {
|
||||
this.productRepository = productRepository;
|
||||
this.inventoryItemRepository = inventoryItemRepository;
|
||||
this.paymentRepository = paymentRepository;
|
||||
this.fareCalculationService = fareCalculationService;
|
||||
this.orderService = orderService;
|
||||
this.appUserService = appUserService;
|
||||
this.paystackClient = paystackClient;
|
||||
this.paystackProperties = paystackProperties;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public CheckoutQuoteResponse quote(CheckoutQuoteRequest request) {
|
||||
CheckoutQuote quote = calculateQuote(request.items(), request.deliveryRide());
|
||||
return toQuoteResponse(quote);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public PaystackInitializeResponse initialize(PaystackInitializeRequest request) {
|
||||
AppUser customer = appUserService.getCurrentUser();
|
||||
if (customer.getRole() != Role.CUSTOMER) {
|
||||
throw new IllegalArgumentException("Only customers can checkout");
|
||||
}
|
||||
|
||||
CheckoutQuote quote = calculateQuote(request.items(), request.deliveryRide());
|
||||
PendingOrderResult pendingOrder = orderService.createPendingOrder(
|
||||
customer,
|
||||
request.toCreateOrderRequest(),
|
||||
quote.rideFare(),
|
||||
quote.currency()
|
||||
);
|
||||
|
||||
String reference = generateReference();
|
||||
Payment payment = new Payment()
|
||||
.setOrder(pendingOrder.order())
|
||||
.setRide(pendingOrder.ride())
|
||||
.setReference(reference)
|
||||
.setProductSubtotal(quote.productSubtotal())
|
||||
.setRideFare(quote.rideFare())
|
||||
.setAmountMajor(quote.grandTotal())
|
||||
.setAmountSubunits(toSubunits(quote.grandTotal()))
|
||||
.setCurrency(quote.currency())
|
||||
.setStatus(PaymentStatus.PENDING);
|
||||
|
||||
paymentRepository.save(payment);
|
||||
|
||||
JsonNode paystackData = paystackClient.initializeTransaction(
|
||||
customer.getUsername(),
|
||||
payment.getAmountSubunits(),
|
||||
payment.getCurrency(),
|
||||
payment.getReference(),
|
||||
buildMetadata(customer, payment)
|
||||
);
|
||||
|
||||
payment
|
||||
.setAuthorizationUrl(paystackData.path("authorization_url").asText())
|
||||
.setAccessCode(paystackData.path("access_code").asText());
|
||||
|
||||
return toInitializeResponse(payment);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public PaystackVerifyResponse verify(String reference) {
|
||||
Payment payment = getPayment(reference);
|
||||
assertCanAccess(payment);
|
||||
|
||||
return verifyPayment(payment);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void handleWebhook(String body, String signature) {
|
||||
verifyWebhookSignature(body, signature);
|
||||
|
||||
JsonNode event;
|
||||
try {
|
||||
event = objectMapper.readTree(body);
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new IllegalArgumentException("Webhook payload is not valid JSON");
|
||||
}
|
||||
|
||||
if (!"charge.success".equals(event.path("event").asText())) {
|
||||
return;
|
||||
}
|
||||
|
||||
String reference = event.path("data").path("reference").asText(null);
|
||||
if (reference == null || reference.isBlank()) {
|
||||
return;
|
||||
}
|
||||
|
||||
paymentRepository.findByReference(reference).ifPresent(this::verifyPayment);
|
||||
}
|
||||
|
||||
private PaystackVerifyResponse verifyPayment(Payment payment) {
|
||||
JsonNode verification = paystackClient.verifyTransaction(payment.getReference());
|
||||
JsonNode data = verification.path("data");
|
||||
String rawPayload = toJson(verification);
|
||||
|
||||
boolean success = "success".equals(data.path("status").asText());
|
||||
boolean matchesReference = payment.getReference().equals(data.path("reference").asText());
|
||||
boolean matchesAmount = payment.getAmountSubunits() == data.path("amount").asLong();
|
||||
boolean matchesCurrency = payment.getCurrency().equalsIgnoreCase(data.path("currency").asText());
|
||||
|
||||
if (success && matchesReference && matchesAmount && matchesCurrency) {
|
||||
payment.markPaid(rawPayload);
|
||||
return toVerifyResponse(payment, "Payment verified");
|
||||
}
|
||||
|
||||
PaymentStatus nextStatus = mapPaystackStatus(data.path("status").asText());
|
||||
payment.markFailed(nextStatus, rawPayload);
|
||||
|
||||
if (!success) {
|
||||
return toVerifyResponse(payment, data.path("gateway_response").asText("Payment was not successful"));
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Paystack verification did not match the stored payment");
|
||||
}
|
||||
|
||||
private CheckoutQuote calculateQuote(
|
||||
java.util.List<com.andwati.orders.dto.request.CreateOrderItemRequest> items,
|
||||
com.andwati.orders.dto.request.CreateOrderRideRequest deliveryRide
|
||||
) {
|
||||
if (items == null || items.isEmpty()) {
|
||||
throw new IllegalArgumentException("items must contain at least one item");
|
||||
}
|
||||
|
||||
Map<UUID, Integer> requestedQuantities = items.stream()
|
||||
.collect(Collectors.toMap(
|
||||
com.andwati.orders.dto.request.CreateOrderItemRequest::productId,
|
||||
com.andwati.orders.dto.request.CreateOrderItemRequest::quantity,
|
||||
Integer::sum,
|
||||
LinkedHashMap::new
|
||||
));
|
||||
|
||||
Map<UUID, Product> productsById = productRepository.findByIdIn(requestedQuantities.keySet())
|
||||
.stream()
|
||||
.collect(Collectors.toMap(Product::getId, Function.identity()));
|
||||
|
||||
for (UUID productId : requestedQuantities.keySet()) {
|
||||
Product product = productsById.get(productId);
|
||||
if (product == null) {
|
||||
throw new ProductNotFoundException(productId);
|
||||
}
|
||||
if (!product.isActive()) {
|
||||
throw new IllegalArgumentException("Product " + product.getName() + " is not active");
|
||||
}
|
||||
}
|
||||
|
||||
Map<UUID, InventoryItem> inventoryByProductId = inventoryItemRepository
|
||||
.findByProduct_IdIn(requestedQuantities.keySet())
|
||||
.stream()
|
||||
.collect(Collectors.toMap(
|
||||
inventory -> inventory.getProduct().getId(),
|
||||
Function.identity()
|
||||
));
|
||||
|
||||
BigDecimal productSubtotal = BigDecimal.ZERO;
|
||||
String currency = null;
|
||||
|
||||
for (Map.Entry<UUID, Integer> entry : requestedQuantities.entrySet()) {
|
||||
UUID productId = entry.getKey();
|
||||
int quantity = entry.getValue();
|
||||
if (quantity < 1) {
|
||||
throw new IllegalArgumentException("quantity must be at least 1");
|
||||
}
|
||||
|
||||
Product product = productsById.get(productId);
|
||||
InventoryItem inventory = inventoryByProductId.get(productId);
|
||||
if (inventory == null) {
|
||||
throw new InventoryNotFoundException(productId);
|
||||
}
|
||||
if (!inventory.hasEnoughStock(quantity)) {
|
||||
throw new InsufficientStockException(
|
||||
productId,
|
||||
product.getName(),
|
||||
quantity,
|
||||
inventory.getAvailableQuantity()
|
||||
);
|
||||
}
|
||||
|
||||
if (currency == null) {
|
||||
currency = product.getCurrency();
|
||||
} else if (!currency.equals(product.getCurrency())) {
|
||||
throw new IllegalArgumentException("Cart items must use one currency");
|
||||
}
|
||||
|
||||
productSubtotal = productSubtotal.add(product.getPrice().multiply(BigDecimal.valueOf(quantity)));
|
||||
}
|
||||
|
||||
BigDecimal rideFare = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
|
||||
if (deliveryRide != null) {
|
||||
FareCalculationResponse fare = fareCalculationService.calculateFare(deliveryRide.distanceKm(), null);
|
||||
if (currency != null && !currency.equals(fare.currency())) {
|
||||
throw new IllegalArgumentException("Ride fare currency must match cart currency");
|
||||
}
|
||||
currency = fare.currency();
|
||||
rideFare = fare.calculatedFare();
|
||||
}
|
||||
|
||||
String resolvedCurrency = currency == null ? DEFAULT_CURRENCY : currency;
|
||||
BigDecimal normalizedSubtotal = productSubtotal.setScale(2, RoundingMode.HALF_UP);
|
||||
BigDecimal normalizedRideFare = rideFare.setScale(2, RoundingMode.HALF_UP);
|
||||
|
||||
return new CheckoutQuote(
|
||||
normalizedSubtotal,
|
||||
normalizedRideFare,
|
||||
normalizedSubtotal.add(normalizedRideFare).setScale(2, RoundingMode.HALF_UP),
|
||||
resolvedCurrency
|
||||
);
|
||||
}
|
||||
|
||||
private CheckoutQuoteResponse toQuoteResponse(CheckoutQuote quote) {
|
||||
return new CheckoutQuoteResponse(
|
||||
quote.productSubtotal(),
|
||||
quote.rideFare(),
|
||||
quote.grandTotal(),
|
||||
quote.currency(),
|
||||
Instant.now().plusSeconds(QUOTE_TTL_MINUTES * 60L)
|
||||
);
|
||||
}
|
||||
|
||||
private PaystackInitializeResponse toInitializeResponse(Payment payment) {
|
||||
return new PaystackInitializeResponse(
|
||||
payment.getAuthorizationUrl(),
|
||||
payment.getAccessCode(),
|
||||
payment.getReference(),
|
||||
payment.getOrder().getId(),
|
||||
payment.getRide() == null ? null : payment.getRide().getId(),
|
||||
payment.getAmountMajor(),
|
||||
payment.getCurrency(),
|
||||
payment.getStatus()
|
||||
);
|
||||
}
|
||||
|
||||
private PaystackVerifyResponse toVerifyResponse(Payment payment, String message) {
|
||||
return new PaystackVerifyResponse(
|
||||
payment.getReference(),
|
||||
payment.getStatus(),
|
||||
payment.getOrder().getId(),
|
||||
payment.getRide() == null ? null : payment.getRide().getId(),
|
||||
payment.getAmountMajor(),
|
||||
payment.getCurrency(),
|
||||
message
|
||||
);
|
||||
}
|
||||
|
||||
private Map<String, Object> buildMetadata(AppUser customer, Payment payment) {
|
||||
Map<String, Object> metadata = new LinkedHashMap<>();
|
||||
metadata.put("orderId", payment.getOrder().getId().toString());
|
||||
metadata.put("rideId", payment.getRide() == null ? null : payment.getRide().getId().toString());
|
||||
metadata.put("userId", customer.getId().toString());
|
||||
metadata.put("productSubtotal", payment.getProductSubtotal());
|
||||
metadata.put("rideFare", payment.getRideFare());
|
||||
metadata.put("grandTotal", payment.getAmountMajor());
|
||||
metadata.put("currency", payment.getCurrency());
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private long toSubunits(BigDecimal amount) {
|
||||
return amount.setScale(2, RoundingMode.HALF_UP)
|
||||
.movePointRight(2)
|
||||
.longValueExact();
|
||||
}
|
||||
|
||||
private String generateReference() {
|
||||
return "CYM-" + UUID.randomUUID();
|
||||
}
|
||||
|
||||
private Payment getPayment(String reference) {
|
||||
return paymentRepository.findByReference(reference)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Payment reference was not found"));
|
||||
}
|
||||
|
||||
private void assertCanAccess(Payment payment) {
|
||||
AppUser currentUser = appUserService.getCurrentUser();
|
||||
if (currentUser.getRole() == Role.ADMIN) {
|
||||
return;
|
||||
}
|
||||
|
||||
AppUser customer = payment.getOrder().getCustomer();
|
||||
if (currentUser.getRole() == Role.CUSTOMER
|
||||
&& customer != null
|
||||
&& currentUser.getId().equals(customer.getId())) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("You cannot access this payment");
|
||||
}
|
||||
|
||||
private PaymentStatus mapPaystackStatus(String status) {
|
||||
return switch (status) {
|
||||
case "abandoned" -> PaymentStatus.ABANDONED;
|
||||
case "reversed" -> PaymentStatus.REFUNDED;
|
||||
default -> PaymentStatus.FAILED;
|
||||
};
|
||||
}
|
||||
|
||||
private void verifyWebhookSignature(String body, String signature) {
|
||||
String secret = paystackProperties.resolvedWebhookSecret();
|
||||
if (secret == null || secret.isBlank()) {
|
||||
throw new IllegalStateException("PAYSTACK_WEBHOOK_SECRET or PAYSTACK_SECRET_KEY is not configured");
|
||||
}
|
||||
if (signature == null || signature.isBlank()) {
|
||||
throw new IllegalArgumentException("Paystack signature is required");
|
||||
}
|
||||
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA512");
|
||||
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA512"));
|
||||
String expected = HexFormat.of().formatHex(mac.doFinal(body.getBytes(StandardCharsets.UTF_8)));
|
||||
if (!constantTimeEquals(expected, signature)) {
|
||||
throw new IllegalArgumentException("Invalid Paystack signature");
|
||||
}
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw exception;
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("Could not verify Paystack signature", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean constantTimeEquals(String expected, String actual) {
|
||||
byte[] expectedBytes = expected.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] actualBytes = actual.getBytes(StandardCharsets.UTF_8);
|
||||
if (expectedBytes.length != actualBytes.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int result = 0;
|
||||
for (int index = 0; index < expectedBytes.length; index++) {
|
||||
result |= expectedBytes[index] ^ actualBytes[index];
|
||||
}
|
||||
return result == 0;
|
||||
}
|
||||
|
||||
private String toJson(JsonNode node) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(node);
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new IllegalStateException("Could not serialize Paystack verification payload", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private record CheckoutQuote(
|
||||
BigDecimal productSubtotal,
|
||||
BigDecimal rideFare,
|
||||
BigDecimal grandTotal,
|
||||
String currency
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.andwati.orders.services;
|
||||
|
||||
import com.andwati.orders.config.PaystackProperties;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.RestClient;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class PaystackClient {
|
||||
|
||||
private final PaystackProperties paystackProperties;
|
||||
private final RestClient restClient;
|
||||
|
||||
public PaystackClient(PaystackProperties paystackProperties, RestClient.Builder restClientBuilder) {
|
||||
this.paystackProperties = paystackProperties;
|
||||
this.restClient = restClientBuilder
|
||||
.baseUrl(paystackProperties.resolvedApiBaseUrl())
|
||||
.build();
|
||||
}
|
||||
|
||||
public JsonNode initializeTransaction(
|
||||
String email,
|
||||
long amountSubunits,
|
||||
String currency,
|
||||
String reference,
|
||||
Map<String, Object> metadata
|
||||
) {
|
||||
assertConfigured();
|
||||
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("email", email);
|
||||
body.put("amount", String.valueOf(amountSubunits));
|
||||
body.put("currency", currency);
|
||||
body.put("reference", reference);
|
||||
body.put("metadata", metadata);
|
||||
|
||||
if (paystackProperties.hasCallbackUrl()) {
|
||||
body.put("callback_url", paystackProperties.callbackUrl());
|
||||
}
|
||||
|
||||
JsonNode response = restClient.post()
|
||||
.uri("/transaction/initialize")
|
||||
.headers(headers -> headers.setBearerAuth(paystackProperties.secretKey()))
|
||||
.body(body)
|
||||
.retrieve()
|
||||
.body(JsonNode.class);
|
||||
|
||||
assertSuccessful(response, "Paystack transaction initialization failed");
|
||||
return response.path("data");
|
||||
}
|
||||
|
||||
public JsonNode verifyTransaction(String reference) {
|
||||
assertConfigured();
|
||||
|
||||
JsonNode response = restClient.get()
|
||||
.uri("/transaction/verify/{reference}", reference)
|
||||
.headers(headers -> headers.setBearerAuth(paystackProperties.secretKey()))
|
||||
.retrieve()
|
||||
.body(JsonNode.class);
|
||||
|
||||
assertSuccessful(response, "Paystack transaction verification failed");
|
||||
return response;
|
||||
}
|
||||
|
||||
private void assertConfigured() {
|
||||
if (!paystackProperties.hasSecretKey()) {
|
||||
throw new IllegalStateException("PAYSTACK_SECRET_KEY is not configured");
|
||||
}
|
||||
}
|
||||
|
||||
private void assertSuccessful(JsonNode response, String fallbackMessage) {
|
||||
if (response == null || !response.path("status").asBoolean(false)) {
|
||||
String message = response == null ? fallbackMessage : response.path("message").asText(fallbackMessage);
|
||||
throw new IllegalStateException(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.andwati.orders.services;
|
||||
|
||||
import com.andwati.orders.model.Order;
|
||||
import com.andwati.orders.model.Ride;
|
||||
|
||||
public record PendingOrderResult(Order order, Ride ride) {
|
||||
}
|
||||
@@ -20,6 +20,12 @@ fare.minimum-fare=${FARE_MINIMUM_FARE:150.00}
|
||||
fare.default-surge-multiplier=${FARE_DEFAULT_SURGE_MULTIPLIER:1.0}
|
||||
fare.currency=${FARE_CURRENCY:KES}
|
||||
|
||||
paystack.secret-key=${PAYSTACK_SECRET_KEY:}
|
||||
paystack.public-key=${PAYSTACK_PUBLIC_KEY:}
|
||||
paystack.callback-url=${PAYSTACK_CALLBACK_URL:}
|
||||
paystack.webhook-secret=${PAYSTACK_WEBHOOK_SECRET:}
|
||||
paystack.api-base-url=${PAYSTACK_API_BASE_URL:https://api.paystack.co}
|
||||
|
||||
app.seed-data=${SEED_DATA:true}
|
||||
app.cors.allowed-origins=${APP_CORS_ALLOWED_ORIGINS:http://localhost:3000}
|
||||
springdoc.api-docs.path=/api-docs
|
||||
|
||||
Reference in New Issue
Block a user