Skip to content

Commit

Permalink
Merge pull request #20 from techmaverick89/feature/19-feature-payment
Browse files Browse the repository at this point in the history
 feat(payment): Add feature payment #19
  • Loading branch information
maverick8899 committed May 27, 2024
2 parents ce18b7e + 934c893 commit 8bef910
Show file tree
Hide file tree
Showing 31 changed files with 1,679 additions and 1,169 deletions.
6 changes: 5 additions & 1 deletion backend/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@
<artifactId>org.eclipse.persistence.core</artifactId>
<version>2.7.12</version>
</dependency>

<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
Expand Down
14 changes: 14 additions & 0 deletions backend/src/main/java/com/dong/DTO/PaymentResDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.dong.DTO;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

@Getter
@Setter
public class PaymentResDTO implements Serializable {
private String status;
private String message;
private String URL;
}
123 changes: 123 additions & 0 deletions backend/src/main/java/com/dong/configs/ConfigVNPay.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package com.dong.configs;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class ConfigVNPay {
public static String vnp_PayUrl = "https://sandbox.vnpayment.vn/paymentv2/vpcpay.html";
public static String vnp_Version = "2.1.0";
public static String vnp_Command = "pay";
public static String vnp_ReturnUrl = "http://localhost:8080/vnpay_jsp/vnpay_return.jsp";
public static String vnp_TmnCode = "IRWGSDFF";
public static String secretKey = "ESYV9705RI8SXEM1ZZDCKBOVGE98OI85";
public static String vnp_ApiUrl = "https://sandbox.vnpayment.vn/merchant_webapi/api/transaction";

public static String md5(String message) {
String digest = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(message.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder(2 * hash.length);
for (byte b : hash) {
sb.append(String.format("%02x", b & 0xff));
}
digest = sb.toString();
} catch (UnsupportedEncodingException ex) {
digest = "";
} catch (NoSuchAlgorithmException ex) {
digest = "";
}
return digest;
}

public static String Sha256(String message) {
String digest = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(message.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder(2 * hash.length);
for (byte b : hash) {
sb.append(String.format("%02x", b & 0xff));
}
digest = sb.toString();
} catch (UnsupportedEncodingException ex) {
digest = "";
} catch (NoSuchAlgorithmException ex) {
digest = "";
}
return digest;
}

//Util for VNPAY
public static String hashAllFields(Map fields) {
List fieldNames = new ArrayList(fields.keySet());
Collections.sort(fieldNames);
StringBuilder sb = new StringBuilder();
Iterator itr = fieldNames.iterator();
while (itr.hasNext()) {
String fieldName = (String) itr.next();
String fieldValue = (String) fields.get(fieldName);
if ((fieldValue != null) && (fieldValue.length() > 0)) {
sb.append(fieldName);
sb.append("=");
sb.append(fieldValue);
}
if (itr.hasNext()) {
sb.append("&");
}
}
return hmacSHA512(secretKey,sb.toString());
}

public static String hmacSHA512(final String key, final String data) {
try {

if (key == null || data == null) {
throw new NullPointerException();
}
final Mac hmac512 = Mac.getInstance("HmacSHA512");
byte[] hmacKeyBytes = key.getBytes();
final SecretKeySpec secretKey = new SecretKeySpec(hmacKeyBytes, "HmacSHA512");
hmac512.init(secretKey);
byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
byte[] result = hmac512.doFinal(dataBytes);
StringBuilder sb = new StringBuilder(2 * result.length);
for (byte b : result) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();

} catch (Exception ex) {
return "";
}
}

public static String getIpAddress(HttpServletRequest request) {
String ipAdress;
try {
ipAdress = request.getHeader("X-FORWARDED-FOR");
if (ipAdress == null) {
ipAdress = request.getRemoteAddr();
}
} catch (Exception e) {
ipAdress = "Invalid IP:" + e.getMessage();
}
return ipAdress;
}

public static String getRandomNumber(int len) {
Random rnd = new Random();
String chars = "0123456789";
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
sb.append(chars.charAt(rnd.nextInt(chars.length())));
}
return sb.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ protected Class<?>[] getRootConfigClasses() {
HibernateConfig.class,
TilesConfigs.class,
WebSocketConfig.class
,
ConfigVNPay.class
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ public void configureMessageBroker(MessageBrokerRegistry config) {

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
registry.addEndpoint("/ws").setAllowedOrigins("http://localhost:3000").withSockJS();
}
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
package com.dong.controllers;
import com.dong.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")

public class ApiNotificationController {

private final NotificationService notificationService;

@Autowired
private NotificationController notificationController;
public ApiNotificationController(NotificationService notificationService) {
this.notificationService = notificationService;
}

@PostMapping("/notify")
public void handleEvent(@RequestBody String event) {

@RequestMapping(value = "/push", method = RequestMethod.GET)
public String pushNotification() {
notificationController.notifyFrontend("This is a test notification!");
return "Notification sent!";
notificationService.sendNotification(event);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package com.dong.controllers;

import com.dong.DTO.PaymentResDTO;
import com.dong.configs.ConfigVNPay;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/api/vnpay")
public class ApiPaymentController {
@GetMapping("/create_payment")
public String create_payment( HttpServletRequest request) throws UnsupportedEncodingException {
//
String orderType = "other";
// long amount = Integer.parseInt(req.getParameter("amount")) * 100;
// String bankCode = req.getParameter("bankCode");
String vnp_IpAddr = ConfigVNPay.getIpAddress(request);
long amount= 1000000;
String vnp_Version = "2.1.0";
String vnp_Command = "pay";
String vnp_TxnRef = ConfigVNPay.getRandomNumber(8);
String vnp_TmnCode = ConfigVNPay.vnp_TmnCode;
Map<String, String> vnp_Params = new HashMap<>();
vnp_Params.put("vnp_Version", vnp_Version);
vnp_Params.put("vnp_Command",vnp_Command);
vnp_Params.put("vnp_TmnCode", vnp_TmnCode);
vnp_Params.put("vnp_Amount", String.valueOf(amount));
vnp_Params.put("vnp_CurrCode", "VND");
vnp_Params.put("vnp_BankCode", "NCB");
vnp_Params.put("vnp_TxnRef", vnp_TxnRef);
vnp_Params.put("vnp_OrderInfo", "Thanh toan don hang:" + vnp_TxnRef);
vnp_Params.put("vnp_Locale", "vn");
vnp_Params.put("vnp_IpAddr", vnp_IpAddr);
vnp_Params.put("vnp_OrderType", orderType);

vnp_Params.put("vnp_ReturnUrl", ConfigVNPay.vnp_ReturnUrl);
Calendar cld = Calendar.getInstance(TimeZone.getTimeZone("Etc/GMT+7"));
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String vnp_CreateDate = formatter.format(cld.getTime());
vnp_Params.put("vnp_CreateDate", vnp_CreateDate);

cld.add(Calendar.MINUTE, 15);
String vnp_ExpireDate = formatter.format(cld.getTime());
vnp_Params.put("vnp_ExpireDate", vnp_ExpireDate);

List fieldNames = new ArrayList(vnp_Params.keySet());
Collections.sort(fieldNames);
StringBuilder hashData = new StringBuilder();
StringBuilder query = new StringBuilder();
Iterator itr = fieldNames.iterator();
while (itr.hasNext()) {
String fieldName = (String) itr.next();
String fieldValue = (String) vnp_Params.get(fieldName);
if ((fieldValue != null) && (fieldValue.length() > 0)) {
//Build hash data
hashData.append(fieldName);
hashData.append('=');
hashData.append(URLEncoder.encode(fieldValue, StandardCharsets.US_ASCII.toString()));
//Build query
query.append(URLEncoder.encode(fieldName, StandardCharsets.US_ASCII.toString()));
query.append('=');
query.append(URLEncoder.encode(fieldValue, StandardCharsets.US_ASCII.toString()));
if (itr.hasNext()) {
query.append('&');
hashData.append('&');
}
}
}
String queryUrl = query.toString();
String vnp_SecureHash = ConfigVNPay.hmacSHA512(ConfigVNPay.secretKey, hashData.toString());
queryUrl += "&vnp_SecureHash=" + vnp_SecureHash;
String paymentUrl = ConfigVNPay.vnp_PayUrl + "?" + queryUrl;
PaymentResDTO paymentResDTO = new PaymentResDTO();
paymentResDTO.setStatus("OK");
paymentResDTO.setMessage("Successfully");
paymentResDTO.setURL(paymentUrl);
// return ResponseEntity.status(HttpStatus.OK).body(paymentResDTO);

return "redirect:" + paymentUrl;
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,11 @@ public String add(@ModelAttribute(value = "customer") @Valid Customer c,
return "customers";
}

@GetMapping("/customers/{id}")
@GetMapping("/addCustomer/{id}")
public String update(Model model, @PathVariable(value = "id") int id) {
// model.addAttribute("customer", this.cusService.getCustomerById(id));
model.addAttribute("service", this.se.getServicesByIdCustomer(id));
model.addAttribute("customer", this.accSer.getAccountsByIdCustomer(id));
return "customers";
return "addCustomer";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public MerchandiseCabinetController() {

@RequestMapping({"merchandisecabinet"})
public String index(Model model) {
model.addAttribute("merchandisecabinet", this.cusSer.getCustomers((Map)null));
model.addAttribute("merchandisecabinet", this.cusSer.getCustomers((null)));
return "merchandisecabinet";
}

Expand All @@ -45,6 +45,7 @@ public String list1(Model model) {
@GetMapping({"/cabinetdetails/{id}"})
public String update(Model model, @PathVariable("id") int id) {
model.addAttribute("cabinetdetails", this.MerSer.getMerchandiseByCustomerId(id));
model.addAttribute("id", id);
return "cabinetdetails";
}
}
Loading

0 comments on commit 8bef910

Please sign in to comment.