purge paystack

This commit is contained in:
2026-06-15 11:38:04 +03:00
parent 8f7cec33ef
commit 6a98e8984e
26 changed files with 85 additions and 730 deletions
-6
View File
@@ -10,10 +10,4 @@ FARE_MINIMUM_FARE=150.00
FARE_DEFAULT_SURGE_MULTIPLIER=1.0
FARE_CURRENCY=KES
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
+1 -1
View File
@@ -1,7 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip
networkTimeout=60000
networkTimeout=300000
retries=3
retryBackOffMs=1000
validateDistributionUrl=true
@@ -2,7 +2,6 @@ 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;
@@ -11,8 +10,7 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
@SpringBootApplication
@EnableConfigurationProperties({
FareProperties.class,
InventoryProperties.class,
PaystackProperties.class
InventoryProperties.class
})
public class OrdersBackendApplication {
@@ -1,32 +0,0 @@
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,7 +14,6 @@ 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;
@@ -32,7 +31,6 @@ 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)
@@ -43,7 +41,6 @@ public class SecurityConfig {
.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")
@@ -1,14 +1,16 @@
package com.andwati.orders.controller;
import com.andwati.orders.dto.request.CheckoutQuoteRequest;
import com.andwati.orders.dto.request.CreateOrderRequest;
import com.andwati.orders.dto.response.CheckoutQuoteResponse;
import com.andwati.orders.dto.response.SimulatedCheckoutResponse;
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")
@Tag(name = "Checkout", description = "Quote totals and simulate ecommerce checkout")
@RestController
@RequestMapping("/api/checkout")
public class CheckoutController {
@@ -27,4 +29,13 @@ public class CheckoutController {
public CheckoutQuoteResponse quote(@Valid @RequestBody CheckoutQuoteRequest request) {
return paymentService.quote(request);
}
@Operation(
summary = "Simulate checkout",
description = "Creates a pending order, optional delivery ride, and a paid local payment record without an external provider."
)
@PostMapping("/simulate")
public SimulatedCheckoutResponse simulate(@Valid @RequestBody CreateOrderRequest request) {
return paymentService.simulateCheckout(request);
}
}
@@ -1,51 +0,0 @@
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);
}
}
@@ -1,19 +0,0 @@
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);
}
}
@@ -1,18 +0,0 @@
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
) {
}
@@ -5,13 +5,13 @@ import com.andwati.orders.model.PaymentStatus;
import java.math.BigDecimal;
import java.util.UUID;
public record PaystackVerifyResponse(
public record SimulatedCheckoutResponse(
String reference,
PaymentStatus status,
UUID orderId,
UUID rideId,
BigDecimal amount,
String currency,
PaymentStatus status,
String message
) {
}
@@ -49,12 +49,6 @@ public class Payment {
@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;
@@ -194,24 +188,6 @@ public class Payment {
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;
}
@@ -1,13 +1,10 @@
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.dto.response.SimulatedCheckoutResponse;
import com.andwati.orders.exception.InsufficientStockException;
import com.andwati.orders.exception.InventoryNotFoundException;
import com.andwati.orders.exception.ProductNotFoundException;
@@ -15,19 +12,12 @@ 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;
@@ -46,9 +36,6 @@ public class PaymentService {
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,
@@ -56,10 +43,7 @@ public class PaymentService {
PaymentRepository paymentRepository,
FareCalculationService fareCalculationService,
OrderService orderService,
AppUserService appUserService,
PaystackClient paystackClient,
PaystackProperties paystackProperties,
ObjectMapper objectMapper
AppUserService appUserService
) {
this.productRepository = productRepository;
this.inventoryItemRepository = inventoryItemRepository;
@@ -67,9 +51,6 @@ public class PaymentService {
this.fareCalculationService = fareCalculationService;
this.orderService = orderService;
this.appUserService = appUserService;
this.paystackClient = paystackClient;
this.paystackProperties = paystackProperties;
this.objectMapper = objectMapper;
}
@Transactional(readOnly = true)
@@ -79,7 +60,7 @@ public class PaymentService {
}
@Transactional
public PaystackInitializeResponse initialize(PaystackInitializeRequest request) {
public SimulatedCheckoutResponse simulateCheckout(CreateOrderRequest request) {
AppUser customer = appUserService.getCurrentUser();
if (customer.getRole() != Role.CUSTOMER) {
throw new IllegalArgumentException("Only customers can checkout");
@@ -88,7 +69,7 @@ public class PaymentService {
CheckoutQuote quote = calculateQuote(request.items(), request.deliveryRide());
PendingOrderResult pendingOrder = orderService.createPendingOrder(
customer,
request.toCreateOrderRequest(),
request,
quote.rideFare(),
quote.currency()
);
@@ -106,76 +87,9 @@ public class PaymentService {
.setStatus(PaymentStatus.PENDING);
paymentRepository.save(payment);
payment.markPaid(buildSimulatedPayload(customer, 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");
return toSimulatedCheckoutResponse(payment);
}
private CheckoutQuote calculateQuote(
@@ -281,33 +195,22 @@ public class PaymentService {
);
}
private PaystackInitializeResponse toInitializeResponse(Payment payment) {
return new PaystackInitializeResponse(
payment.getAuthorizationUrl(),
payment.getAccessCode(),
private SimulatedCheckoutResponse toSimulatedCheckoutResponse(Payment payment) {
return new SimulatedCheckoutResponse(
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
"Checkout simulated successfully"
);
}
private Map<String, Object> buildMetadata(AppUser customer, Payment payment) {
private String buildSimulatedPayload(AppUser customer, Payment payment) {
Map<String, Object> metadata = new LinkedHashMap<>();
metadata.put("provider", "simulated");
metadata.put("reference", payment.getReference());
metadata.put("orderId", payment.getOrder().getId().toString());
metadata.put("rideId", payment.getRide() == null ? null : payment.getRide().getId().toString());
metadata.put("userId", customer.getId().toString());
@@ -315,7 +218,8 @@ public class PaymentService {
metadata.put("rideFare", payment.getRideFare());
metadata.put("grandTotal", payment.getAmountMajor());
metadata.put("currency", payment.getCurrency());
return metadata;
metadata.put("status", PaymentStatus.PAID.name());
return metadata.toString();
}
private long toSubunits(BigDecimal amount) {
@@ -328,80 +232,6 @@ public class PaymentService {
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,
@@ -1,80 +0,0 @@
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);
}
}
}
@@ -20,12 +20,6 @@ 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