提交 0cd7de3d authored 作者: Whispa's avatar Whispa

commit

上级 ea401cd3
...@@ -60,6 +60,23 @@ ...@@ -60,6 +60,23 @@
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
<!--<version>2.8.5</version>--> <!--<version>2.8.5</version>-->
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<!-- https://mvnrepository.com/artifact/de.odysseus.staxon/staxon -->
<dependency>
<groupId>de.odysseus.staxon</groupId>
<artifactId>staxon</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>6.14.0</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId> <artifactId>spring-boot-starter-oauth2-client</artifactId>
......
package com.example.afrishop_v3.config;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONObject;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.apache.http.conn.ssl.SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
/**
* @author Theresa
*/
public class ApiConnection {
final private String url;
/**
* @param url - Flutterwave API url
*/
public ApiConnection(String url) {
this.url = url;
this.enforceTlsV1point2();
}
private void enforceTlsV1point2() {
try {
SSLContext sslContext = SSLContexts.custom()
.useTLS()
.build();
SSLConnectionSocketFactory f = new SSLConnectionSocketFactory(
sslContext,
new String[]{"TLSv1.2"},
null,
BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(f)
.build();
Unirest.setHttpClient(httpClient);
} catch (NoSuchAlgorithmException | KeyManagementException ex) {
Logger.getLogger(ApiConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Connects to and queries Flutterwave API with POST
*
* @param query - APIQuery containing parameters to send
* @return - JSONObject containing API response
*/
public JSONObject connectAndQuery(ApiQuery query) {
try {
HttpResponse<JsonNode> queryForResponse = Unirest.post(url)
.header("Accept", "application/json")
.fields(query.getParams())
.asJson();
try{
return queryForResponse.getBody().getObject();
}catch(Exception ex){}
} catch (UnirestException e) {
}
return null;
}
/**
* Connects to and queries API with POST
*
* @param query - HashMap containing parameters to send
* @return - JSONObject containing API response
*/
public JSONObject connectAndQuery(HashMap<String, Object> query) {
try {
HttpResponse<JsonNode> queryForResponse = Unirest.post(url)
.header("Accept", "application/json")
.fields(query)
.asJson();
return queryForResponse.getBody().getObject();
} catch (UnirestException e) {
}
return null;
}
/**
* Used to send a GET request to the Flutterwave API
*
* @return - JSONObject containing the API response
*/
public JsonNode connectAndQueryWithGet() {
try {
HttpResponse<JsonNode> queryForResponse = Unirest.get(url)
.header("content-type", "application/json")
.asJson();
return queryForResponse.getBody();
} catch (UnirestException e) {
System.out.println("Cant query at this time!");
}
return null;
}
}
package com.example.afrishop_v3.config;
import java.util.HashMap;
public class ApiQuery {
final private HashMap<String, Object> queryMap;
/**
* Initializes a new query map
*/
public ApiQuery() {
this.queryMap = new HashMap<>();
}
/**
* Used to add a parameter to the query map
*
* @param key
* @param value
*/
public void putParams(String key, Object value) {
this.queryMap.put(key, value);
}
public HashMap<String, Object> getParams() {
return this.queryMap;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.afrishop_v3.config;
import org.json.JSONException;
import org.json.JSONObject;
import java.awt.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import static com.example.afrishop_v3.config.Encryption.encryptData;
import static com.example.afrishop_v3.config.Encryption.getKey;
/**
*
* @author Theresa
*/
public class CardCharge {
JSONObject api=new JSONObject();
Endpoints ed=new Endpoints();
ApiConnection apiConnection;
Encryption e=new Encryption();
private String cardno,cvv,expirymonth,expiryyear,currency,country,pin,suggested_auth,
amount,email,phonenumber,firstname,lastname,txRef,redirect_url,device_fingerprint,IP,
charge_type;
private String transactionreference,otp, authUrl;
/**
*
*
* @return JSONObject
*/
public JSONObject setJSON() {
JSONObject json=new JSONObject();
try{
json.put("cardno", this.getCardno());
json.put("cvv", this.getCvv());
json.put("currency", this.getCurrency());
json.put("country", this.getCountry());
json.put("amount", this.getAmount());
json.put("expiryyear", this.getExpiryyear());
json.put("expirymonth", this.getExpirymonth());
json.put("email", this.getEmail());
json.put("IP", this.getIP());
json.put("txRef", this.getTxRef());
json.put("device_fingerprint", this.getDevice_fingerprint());
// json.put("pin", this.getPin());
//json.put("suggested_auth", this.getSuggested_auth());
json.put("firstname", this.getFirstname());
json.put("lastname", this.getLastname());
json.put("redirect_url", this.getRedirect_url());
json.put("charge_type", this.getCharge_type());
}catch( JSONException ex){ex.getMessage();}
return json;
}
public JSONObject chargeMasterAndVerveCard() throws JSONException {
JSONObject json= setJSON();
json.put("PBFPubKey",RaveConstant.PUBLIC_KEY);
json.put("pin",this.getPin() );
json.put("suggested_auth",this.getSuggested_auth() );
String message= json.toString();
String encrypt_secret_key=getKey(RaveConstant.SECRET_KEY);
String client= encryptData(message,encrypt_secret_key);
Charge ch=new Charge();
return ch.charge(client);
}
public JSONObject chargeMasterAndVerveCard(boolean polling) {
JSONObject json= setJSON();
json.put("PBFPubKey",RaveConstant.PUBLIC_KEY);
json.put("pin",this.getPin() );
json.put("suggested_auth",this.getSuggested_auth() );
Polling p=new Polling();
return p.handleTimeoutCharge(json);
}
public JSONObject chargeVisaAndIntl() throws JSONException {
JSONObject json= setJSON();
json.put("PBFPubKey",RaveConstant.PUBLIC_KEY);
json.put("redirect_url", this.getRedirect_url() );
String message= json.toString();
String encrypt_secret_key=getKey(RaveConstant.SECRET_KEY);
String client= encryptData(message,encrypt_secret_key);
Charge ch=new Charge();
return ch.charge(client);
}
public JSONObject chargeVisaAndIntl(boolean polling) throws JSONException {
JSONObject json= setJSON();
json.put("PBFPubKey",RaveConstant.PUBLIC_KEY);
json.put("redirect_url", this.getRedirect_url() );
Polling p=new Polling();
return p.handleTimeoutCharge(json);
}
/*
if AuthMode::"PIN"
@params transaction reference(flwRef),OTP
* @return JSONObject
*/
public JSONObject validateCardCharge(){
Charge vch= new Charge();
return vch.validateCardCharge(this.getTransactionreference(), this.getOtp());
}
//if timeout
public JSONObject validateCardCharge(boolean polling){
Polling p=new Polling();
return p.validateCardChargeTimeout(this.getTransactionreference(), this.getOtp());
}
/*
if AuthMode::"VBSECURE"or "AVS_VBVSECURECODE"
@params authUrl This requires that you copy the authurl returned in the response
and paste it in the argument and it opens a small window for card validation
*/
public void validateCardChargeVB(){
if (Desktop.isDesktopSupported()) {
try{
Desktop.getDesktop().browse(new URI(this.getAuthUrl()));
}catch(URISyntaxException | IOException ex){}
}
}
/**
* @return the cardno
*/
public String getCardno() {
return cardno;
}
/**
* @param cardno the cardno to set
* @return CardCharge
*/
public CardCharge setCardno(String cardno) {
this.cardno = cardno;
return this;
}
/**
* @return the cvv
*/
public String getCvv() {
return cvv;
}
/**
* @param cvv the cvv to set
* @return CardCharge
*/
public CardCharge setCvv(String cvv) {
this.cvv = cvv;
return this;
}
/**
* @return the expirymonth
*/
public String getExpirymonth() {
return expirymonth;
}
/**
* @param expirymonth the expirymonth to set
* @return CardCharge
*/
public CardCharge setExpirymonth(String expirymonth) {
this.expirymonth = expirymonth;
return this;
}
/**
* @return the expiryyear
*/
public String getExpiryyear() {
return expiryyear;
}
/**
* @param expiryyear the expiryyear to set
* @return CardCharge
*/
public CardCharge setExpiryyear(String expiryyear) {
this.expiryyear = expiryyear;
return this;
}
/**
* @return the currency
*/
public String getCurrency() {
return currency;
}
/**
* @param currency the currency to set
* @return CardCharge
*/
public CardCharge setCurrency(String currency) {
this.currency = currency;
return this;
}
/**
* @return the country
*/
public String getCountry() {
return country;
}
/**
* @param country the country to set
* @return CardCharge
*/
public CardCharge setCountry(String country) {
this.country = country;
return this;
}
/**
* @return the pin
*/
public String getPin() {
return pin;
}
/**
* @param pin the pin to set
* @return CardCharge
*/
public CardCharge setPin(String pin) {
this.pin = pin;
return this;
}
/**
* @return the suggested_auth
*/
public String getSuggested_auth() {
return suggested_auth;
}
/**
* @param suggested_auth the suggested_auth to set
* @return CardCharge
*/
public CardCharge setSuggested_auth(String suggested_auth) {
this.suggested_auth = suggested_auth;
return this;
}
/**
* @return the amount
*/
public String getAmount() {
return amount;
}
/**
* @param amount the amount to set
* @return CardCharge
*/
public CardCharge setAmount(String amount) {
this.amount = amount;
return this;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
* @return CardCharge
*/
public CardCharge setEmail(String email) {
this.email = email;
return this;
}
/**
* @return the phonenumber
*/
public String getPhonenumber() {
return phonenumber;
}
/**
* @param phonenumber the phonenumber to set
* @return CardCharge
*/
public CardCharge setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
return this;
}
/**
* @return the firstname
*/
public String getFirstname() {
return firstname;
}
/**
* @param firstname the firstname to set
* @return CardCharge
*/
public CardCharge setFirstname(String firstname) {
this.firstname = firstname;
return this;
}
/**
* @return the lastname
*/
public String getLastname() {
return lastname;
}
/**
* @param lastname the lastname to set
* @return CardCharge
*/
public CardCharge setLastname(String lastname) {
this.lastname = lastname;
return this;
}
/**
* @return the IP
*/
public String getIP() {
return IP;
}
/**
* @param IP the IP to set
* @return CardCharge
*/
public CardCharge setIP(String IP) {
this.IP = IP;
return this;
}
/**
* @return the txRef
*/
public String getTxRef() {
return txRef;
}
/**
* @param txRef the txRef to set
* @return CardCharge
*/
public CardCharge setTxRef(String txRef) {
this.txRef = txRef;
return this;
}
/**
* @return the redirect_url
*/
public String getRedirect_url() {
return redirect_url;
}
/**
* @param redirect_url the redirect_url to set
* @return CardCharge
*/
public CardCharge setRedirect_url(String redirect_url) {
this.redirect_url = redirect_url;
return this;
}
/**
* @return the device_fingerprint
*/
public String getDevice_fingerprint() {
return device_fingerprint;
}
/**
* @param device_fingerprint the device_fingerprint to set
* @return CardCharge
*/
public CardCharge setDevice_fingerprint(String device_fingerprint) {
this.device_fingerprint = device_fingerprint;
return this;
}
/**
* @return the charge_type
*/
public String getCharge_type() {
return charge_type;
}
/**
* @param charge_type the charge_type to set
* @return CardCharge
*/
public CardCharge setCharge_type(String charge_type) {
this.charge_type = charge_type;
return this;
}
/**
* @return the transaction_reference
*/
public String getTransactionreference() {
return transactionreference;
}
/**
* @param transaction_reference the transaction_reference to set
* @return CardCharge
*/
public CardCharge setTransactionreference(String transaction_reference) {
this.transactionreference= transaction_reference;
return this;
}
/**
* @return the otp
*/
public String getOtp() {
return otp;
}
/**
* @param otp the otp to set
* @return CardCharge
*/
public CardCharge setOtp(String otp) {
this.otp = otp;
return this;
}
/**
* @return the authUrl
*/
public String getAuthUrl() {
return authUrl;
}
/**
* @param authUrl the authUrl to set
* @return CardCharge
*/
public CardCharge setAuthUrl(String authUrl) {
this.authUrl = authUrl;
return this;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.afrishop_v3.config;
import org.json.JSONObject;
/**
*
* @author Theresa
*/
public class Charge {
ApiConnection apiConnection;
Endpoints ed= new Endpoints();
/**
*
* @param client
* @return JSONObject
*/
//for all charges
public JSONObject charge(String client){
this.apiConnection = new ApiConnection(ed.getChargeEndPoint());
String alg="3DES-24";
ApiQuery api=new ApiQuery();
api.putParams("PBFPubKey", RaveConstant.PUBLIC_KEY);
api.putParams("client", client);
api.putParams("alg", alg);
return this.apiConnection.connectAndQuery(api);
}
/**
*
*
* @return JSONObject
* @param transaction_reference
* @param otp
*
*/
public JSONObject validateAccountCharge(String transaction_reference, String otp){
this.apiConnection = new ApiConnection(ed.getValidateAccountChargeEndPoint());
ApiQuery api=new ApiQuery();
api.putParams("PBFPubKey",RaveConstant.PUBLIC_KEY);
api.putParams("transactionreference", transaction_reference);
api.putParams("otp", otp);
return this.apiConnection.connectAndQuery(api);
}
/**
*
*
* @return JSONObject
* @param transaction_reference
* @param otp
*
*/
public JSONObject validateCardCharge(String transaction_reference, String otp){
this.apiConnection = new ApiConnection(ed.getValidateCardChargeEndPoint());
ApiQuery api=new ApiQuery();
api.putParams("PBFPubKey",RaveConstant.PUBLIC_KEY);
api.putParams("transaction_reference", transaction_reference);
api.putParams("otp", otp);
return this.apiConnection.connectAndQuery(api);
}
}
package com.example.afrishop_v3.config;
/**
* @Auther: wudepeng
* @Date: 2020/02/27
* @Description:DPO配置类 (正式环境)
*/
public class DpoConfig {
//创建交易请求
public final static String CREATE_TOKEN_REQUEST = "createToken";
//校验交易请求
public final static String VERIFY_TOKEN_REQUEST = "verifyToken";
//取消交易请求
public final static String CANCEL_TOKEN_REQUEST = "cancelToken";
//CompanyToken
public final static String COMPANY_TOKEN = "E6759E15-C2F3-4526-ADEF-8FC0017BB1C4";
//请求成功的状态码
public final static String SUCCESS_CODE = "000";
//DPO支付API
public final static String PAYMENT_API = "https://secure.3gdirectpay.com/API/v6/";
//重定向地址
public final static String REDIRECT_URL = "https://secure.3gdirectpay.com/pay.asp";
//服务类型
public final static String SERVICE_TYPE = "35711";
//回调地址
public final static String NOTIFY_URL = "https://app.afrieshop.com/zion/dpo/notify";
//取消地址
public final static String BACK_URL = "https://app.afrieshop.com/zion/dpo/cancel";
//支付成功页面
public final static String SUCCESS_URL = "https://www.afrieshop.com/payment_successful";
//支付失败页面
public final static String FAILED_URL = "https://www.afrieshop.com/payment_failed";
//支付成功页面
public final static String MOBILE_SUCCESS_URL = "https://m.afrieshop.com/#/Paysuccess";
//支付失败页面
public final static String MOBILE_FAILED_URL = "https://m.afrieshop.com/#/PayFail";
}
package com.example.afrishop_v3.config;
/**
* @Auther: wudepeng
* @Date: 2020/03/13
* @Description:DPO配置(测试环境)
*/
public class DpoConfigTest {
//创建交易请求
public final static String CREATE_TOKEN_REQUEST = "createToken";
//校验交易请求
public final static String VERIFY_TOKEN_REQUEST = "verifyToken";
//取消交易请求
public final static String CANCEL_TOKEN_REQUEST = "cancelToken";
//CompanyToken
public final static String COMPANY_TOKEN = "9F416C11-127B-4DE2-AC7F-D5710E4C5E0A";
//请求成功的状态码
public final static String SUCCESS_CODE = "000";
//DPO支付API
public final static String PAYMENT_API = "https://secure1.sandbox.directpay.online/API/v6/";
//重定向地址
public final static String REDIRECT_URL = "https://secure1.sandbox.directpay.online/payv2.php";
//回调地址
public final static String NOTIFY_URL = "https://dev.diaosaas.com/zion/dpo/notify";
//支付成功页面
public final static String SUCCESS_URL = "https://dev.diaosaas.com/afrishop_web/payment_successful";
//支付失败页面
public final static String FAILED_URL = "https://dev.diaosaas.com/afrishop_web/payment_failed";
//支付成功页面
public final static String MOBILE_SUCCESS_URL = "https://m.afrieshop.com/#/Paysuccess";
//支付失败页面
public final static String MOBILE_FAILED_URL = "https://m.afrieshop.com/#/PayFail";
//取消地址
public final static String BACK_URL = "https://dev.diaosaas.com/zion/dpo/cancel";
//服务类型
public final static Integer SERVICE_TYPE = 5525;
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.afrishop_v3.config;
import org.json.JSONObject;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Theresa
*/
public class Encryption {
RaveConstant keys= new RaveConstant();
// Method to turn bytes in hex
public static String toHexStr(byte[] bytes){
StringBuilder builder = new StringBuilder();
for(int i = 0; i < bytes.length; i++ ){
builder.append(String.format("%02x", bytes[i]));
}
return builder.toString();
}
// this is the getKey function that generates an encryption Key for you by passing your Secret Key as a parameter.
public static String getKey(String seedKey) {
try {
MessageDigest md = MessageDigest.getInstance("md5");
byte[] hashedString = md.digest(seedKey.getBytes("utf-8"));
byte[] subHashString = toHexStr(Arrays.copyOfRange(hashedString, hashedString.length - 12, hashedString.length)).getBytes("utf-8");
String subSeedKey = seedKey.replace("FLWSECK-", "");
subSeedKey = subSeedKey.substring(0, 12);
byte[] combineArray = new byte[24];
System.arraycopy(subSeedKey.getBytes(), 0, combineArray, 0, 12);
System.arraycopy(subHashString, subHashString.length - 12, combineArray, 12, 12);
return new String(combineArray);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
Logger.getGlobal().log(Level.SEVERE, null, ex);
}
return null;
}
// This is the encryption function that encrypts your payload by passing the stringified format and your encryption Key.
public static String encryptData(String message, String _encryptionKey) {
try {
final byte[] digestOfPassword = _encryptionKey.getBytes("utf-8");
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
final SecretKey key = new SecretKeySpec( keyBytes , "DESede");
final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
return Base64.getEncoder().encodeToString(cipherText);
} catch (UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
return "";
}
}
/**
*
* @param api(JSON object)
* @return String
*/
public String encryptParameters(JSONObject api) {
try{
api.put("PBFPubKey",RaveConstant.PUBLIC_KEY);
}catch(Exception ex){}
String message= api.toString();
String encrypt_secret_key=getKey(RaveConstant.SECRET_KEY);
String encrypted_message= encryptData(message,encrypt_secret_key);
return encrypted_message;
}
/**
*
*
* @return String
* @param api
*
*/
public String encryptParametersPreAuth(JSONObject api){
try{
api.put("PBFPubKey","FLWPUBK-8cd258c49f38e05292e5472b2b15906e-X");
}catch(Exception ex){}
String message= api.toString();
String encrypt_secret_key=getKey("FLWSECK-c51891678d48c39eff3701ff686bdb69-X");
String encrypted_message= encryptData(message,encrypt_secret_key);
return encrypted_message;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.afrishop_v3.config;
/**
*
* @author Theresa
*/
public class Endpoints {
RaveConstant key= new RaveConstant();
String staging_url="https://ravesandboxapi.flutterwave.com/";
String live_url="https://api.ravepay.co/";
String url;
public String BANK_ENDPOINT;
public static String CHARGE_ENDPOINT;
public static String CARD_VALIDATE_ENDPOINT;
public static String ACCOUNT_VALIDATE_ENDPOINT;
public static String TIMEOUT_ENDPOINT;
public static String POLL_ENDPOINT;
public static String FEES_ENDPOINT;
public static String REFUND_ENDPOINT;
public static String FOREX_ENDPOINT;
public static String VERIFY_TRANSACTION_ENDPOINT;
public static String VERIFY_XREQUERY_ENDPOINT;
public static String CAPTURE_ENDPOINT;
public static String REFUNDVOID_ENDPOINT;
public static String CHARGE_TIMEOUT_ENDPOINT;
public static String VALIDATE_CARD_CHARGE_TIMEOUT_ENDPOINT;
public static String VALIDATE_ACCOUNT_CHARGE_TIMEOUT_ENDPOINT;
void init(){
if(RaveConstant.ENVIRONMENT.toString().equalsIgnoreCase("live")){
url=live_url;
}
else {
url=staging_url;
}
BANK_ENDPOINT= url+"flwv3-pug/getpaidx/api/flwpbf-banks.js?json=1";
CHARGE_ENDPOINT =url+"flwv3-pug/getpaidx/api/charge";
CARD_VALIDATE_ENDPOINT = url+"flwv3-pug/getpaidx/api/validatecharge";
ACCOUNT_VALIDATE_ENDPOINT=url+"flwv3-pug/getpaidx/api/validate";
TIMEOUT_ENDPOINT=url+"flwv3-pug/getpaidx/api/charge?use_polling=1";
POLL_ENDPOINT=url+"flwv3-pug/getpaidx/api/requests/RCORE_CHREQ_3FC28781846AD8E1C598";
FEES_ENDPOINT=url+"flwv3-pug/getpaidx/api/fee";
REFUND_ENDPOINT=url+"gpx/merchant/transactions/refund";
FOREX_ENDPOINT=url+"flwv3-pug/getpaidx/api/forex";
VERIFY_TRANSACTION_ENDPOINT=url+"flwv3-pug/getpaidx/api/verify";
VERIFY_XREQUERY_ENDPOINT=url+"flwv3-pug/getpaidx/api/xrequery";
CAPTURE_ENDPOINT=url+"flwv3-pug/getpaidx/api/capture";
REFUNDVOID_ENDPOINT=url+"flwv3-pug/getpaidx/api/refundorvoid";
CHARGE_TIMEOUT_ENDPOINT=url+"flwv3-pug/getpaidx/api/charge?use_polling=1";
VALIDATE_CARD_CHARGE_TIMEOUT_ENDPOINT=url+"flwv3-pug/getpaidx/api/validatecharge?use_polling=1";
VALIDATE_ACCOUNT_CHARGE_TIMEOUT_ENDPOINT= url+"flwv3-pug/getpaidx/api/validate?use_polling=1";
}
public String getBankEndPoint(){
init();
return BANK_ENDPOINT;
}
public String getChargeEndPoint(){
init();
return CHARGE_ENDPOINT;
}
public String getValidateCardChargeEndPoint(){
init();
return CARD_VALIDATE_ENDPOINT;
}
public String getValidateAccountChargeEndPoint(){
init();
return ACCOUNT_VALIDATE_ENDPOINT;
}
public String getFeesEndPoint(){
init();
return FEES_ENDPOINT;
}
public String getRefundEndPoint(){
init();
return REFUND_ENDPOINT;
}
public String getForexEndPoint(){
init();
return FOREX_ENDPOINT;
}
public String getVerifyEndPoint(){
init();
return VERIFY_TRANSACTION_ENDPOINT;
}
public String getVerifyXrequeryEndPoint(){
init();
return VERIFY_XREQUERY_ENDPOINT;
}
public String getCaptureEndPoint(){
init();
return CAPTURE_ENDPOINT;
}
public String getRefundOrVoidEndPoint(){
init();
return REFUNDVOID_ENDPOINT;
}
public String getChargeTimeoutEndpoint(){
init();
return CHARGE_TIMEOUT_ENDPOINT;
}
public String getValidateCardChargeTimeoutEndpoint(){
init();
return VALIDATE_CARD_CHARGE_TIMEOUT_ENDPOINT;
}
public String getValidateAccountChargeTimeoutEndpoint(){
init();
return VALIDATE_ACCOUNT_CHARGE_TIMEOUT_ENDPOINT;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.afrishop_v3.config;
/**
*
* @author Theresa
*/
public enum Environment {
STAGING,
LIVE
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.afrishop_v3.config;
import org.json.JSONException;
import org.json.JSONObject;
import static com.example.afrishop_v3.config.Encryption.encryptData;
/**
*
* @author Theresa
*/
public class Polling {
ApiConnection apiConnection;
final private Endpoints ed=new Endpoints();
Encryption e=new Encryption();
RaveConstant key=new RaveConstant();
//if timeout, start polling
/**
*
*@param json
* @throws JSONException
* @return JSONObject
*/
public JSONObject handleTimeoutCharge(JSONObject json){
this.apiConnection = new ApiConnection(ed.getChargeTimeoutEndpoint());
JSONObject tcharge= null;
String message= json.toString();
String encrypt_secret_key=Encryption.getKey( RaveConstant.SECRET_KEY);
String client= encryptData(message,encrypt_secret_key);
String alg="3DES-24";
ApiQuery api=new ApiQuery();
api.putParams("PBFPubKey", RaveConstant.PUBLIC_KEY);
api.putParams("client", client);
api.putParams("alg", alg);
tcharge= this.apiConnection.connectAndQuery(api);
return tcharge;
}
/**
*
* @param transaction_reference
* @param otp
* @return String
*/
public JSONObject validateCardChargeTimeout(String transaction_reference, String otp){
this.apiConnection = new ApiConnection(ed.getValidateCardChargeTimeoutEndpoint());
ApiQuery api=new ApiQuery();
api.putParams("PBFPubKey",RaveConstant.PUBLIC_KEY);
api.putParams("transaction_reference", transaction_reference);
api.putParams("otp", otp);
return this.apiConnection.connectAndQuery(api);
}
/**
*
* @param transaction_reference
* @param otp
* @return String
*/
public JSONObject validateAccountChargeTimeout(String transaction_reference, String otp){
this.apiConnection = new ApiConnection(ed.getValidateAccountChargeTimeoutEndpoint());
ApiQuery api=new ApiQuery();
api.putParams("PBFPubKey",RaveConstant.PUBLIC_KEY);
api.putParams("transaction_reference", transaction_reference);
api.putParams("otp", otp);
return this.apiConnection.connectAndQuery(api);
}
}
package com.example.afrishop_v3.config;
/**
* @author Theresa
*/
public class RaveConstant {
public static String SECRET_KEY;
public static String PUBLIC_KEY;
public static Environment ENVIRONMENT;
}
package com.example.afrishop_v3.controllers; package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.base.Result; import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.base.StateConstant;
import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.models.TbCfAddress; import com.example.afrishop_v3.models.TbCfAddress;
import com.example.afrishop_v3.models.TbCfUserInfo;
import com.example.afrishop_v3.repository.TbCfAddressRepository; import com.example.afrishop_v3.repository.TbCfAddressRepository;
import com.example.afrishop_v3.repository.UserRepository;
import com.example.afrishop_v3.security.services.AuthenticationUser; import com.example.afrishop_v3.security.services.AuthenticationUser;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController @RestController
@RequestMapping("/address") @RequestMapping("/address")
public class AddressController extends Controller{ public class AddressController extends Controller{
private final TbCfAddressRepository repository; private final TbCfAddressRepository repository;
private final UserRepository userRepository;
private final AuthenticationUser user; private final AuthenticationUser user;
public AddressController(TbCfAddressRepository repository, AuthenticationUser user) { public AddressController(TbCfAddressRepository repository, UserRepository userRepository, AuthenticationUser user) {
this.repository = repository; this.repository = repository;
this.userRepository = userRepository;
this.user = user; this.user = user;
} }
...@@ -36,4 +44,37 @@ public class AddressController extends Controller{ ...@@ -36,4 +44,37 @@ public class AddressController extends Controller{
address.setAddressId(addressId); address.setAddressId(addressId);
return new Result<>(repository.save(address)); return new Result<>(repository.save(address));
} }
@PutMapping(value = "/default/{addressId}")
public Result configDefaultAddress(@PathVariable("addressId") String addressId) {
Optional<TbCfAddress> byId = repository.findById(addressId);
if( byId.isPresent() ){
TbCfAddress address = byId.get();
TbCfUserInfo user = this.user.user();
address.setDefaultFlag(StateConstant.VALID);
repository.save(address);
user.setAddress(address);
userRepository.save(user);
repository.resetToDefault(user.getUserId());
return new Result<>(ResultCodeEnum.SUCCESS.getDesc());
}
return new Result<>().setCode(ResultCodeEnum.ERROR.getCode()).setMessage(ResultCodeEnum.ERROR.getDesc());
}
@GetMapping(value = "/default")
public Result getDefaultAddress() {
TbCfAddress address = user.user().getAddress();
return new Result<>(address, address == null ? ResultCodeEnum.SERVICE_ERROR.getCode() : ResultCodeEnum.SUCCESS.getCode(),"");
}
} }
package com.example.afrishop_v3.controllers; package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.base.Result; import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.base.StateConstant;
import com.example.afrishop_v3.config.DomainProperties;
import com.example.afrishop_v3.enums.ResultCodeEnum; import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.enums.SexEnum;
import com.example.afrishop_v3.enums.UserTypeEnum;
import com.example.afrishop_v3.models.TbCfCoupon;
import com.example.afrishop_v3.models.TbCfToicoupon;
import com.example.afrishop_v3.models.TbCfUserInfo; import com.example.afrishop_v3.models.TbCfUserInfo;
import com.example.afrishop_v3.payload.request.LoginRequest; import com.example.afrishop_v3.payload.request.LoginRequest;
import com.example.afrishop_v3.payload.response.JwtResponse;
import com.example.afrishop_v3.payload.response.MessageResponse; import com.example.afrishop_v3.payload.response.MessageResponse;
import com.example.afrishop_v3.repository.TbCfCouponRepository;
import com.example.afrishop_v3.repository.TbCfToicouponRepository;
import com.example.afrishop_v3.repository.UserRepository; import com.example.afrishop_v3.repository.UserRepository;
import com.example.afrishop_v3.security.jwt.JwtUtils; import com.example.afrishop_v3.security.jwt.JwtUtils;
import com.example.afrishop_v3.security.services.UserDetailsImpl; import com.example.afrishop_v3.security.services.UserDetailsImpl;
import com.example.afrishop_v3.util.IdUtil; import com.example.afrishop_v3.util.IdUtil;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.Collection; import java.io.IOException;
import java.util.List; import java.io.InputStream;
import java.util.Optional; import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@CrossOrigin(origins = "*", maxAge = 3600) @CrossOrigin(origins = "*", maxAge = 3600)
...@@ -32,22 +47,28 @@ public class AuthController { ...@@ -32,22 +47,28 @@ public class AuthController {
private final AuthenticationManager authenticationManager; private final AuthenticationManager authenticationManager;
private final UserRepository userRepository; private final UserRepository userRepository;
private final TbCfCouponRepository couponRepository;
private final TbCfToicouponRepository toicouponRepository;
private final PasswordEncoder encoder; private final PasswordEncoder encoder;
private final DomainProperties domainProperties;
private final JwtUtils jwtUtils; private final JwtUtils jwtUtils;
public AuthController(AuthenticationManager authenticationManager, UserRepository userRepository, PasswordEncoder encoder, JwtUtils jwtUtils) { public AuthController(AuthenticationManager authenticationManager, UserRepository userRepository, TbCfCouponRepository couponRepository, TbCfToicouponRepository toicouponRepository, PasswordEncoder encoder, DomainProperties domainProperties, JwtUtils jwtUtils) {
this.authenticationManager = authenticationManager; this.authenticationManager = authenticationManager;
this.userRepository = userRepository; this.userRepository = userRepository;
this.couponRepository = couponRepository;
this.toicouponRepository = toicouponRepository;
this.encoder = encoder; this.encoder = encoder;
this.domainProperties = domainProperties;
this.jwtUtils = jwtUtils; this.jwtUtils = jwtUtils;
} }
@PostMapping("/signin") @PostMapping("/signin")
public Result authenticateUser(@RequestBody LoginRequest loginRequest) { public Result authenticateUser(@RequestBody LoginRequest loginRequest) {
Optional<TbCfUserInfo> byAccount = userRepository.findByAccount(loginRequest.getAccount()); Optional<TbCfUserInfo> byAccount = userRepository.findByFirebaseUid(loginRequest.getAccount());
if( !byAccount.isPresent() ){ if( !byAccount.isPresent() ){
return new Result<>(ResultCodeEnum.VALIDATE_ERROR,"User not found"); return new Result<>(ResultCodeEnum.VALIDATE_ERROR,"User not found");
} }
...@@ -99,4 +120,130 @@ public class AuthController { ...@@ -99,4 +120,130 @@ public class AuthController {
return ResponseEntity.ok(new Result<>(userInfo,"User createdSuccessfully")); return ResponseEntity.ok(new Result<>(userInfo,"User createdSuccessfully"));
} }
private boolean validateFirebaseToken(String token) {
FirebaseOptions options;
try {
InputStream in = new ClassPathResource("afrishop-6e142-firebase-adminsdk-ypj91-b5e0248586.json").getInputStream();
// InputStream in = ResourceUtils.getURL("src/main/resources/afrishop-6e142-firebase-adminsdk-ypj91-b5e0248586.json").openStream();
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(in))
.setDatabaseUrl("https://afrishop-6e142.firebaseio.com")
.build();
FirebaseApp firebaseApp;
try {
firebaseApp = FirebaseApp.getInstance("other");
} catch (IllegalStateException e) {
firebaseApp = FirebaseApp.initializeApp(options, "other");
}
FirebaseAuth instance = FirebaseAuth.getInstance(firebaseApp);
System.out.println(firebaseApp.getName());
System.out.println(token);
try {
FirebaseToken firebaseToken = instance.verifyIdToken(token);
// verify token successfully
return true;
} catch (FirebaseAuthException e) {
// verify token error
System.out.println("verify token error");
System.out.println(e.getMessage());
}
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
@PostMapping(value = "/register/user")
public Result checkFirebase(@RequestBody TbCfUserInfo user) throws ParseException {
//Data to be userInfoVo
// {
// "firebaseUid":"firebaseUid",
// "name":"name",
// "email":"email",
// "phone":"phone",
// "birthDate":"date",
// "token":"token",
// }
// Check if firebase token is valid
boolean isTokenValid = user.getToken() != null && validateFirebaseToken(user.getToken());
// if valid do sign in if firebase Uid exist in database or register as new user
if (isTokenValid) {
//Query to find user from database by firebase uid
Optional<TbCfUserInfo> optional = userRepository.findByFirebaseUid(user.getFirebaseUid());
if ( !optional.isPresent() ) {
String userid = IdUtil.createIdbyUUID();
user.setPassword(encoder.encode(user.getFirebaseUid()));
user.setUserId(userid);
fillUserNecessayInfo(user);
userRepository.save(user);
//赠送用户优惠券
List<TbCfCoupon> couponVailList = couponRepository.findAllByCouponVaild(1);
//获取当前时间的时分秒
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");//设置日期格式
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, +7);
Date time = c.getTime();
Date startDate = sdf.parse(sdf.format(new Date()));
Date endDate = sdf.parse(sdf.format(time));
for (TbCfCoupon tbCfCoupon : couponVailList) {
TbCfToicoupon toi = new TbCfToicoupon();
//把上面获取到的值,赋值到实体类中
toi.setToitableId(IdUtil.createIdbyUUID());
toi.setCoupon(tbCfCoupon);
toi.setUserId(userid);
toi.setStartTime(startDate);
toi.setIdentification(3);
toi.setEnableFlag(1);
toi.setEndTime(endDate);
toicouponRepository.save(toi);
}
} else {
user = optional.get();
if( user.getPassword() == null ){
user.setPassword(encoder.encode(user.getFirebaseUid()));// Assign user from database to the user we have to return back to request
userRepository.save(user);
}
}
// generate token codes has been moved downwards from if condition of checking if user doesn't exist in database, because even if
// user exist we have to generate token also
//注册成功 创建token
return authenticateUser(new LoginRequest(user.getFirebaseUid(),user.getFirebaseUid()));
} else {
return new Result<>(ResultCodeEnum.ILLEGAL_ARGUMENT.getCode(),ResultCodeEnum.ILLEGAL_ARGUMENT.getDesc());
}
}
private void fillUserNecessayInfo(TbCfUserInfo tbCfUserInfoVo) {
if( tbCfUserInfoVo.getAvatar() == null) tbCfUserInfoVo.setAvatar(domainProperties.getProperty("user.avatar"));
tbCfUserInfoVo.setUserNo(IdUtil.createIdByDate());
tbCfUserInfoVo.setPhoneFlag(StateConstant.INVALID);
tbCfUserInfoVo.setLoginCount(0);
tbCfUserInfoVo.setCreateTime(new Date());
tbCfUserInfoVo.setSex(SexEnum.UNKNOW.getCode());
tbCfUserInfoVo.setInvitedCount(0);
tbCfUserInfoVo.setEnableFlag(StateConstant.VALID);
//目前有验证码的都是邮箱类型
tbCfUserInfoVo.setUserType(UserTypeEnum.FACEBOOK.getCode());
tbCfUserInfoVo.setEmailFlag(StateConstant.INVALID);
}
} }
...@@ -5,10 +5,10 @@ import com.example.afrishop_v3.base.StateConstant; ...@@ -5,10 +5,10 @@ import com.example.afrishop_v3.base.StateConstant;
import com.example.afrishop_v3.enums.ResultCodeEnum; import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.models.TbCfCartRecordR; import com.example.afrishop_v3.models.TbCfCartRecordR;
import com.example.afrishop_v3.models.TbCfExpressTemplate; import com.example.afrishop_v3.models.TbCfExpressTemplate;
import com.example.afrishop_v3.models.TbCfItemDetail; import com.example.afrishop_v3.models.TbCfStationItem;
import com.example.afrishop_v3.repository.TbCfCartRecordRRepository; import com.example.afrishop_v3.repository.TbCfCartRecordRRepository;
import com.example.afrishop_v3.repository.TbCfExpressTemplateRepository; import com.example.afrishop_v3.repository.TbCfExpressTemplateRepository;
import com.example.afrishop_v3.repository.TbCfItemDetailRepository; import com.example.afrishop_v3.repository.TbCfStationItemRepository;
import com.example.afrishop_v3.security.services.AuthenticationUser; import com.example.afrishop_v3.security.services.AuthenticationUser;
import com.example.afrishop_v3.util.ValidateUtils; import com.example.afrishop_v3.util.ValidateUtils;
import com.example.afrishop_v3.util.WordposHelper; import com.example.afrishop_v3.util.WordposHelper;
...@@ -25,78 +25,86 @@ import java.util.concurrent.TimeoutException; ...@@ -25,78 +25,86 @@ import java.util.concurrent.TimeoutException;
@RequestMapping("/cart") @RequestMapping("/cart")
public class CartController extends Controller { public class CartController extends Controller {
private final TbCfCartRecordRRepository repository; private final TbCfCartRecordRRepository repository;
private final TbCfItemDetailRepository itemDetailRepository; private final TbCfStationItemRepository itemRepository;
private final TbCfExpressTemplateRepository templateRepository; private final TbCfExpressTemplateRepository templateRepository;
private final AuthenticationUser user; private final AuthenticationUser user;
public CartController(TbCfCartRecordRRepository repository, TbCfItemDetailRepository itemDetailRepository, TbCfExpressTemplateRepository templateRepository, AuthenticationUser user) { public CartController(TbCfCartRecordRRepository repository, TbCfStationItemRepository itemRepository, TbCfExpressTemplateRepository templateRepository, AuthenticationUser user) {
this.repository = repository; this.repository = repository;
this.itemDetailRepository = itemDetailRepository; this.itemRepository = itemRepository;
this.templateRepository = templateRepository; this.templateRepository = templateRepository;
this.user = user; this.user = user;
} }
@PutMapping("/num/{cartId}/{itemNum}")
public Result changeItemNum(@PathVariable String cartId, @PathVariable int itemNum) {
Optional<TbCfCartRecordR> byId = repository.findById(cartId);
if (byId.isPresent()) {
TbCfCartRecordR record = byId.get();
record.setItemNum(itemNum);
repository.save(record);
return new Result<>(ResultCodeEnum.SUCCESS.getCode(), "Item quantity updated");
}
return new Result<>(ResultCodeEnum.SERVICE_ERROR.getCode(), "Failed");
}
@PostMapping @PostMapping
public Result addToCart(@RequestBody TbCfItemDetail itemDetail){ public Result addToCart(@RequestBody TbCfCartRecordR itemDetail) {
String userId = this.user.userId(); String userId = this.user.userId();
if( itemDetail == null ){ if (itemDetail == null) {
return new Result(ResultCodeEnum.SERVICE_ERROR.getCode(),"Request body is empty"); return new Result(ResultCodeEnum.SERVICE_ERROR.getCode(), "Request body is empty");
} }
int count = repository.countByUserId(userId); int count = repository.countByUserId(userId);
if( count > 99 ){ if (count > 99) {
return new Result(ResultCodeEnum.SERVICE_ERROR.getCode(),"Your shopping cart is full"); return new Result(ResultCodeEnum.SERVICE_ERROR.getCode(), "Your shopping cart is full");
} }
BigDecimal price = itemDetail.getItemPrice(); BigDecimal price = itemDetail.getItemPrice();
if ( price == null || price.compareTo(BigDecimal.ZERO) <= 0) { if (price == null || price.compareTo(BigDecimal.ZERO) <= 0) {
return new Result(ResultCodeEnum.SERVICE_ERROR.getCode(),"The price of the goods is incorrect"); return new Result(ResultCodeEnum.SERVICE_ERROR.getCode(), "The price of the goods is incorrect");
} }
Optional<TbCfItemDetail> optionalItem; Optional<TbCfCartRecordR> optionalItem;
String itemId = itemDetail.getItemId(); String itemId = itemDetail.getItemId();
boolean hasItemId = itemId != null && !itemId.isEmpty(); boolean hasItemId = itemId != null && !itemId.isEmpty();
if( hasItemId ){ if (hasItemId) {
optionalItem = itemDetailRepository.findFirstByItemImgAndItemSku(itemDetail.getItemImg(), itemDetail.getItemSku()); optionalItem = repository.findFirstByItemImgAndItemSku(itemDetail.getItemImg(), itemDetail.getItemSku());
}else { } else {
optionalItem = itemDetailRepository.findFirstBySourceItemIdAndItemSku(itemDetail.getSourceItemId(),itemDetail.getItemSku()); optionalItem = repository.findFirstBySourceItemIdAndItemSku(itemDetail.getSourceItemId(), itemDetail.getItemSku());
} }
TbCfItemDetail detail; TbCfCartRecordR detail;
if ( optionalItem.isPresent() ){ if (optionalItem.isPresent()) {
detail = optionalItem.get(); detail = optionalItem.get();
detail.setGoodsId(itemId);
itemDetailRepository.save(detail);
itemId = detail.getItemId(); itemId = detail.getItemId();
}else{ } else {
itemId = uid(); itemId = itemId != null && !itemId.isEmpty() ? itemId : uid();
try { itemDetail = updateItemCategory(itemDetail);
detail = insertItem(itemDetail,itemId);
} catch (Exception e) {
return new Result(ResultCodeEnum.SERVICE_ERROR.getCode(),e.getMessage());
}
} }
// Check if the item exist in cart // Check if the item exist in cart
Optional<TbCfCartRecordR> cartOptional = repository.findFirstByUserIdAndItemDetailItemIdAndItemSku(userId, itemId, itemDetail.getItemSku()); Optional<TbCfCartRecordR> cartOptional = repository.findFirstByUserIdAndItemIdAndItemSku(userId, itemId, itemDetail.getItemSku());
if ( cartOptional.isPresent() ){ if (cartOptional.isPresent()) {
TbCfCartRecordR cart = cartOptional.get(); TbCfCartRecordR cart = cartOptional.get();
cart.increaseNum(itemDetail.getItemNum()); cart.increaseNum(itemDetail.getItemNum());
repository.save(cart); repository.save(cart);
}else{ } else {
detail.setItemNum(itemDetail.getItemNum()); //detail.setItemNum(itemDetail.getItemNum());
insertRecord(detail, userId); insertRecord(itemDetail, userId);
} }
return new Result(); return new Result();
...@@ -104,7 +112,7 @@ public class CartController extends Controller { ...@@ -104,7 +112,7 @@ public class CartController extends Controller {
@GetMapping @GetMapping
public Result getItemCartList(){ public Result getItemCartList() {
return new Result<>(repository.findAllByUserId(user.userId())); return new Result<>(repository.findAllByUserId(user.userId()));
} }
...@@ -119,49 +127,47 @@ public class CartController extends Controller { ...@@ -119,49 +127,47 @@ public class CartController extends Controller {
} }
private void insertRecord(TbCfItemDetail itemDetail, String userId) { private void insertRecord(TbCfCartRecordR itemDetail, String userId) {
TbCfCartRecordR tbCfCartRecordREntity = new TbCfCartRecordR(); itemDetail.setCartRecordId(uid());
tbCfCartRecordREntity.setCartRecordId(uid()); itemDetail.setCheckFlag(StateConstant.INVALID);
tbCfCartRecordREntity.setCheckFlag(StateConstant.INVALID); itemDetail.setEnableFlag(StateConstant.VALID);
tbCfCartRecordREntity.setEnableFlag(StateConstant.VALID); itemDetail.setUserId(userId);
tbCfCartRecordREntity.setItemDetail(itemDetail); itemDetail.setCreateTime(new Date());
tbCfCartRecordREntity.setUserId(userId); repository.save(itemDetail);
tbCfCartRecordREntity.setCreateTime(new Date());
tbCfCartRecordREntity.setItemNum(itemDetail.getItemNum());
tbCfCartRecordREntity.setItemSku(itemDetail.getItemSku());
tbCfCartRecordREntity.setSourceItemId(itemDetail.getSourceItemId());
tbCfCartRecordREntity.setItemPrice(itemDetail.getItemPrice());
repository.save(tbCfCartRecordREntity);
} }
private TbCfItemDetail insertItem(TbCfItemDetail tbCfItemDetail, String itemId) throws Exception { private TbCfCartRecordR updateItemCategory(TbCfCartRecordR tbCfItemDetail) {
tbCfItemDetail.setCreateTime(new Date()); Optional<TbCfStationItem> byId = itemRepository.findById(tbCfItemDetail.getItemId());
//为商品分类,后面计算运费 if (byId.isPresent() && byId.get().getExpress() != null) {
try{ tbCfItemDetail.setTemplate(byId.get().getExpress());
} else {
TbCfExpressTemplate expressTemplate = recognizeItemCategory(tbCfItemDetail.getItemTitle()); if( byId.isPresent() ){
if (expressTemplate!=null) TbCfExpressTemplate templateIdAsc = templateRepository.findFirstByOrderByTemplateIdAsc();
if (templateIdAsc != null)
tbCfItemDetail.setTemplate(templateIdAsc);
} else {
TbCfExpressTemplate expressTemplate = null;
try {
expressTemplate = recognizeItemCategory(tbCfItemDetail.getItemTitle());
} catch (ExecutionException | InterruptedException | TimeoutException e) {
System.out.println(e.getMessage());
}
if (expressTemplate != null) {
tbCfItemDetail.setItemCategory(expressTemplate.getTemplateId()); tbCfItemDetail.setItemCategory(expressTemplate.getTemplateId());
}catch (Exception ignored){ tbCfItemDetail.setTemplate(expressTemplate);
}
} }
//加入商品详情
tbCfItemDetail.setGoodsId(tbCfItemDetail.getItemId());
tbCfItemDetail.setStatus(1);
//设置为默认一件商品(为了保证前人数据库信息完整性,无实际作用)
tbCfItemDetail.setItemNum(1);
if (itemId != null) {
tbCfItemDetail.setItemId(itemId);
} else {
tbCfItemDetail.setItemId(tbCfItemDetail.getItemId());
} }
return itemDetailRepository.save(tbCfItemDetail);
return tbCfItemDetail;
//logger.info("插入一条商品数据!"); //logger.info("插入一条商品数据!");
} }
private TbCfExpressTemplate recognizeItemCategory(String itemTitle) throws ExecutionException, InterruptedException, TimeoutException { private TbCfExpressTemplate recognizeItemCategory(String itemTitle) throws ExecutionException, InterruptedException, TimeoutException {
Map<String, Object> wordResult = separateText(itemTitle); Map<String, Object> wordResult = separateText(itemTitle);
//pos_code 16为名词,用名词去匹配; 23非汉字串 //pos_code 16为名词,用名词去匹配; 23非汉字串
...@@ -185,7 +191,7 @@ public class CartController extends Controller { ...@@ -185,7 +191,7 @@ public class CartController extends Controller {
totalTemplateSet.addAll(tbCfExpressTemplateList); totalTemplateSet.addAll(tbCfExpressTemplateList);
//TODO 后续优化 //TODO 后续优化
if (ValidateUtils.isContainChinese(keyword)) { if (ValidateUtils.isContainChinese(keyword)) {
if ( 0 == tbCfExpressTemplateList.size()) { if (0 == tbCfExpressTemplateList.size()) {
String[] split = keyword.split(""); String[] split = keyword.split("");
for (int i = 0; i < split.length; i++) { for (int i = 0; i < split.length; i++) {
if (i + 1 <= split.length) { if (i + 1 <= split.length) {
......
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.models.TbCfToicoupon;
import com.example.afrishop_v3.repository.TbCfCouponRepository;
import com.example.afrishop_v3.repository.TbCfToicouponRepository;
import com.example.afrishop_v3.security.services.AuthenticationUser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.List;
@RestController
@RequestMapping("/coupon")
public class CouponController {
private final TbCfToicouponRepository repository;
private final AuthenticationUser user;
public CouponController(TbCfToicouponRepository repository, AuthenticationUser user) {
this.repository = repository;
this.user = user;
}
@GetMapping
public Result getUserCoupons(){
String userId = user.userId();
List<TbCfToicoupon> availableCoupons = repository.queryUserAvailableCoupon(userId);
List<TbCfToicoupon> expiredCoupons = repository.queryUserExpiredCoupon(userId);
List<TbCfToicoupon> usedCoupons = repository.queryUserUsedCoupon(userId);
LinkedHashMap<String, Object> hashMap = new LinkedHashMap<>();
hashMap.put("validCouponList",availableCoupons);
hashMap.put("usedCouponList",usedCoupons);
hashMap.put("expiredCouponList",expiredCoupons);
return new Result<>(hashMap);
}
}
package com.example.afrishop_v3.controllers;
import com.alibaba.fastjson.JSONObject;
import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.config.DpoConfig;
import com.example.afrishop_v3.enums.DeliveryStatusEnum;
import com.example.afrishop_v3.enums.OrderStatusEnum;
import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.models.TbCfFinance;
import com.example.afrishop_v3.models.TbCfOrder;
import com.example.afrishop_v3.repository.TbCfFinanceRepository;
import com.example.afrishop_v3.repository.TbCfOrderRepository;
import com.example.afrishop_v3.util.DataUtils;
import com.example.afrishop_v3.util.HttpsUtil;
import com.example.afrishop_v3.util.IdUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
@RestController
@RequestMapping("/dpo")
public class DpoPayController {
private static Logger logger = LoggerFactory.getLogger(DpoPayController.class);
private final TbCfOrderRepository repository;
private final TbCfFinanceRepository financeRepository;
public DpoPayController(TbCfOrderRepository repository, TbCfFinanceRepository financeRepository) {
this.repository = repository;
this.financeRepository = financeRepository;
}
@GetMapping("/notify")
public Result payNotify(HttpServletRequest request, HttpServletResponse response) {
Result result = new Result();
try {
System.out.println("DPO支付回调");
//订单号
String orderId = request.getParameter("CompanyRef");
//交易ID
String transId = request.getParameter("TransID");
//交易令牌
String transToken = request.getParameter("TransactionToken");
System.err.println("transID:" + transId);
System.err.println("transToken:" + transToken);
//logger.info("DPO支付:" + "开始支付校验");
if (!StringUtils.isBlank(orderId) && !StringUtils.isBlank(transToken)) {
boolean verifyPay = verifyPay(transToken, orderId);
if (verifyPay) {
//logger.info("DPO支付:" + "支付校验成功");
result.setMessage("Pay for success");
result.setCode(ResultCodeEnum.SUCCESS.getCode());
return result;
}
}
return new Result<>(result,ResultCodeEnum.SERVICE_ERROR.getCode(), "Pay for failure");
} catch (Exception e) {
return new Result<>(result,ResultCodeEnum.SERVICE_ERROR.getCode(), "Pay for failure");
//logger.error("DPO支付回调发生异常--->>>" + e.toString());
}
}
@Transactional
public boolean verifyPay(String transToken, String orderId) {
boolean verify = false;
try {
Optional<TbCfOrder> byId = repository.findById(orderId);
if( !byId.isPresent() ) return false;
TbCfOrder order = byId.get();
//如果数据库订单支付状态为20,说明已支付
if (OrderStatusEnum.PAID.getValue().equals(order.getPayStatus())) {
verify = true;
return verify;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//拼接xml格式的参数,发送请求
Map<String, Object> map = getParameters(transToken);
String mapToXml = DataUtils.multilayerMapToXml(map, false);
mapToXml = mapToXml.replaceAll("<xml>", "").replaceAll("</xml>", "");
String resp = (String) HttpsUtil.sendHttps(DpoConfig.PAYMENT_API, "POST", mapToXml, false);
if (resp != null) {
//将响应结果转成json格式
String json = DataUtils.xml2json(resp);
JSONObject jsonObject = JSONObject.parseObject(json);
JSONObject api3G = jsonObject.getJSONObject("API3G");
String resCode = api3G.getString("Result");
//校验交易状态码
if (DpoConfig.SUCCESS_CODE.equals(resCode)) {
//获取缓存中的订单
// TbCfOrderVo tbCfOrderVo = (TbCfOrderVo) orderRedisCache.get(KeyConstant.ORDER_DET + orderId);
// //如果缓存中没有订单,则从数据库中查找
// if (tbCfOrderVo == null) {
// tbCfOrderVo = tbCfOrderDao.queryObject(orderId);
// }
/**
* 处理支付成功的业务:更新订单,优惠券状态,生成支付明细
*/
//1.更新订单状态
changeOrderState(transToken, order);
//2.更新优惠券状态
/*if (!StringUtils.isBlank(tbCfOrderVo.getCouponId())) {
tbCfToiCouponDao.changeCoupnStatus(tbCfOrderVo.getUserId(), tbCfOrderVo.getCouponId());
}*/
//3.生成支付明细
String authurl = DpoConfig.REDIRECT_URL + "?ID=" + transToken;
TbCfFinance finance = createFinance(transToken, authurl, order);
// TbCfFinanceVo tbCfFinanceVo = new TbCfFinanceVo();
// BeanUtils.copyProperties(finance, tbCfFinanceVo);
//校验数据库中订单支付状态
if (OrderStatusEnum.PAID.getValue().equals(order.getPayStatus())) {
//支付成功
logger.info("DPO支付:订单号" + orderId + "支付成功,支付时间:" + dateFormat.format(new Date()));
verify = true;
//清除缓存中的订单
// removeRedisCache(tbCfOrderVo);
}
}
if (!verify) {
logger.error("DPO支付:订单号" + orderId + "支付失败,支付时间:" + dateFormat.format(new Date()));
logger.error("DPO支付:状态码--->>>" + resCode);
}
}
} catch (Exception e) {
logger.error("DPO支付:订单号" + orderId + "支付异常--->>>" + e.toString());
}
return verify;
}
private void changeOrderState(String transToken, TbCfOrder order) {
//更改订单状态
order.setUpdateTime(new Date());
order.setDealTime(new Date());
order.setPayId(transToken);
order.setOrderStatus(OrderStatusEnum.PAID.getValue());
order.setPayStatus(OrderStatusEnum.PAID.getValue());
order.setDeliveryFlag(DeliveryStatusEnum.PROCESSING.getValue());
repository.save(order);
}
private TbCfFinance createFinance(String paymentId, String url, TbCfOrder tbCfOrderVo) {
TbCfFinance tbCfFinance = new TbCfFinance();
tbCfFinance.setOrderId(tbCfOrderVo.getOrderId());
tbCfFinance.setFinaceId(IdUtil.createIdbyUUID());
tbCfFinance.setPayAccount(tbCfOrderVo.getRealityPay());
tbCfFinance.setPayId(paymentId);
tbCfFinance.setPayTime(new Date());
tbCfFinance.setReceiptUrl(url);
tbCfFinance.setPayWayCode("dpo");
tbCfFinance.setUserId(tbCfOrderVo.getUserId());
financeRepository.save(tbCfFinance);
return tbCfFinance;
}
@PostMapping("/payment")
public Result payment(@RequestParam("orderId") String orderId) {
if( orderId == null || orderId.trim().isEmpty())
return new Result(ResultCodeEnum.ILLEGAL_ARGUMENT.getCode(),"Parameters cannot be empty");
Optional<TbCfOrder> byId = repository.findById(orderId);
if(!byId.isPresent())
return new Result(ResultCodeEnum.ILLEGAL_ARGUMENT.getCode(),"Order not found !");
TbCfOrder order = byId.get();
if (OrderStatusEnum.PAID.getValue().equals(order.getPayStatus()) ){
return new Result(ResultCodeEnum.ILLEGAL_ARGUMENT.getCode(),"Order has been paid !");
}
BigDecimal amount = order.getRealityPay();
boolean amountFlag = amount.compareTo(BigDecimal.ZERO) > 0;
//校验金额
if (!amountFlag) {
// logger.error("DPO支付:订单号" + orderId + "传入的金额有误");
// payErrorInfo(result, "Wrong order amount");
return new Result(ResultCodeEnum.ILLEGAL_ARGUMENT.getCode(),"Wrong order amount");
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//logger.info("DPO支付:订单号" + orderId + "创建交易,交易时间:" + dateFormat.format(new Date()));
//拼接请求参数(将map对象转成xml格式)
Map<String, Object> map = getParameters(order);
String mapToXml = DataUtils.multilayerMapToXml(map, false);
mapToXml = mapToXml.replaceAll("<xml>", "").replaceAll("</xml>", "");
String resp = (String) HttpsUtil.sendHttps(DpoConfig.PAYMENT_API, "POST", mapToXml, false);
if (resp != null) {
//将响应结果转成json格式
String json = DataUtils.xml2json(resp);
JSONObject jsonObject = JSONObject.parseObject(json);
JSONObject api3G = jsonObject.getJSONObject("API3G");
String resCode = api3G.getString("Result");
String transToken = api3G.getString("TransToken");
if (DpoConfig.SUCCESS_CODE.equals(resCode)) {
HashMap<String,Object> resultMap = new HashMap<>();
resultMap.put("transToken", transToken);
resultMap.put("payUrl", DpoConfig.REDIRECT_URL + "?ID=" + transToken);
resultMap.put("orderInfo", order);
// result.setData(resultMap);
// logger.info("DPO支付:订单号" + orderId + "创建令牌成功");
return new Result<>(resultMap,"Pay success");
}
// logger.info("DPO支付:订单号" + orderId + "创建令牌失败,状态码:" + resCode);
// payErrorInfo(result, "DPO支付:订单号" + orderId + "创建令牌失败,状态码:" + resCode);
}
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(),"DPO支付:订单号" + orderId + "创建令牌失败,状态码:");
}
private Map<String, Object> getParameters(String transToken) {
Map<String, Object> paramMap = new HashMap<>();
Map<String, Object> apiMap = new HashMap<>();
apiMap.put("CompanyToken", DpoConfig.COMPANY_TOKEN);
apiMap.put("Request", DpoConfig.VERIFY_TOKEN_REQUEST);
apiMap.put("TransactionToken", transToken);
paramMap.put("API3G", apiMap);
return paramMap;
}
private Map<String, Object> getParameters(TbCfOrder order) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm");
Map<String, Object> paramMap = new HashMap<>();
Map<String, Object> apiMap = new HashMap<>();
Map<String, Object> tranMap = new HashMap<>();
tranMap.put("Request", DpoConfig.CREATE_TOKEN_REQUEST);
tranMap.put("PaymentAmount", order.getRealityPay().setScale(2, BigDecimal.ROUND_UP));
tranMap.put("PaymentCurrency", "USD");
tranMap.put("CompanyRef", order.getOrderId());
tranMap.put("CompanyRefUnique", 0);
//回调地址
if (order.getOrderSource() != null && "1".equals(order.getOrderSource().toString())) {
tranMap.put("RedirectURL", DpoConfig.NOTIFY_URL);
} else if (order.getOrderSource() != null && "2".equals(order.getOrderSource().toString())) {
tranMap.put("RedirectURL", DpoConfig.NOTIFY_URL + "/web");
} else if (order.getOrderSource() != null && "3".equals(order.getOrderSource().toString())) {
tranMap.put("RedirectURL", DpoConfig.NOTIFY_URL + "/mobile");
}
System.out.println("回调地址:" + tranMap.get("RedirectURL"));
//取消地址
tranMap.put("BackURL", DpoConfig.BACK_URL);
// tranMap.put("PTL", 5);
Map<String, Object> servicesMap = new HashMap<>();
Map<String, Object> serviceMap = new HashMap<>();
serviceMap.put("ServiceType", DpoConfig.SERVICE_TYPE);
serviceMap.put("ServiceDescription", "DPO payment,name:" + order.getUserName() + ",amount:$" + order.getRealityPay());
serviceMap.put("ServiceDate", dateFormat.format(new Date()));
servicesMap.put("Service", serviceMap);
apiMap.put("Transaction", tranMap);
apiMap.put("Services", servicesMap);
apiMap.put("CompanyToken", DpoConfig.COMPANY_TOKEN);
apiMap.put("Request", DpoConfig.CREATE_TOKEN_REQUEST);
paramMap.put("API3G", apiMap);
return paramMap;
}
}
package com.example.afrishop_v3.controllers;
import com.alibaba.fastjson.JSON;
import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.config.CardCharge;
import com.example.afrishop_v3.config.DomainProperties;
import com.example.afrishop_v3.config.Environment;
import com.example.afrishop_v3.config.RaveConstant;
import com.example.afrishop_v3.enums.DeliveryStatusEnum;
import com.example.afrishop_v3.enums.OrderStatusEnum;
import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.models.*;
import com.example.afrishop_v3.repository.TbCfFinanceRepository;
import com.example.afrishop_v3.repository.TbCfOrderRepository;
import com.example.afrishop_v3.repository.UserRepository;
import com.example.afrishop_v3.util.HttpClientUtil;
import com.example.afrishop_v3.util.IdUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.*;
@RestController
@RequestMapping("/flutterwave")
public class FlutterWaveController {
private static Logger logger = LoggerFactory.getLogger(FlutterWaveController.class);
private final TbCfOrderRepository repository;
private final TbCfFinanceRepository financeRepository;
private final UserRepository userRepository;
private final DomainProperties domainProperties;
//退款API
private String FLUTTERWAVE_REFUND_URL = "https://api.ravepay.co/gpx/merchant/transactions/refund";
// //校验API
private String VERIFY_PAY_URL = "https://api.ravepay.co/flwv3-pug/getpaidx/api/v2/verify";
public FlutterWaveController(TbCfOrderRepository repository, TbCfFinanceRepository financeRepository, UserRepository userRepository, DomainProperties domainProperties) {
this.repository = repository;
this.financeRepository = financeRepository;
this.userRepository = userRepository;
this.domainProperties = domainProperties;
}
@PostMapping("/pay")
public ResponseEntity<String> payForOrderByCard(@RequestParam("orderId") String orderId, @RequestBody FlutterWaveCard flutterWaveCard) {
RaveConstant.PUBLIC_KEY = domainProperties.getProperty("flutterwave.public.key");
RaveConstant.SECRET_KEY = domainProperties.getProperty("flutterwave.secret.key");
RaveConstant.ENVIRONMENT = Environment.LIVE; //or live
// Result result = new Result();
Optional<TbCfOrder> byId = repository.findById(orderId);
JSONObject json = new JSONObject();
if (byId.isPresent()) {
//TbCfOrderVo tbCfOrderVo = (TbCfOrderVo) orderRedisCache.get(KeyConstant.ORDER_DET + orderId);
TbCfOrder orderEntity = byId.get();
//判断这个订单是否已支付
if (OrderStatusEnum.PAID.getValue().equals(orderEntity.getPayStatus())) {
json.put("message", "Order paid!");
json.put("code", ResultCodeEnum.ORDER_PAY_ERROR.getCode());
}else {
try {
String orderPrice = orderEntity.getRealityPay().toString();
CardCharge ch = new CardCharge();
ch.setCardno(flutterWaveCard.getCard())
.setCvv(flutterWaveCard.getCvv())
.setCurrency("USD")
.setCountry("NG")
.setAmount(orderPrice)
.setExpiryyear(flutterWaveCard.getYear())
.setExpirymonth(flutterWaveCard.getMonth())
.setEmail(flutterWaveCard.getEmail())
.setTxRef(orderId);
JSONObject chargevisa = ch.chargeVisaAndIntl();
JSONObject object = chargevisa.getJSONObject("data");
boolean b = object != null && object.has("authurl");
json.put("data", chargevisa);
json.put("code", b ? ResultCodeEnum.SUCCESS.getCode() : ResultCodeEnum.SERVICE_ERROR.getCode());
json.put("message", b ? ResultCodeEnum.SUCCESS.getDesc() : object == null ? ResultCodeEnum.SERVICE_ERROR.getDesc() : object.toString());
} catch (Exception e) {
json.put("code", ResultCodeEnum.ORDER_PAY_ERROR.getCode()).put("message", e.getMessage());
logger.error(e.getMessage(), e);
}
}
}
return new ResponseEntity<>(json.toString(), HttpStatus.OK);
}
/**
* 验证付款
*
* @param
* @param orderId
* @return
*/
@PostMapping("/verifyPay")
public Result verifyPay(@RequestParam("orderId") String orderId) {
Result result = new Result();
try {
logger.info("订单号" + orderId + "[flutterwave支付]校验开始时间:" + new Date());
Optional<TbCfOrder> byId = repository.findById(orderId);
if (!byId.isPresent()) return new Result(ResultCodeEnum.SERVICE_ERROR.getCode(), "Order not found !");
TbCfOrder tbCfOrderVo = byId.get();
Map<String, Object> map = new HashMap<>();
map.put("txref", orderId);
map.put("SECKEY", domainProperties.getProperty("flutterwave.secret.key"));
String data = HttpClientUtil.sendPostWithBodyParameter(VERIFY_PAY_URL, map);
com.alibaba.fastjson.JSONObject object = JSON.parseObject(data);
String statusFlag = object.getString("status");
com.alibaba.fastjson.JSONObject results = object.getJSONObject("data");
String status = results.getString("status");
String paymentid = results.getString("paymentid");
String authurl = results.getString("authurl");
if ("success".equalsIgnoreCase(statusFlag) && "successful".equalsIgnoreCase(status)) {
logger.info("订单号" + orderId + "[flutterwave支付]校验成功时间:" + new Date());
//支付成功
changeOrderState(paymentid, tbCfOrderVo);
//修改优惠券状态
/* if (!StringUtils.isBlank(tbCfOrderVo.getCouponId())) {
tbCfToiCouponDao.changeCoupnStatus(tbCfOrderVo.getUserId(), tbCfOrderVo.getCouponId());
}*/
//生成支付流水
TbCfFinance finance = createFinance(paymentid, authurl, tbCfOrderVo);
// TbCfFinanceVo tbCfFinanceVo = new TbCfFinanceVo();
// BeanUtils.copyProperties(finance, tbCfFinanceVo);
// removeRedisCache(tbCfOrderVo);
result.setData(JSON.parseObject(data));
result.setCode(ResultCodeEnum.SUCCESS.getCode()).setMessage("payment success!");
logger.info("payment success!");
//清空订单
logger.info("订单号" + orderId + "[flutterwave支付]校验结束时间:" + new Date());
} else {
result.setData(JSON.parseObject(data));
//支付失败
result.setCode(ResultCodeEnum.ORDER_PAY_ERROR.getCode()).setMessage("payment failure!");
logger.error("payment failure!");
logger.info("订单号" + orderId + "[flutterwave支付]校验失败时间:" + new Date());
}
} catch (Exception e) {
result.setCode(ResultCodeEnum.VALIDATE_ERROR.getCode()).setMessage(e.getMessage());
logger.error(e.getMessage(), e);
return result;
}
return result;
}
private void changeOrderState(String payId, TbCfOrder order) {
//更改订单状态
order.setUpdateTime(new Date());
order.setDealTime(new Date());
order.setPayId(payId);
order.setOrderStatus(OrderStatusEnum.PAID.getValue());
order.setPayStatus(OrderStatusEnum.PAID.getValue());
order.setDeliveryFlag(DeliveryStatusEnum.PROCESSING.getValue());
repository.save(order);
}
private TbCfFinance createFinance(String paymentId, String url, TbCfOrder tbCfOrderVo) {
TbCfFinance tbCfFinance = new TbCfFinance();
tbCfFinance.setOrderId(tbCfOrderVo.getOrderId());
tbCfFinance.setFinaceId(IdUtil.createIdbyUUID());
tbCfFinance.setPayAccount(tbCfOrderVo.getRealityPay());
tbCfFinance.setPayId(paymentId);
tbCfFinance.setPayTime(new Date());
tbCfFinance.setReceiptUrl(url);
tbCfFinance.setPayWayCode("flutterwave");
tbCfFinance.setUserId(tbCfOrderVo.getUserId());
financeRepository.save(tbCfFinance);
return tbCfFinance;
}
/**
* 退款
*
* @param flutterWaveCard
* @return
*/
@PostMapping("/refund")
public Result refund(@RequestBody FlutterWaveCard flutterWaveCard) {
Result result = new Result();
RaveConstant.SECRET_KEY = domainProperties.getProperty("flutterwave.secret.key");
Map<String, Object> params = new HashMap<>();
params.put("ref", flutterWaveCard.getRef());
params.put("seckey", RaveConstant.SECRET_KEY);
if (flutterWaveCard.getAmount() != null) {
params.put("amount", flutterWaveCard.getAmount());
}
try {
String post = HttpClientUtil.sendPostWithBodyParameter(FLUTTERWAVE_REFUND_URL, params);
com.alibaba.fastjson.JSONObject object = JSON.parseObject(post);
String status = object.getString("status");
if ("success".equals(status)) {
result.setData(object).setMessage("Refund success!");
logger.info("Refund success!");
} else {
result.setCode(ResultCodeEnum.REFUND_PAY_ERROR.getCode()).setMessage("Refund failure!");
}
} catch (IOException e) {
result.setCode(ResultCodeEnum.REFUND_PAY_ERROR.getCode()).setMessage(e.getMessage());
logger.error(e.getMessage(), e);
return result;
}
return result;
}
/**
* 支付参数
*
* @param userId
* @return
*/
@GetMapping("/queryParams")
public Result queryParams(@RequestParam("userId") String userId) {
Optional<TbCfUserInfo> byId = userRepository.findById(userId);
if (!byId.isPresent()) return new Result();
TbCfUserInfo userInfo = byId.get();
Result result = new Result<>();
List<TbCfUserInfo> list = new ArrayList<>();
FlutterKey key = new FlutterKey();
String public_key = domainProperties.getProperty("flutterwave.public.key");
list.add(userInfo);
key.setPublic_key(public_key);
key.setUserInfo(list);
result.setData(key).setMessage(ResultCodeEnum.SUCCESS.getDesc());
return result;
}
}
package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.base.StateConstant;
import com.example.afrishop_v3.enums.OrderStatusEnum;
import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.models.OrderRequest;
import com.example.afrishop_v3.models.TbCfCartRecordR;
import com.example.afrishop_v3.models.TbCfCoupon;
import com.example.afrishop_v3.models.TbCfOrder;
import com.example.afrishop_v3.repository.TbCfCartRecordRRepository;
import com.example.afrishop_v3.repository.TbCfCouponRepository;
import com.example.afrishop_v3.repository.TbCfItemOrderRepository;
import com.example.afrishop_v3.repository.TbCfOrderRepository;
import com.example.afrishop_v3.security.services.AuthenticationUser;
import com.example.afrishop_v3.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import static org.springframework.data.domain.Sort.Order.asc;
import static org.springframework.data.domain.Sort.Order.desc;
@RestController
@RequestMapping("/order")
public class OrderController {
private final TbCfOrderRepository repository;
private final TbCfCartRecordRRepository cartRepository;
private final TbCfCouponRepository couponRepository;
private final TbCfItemOrderRepository itemOrderRepository;
private final AuthenticationUser user;
public OrderController(TbCfOrderRepository repository, TbCfCartRecordRRepository cartRepository, TbCfCouponRepository couponRepository, TbCfItemOrderRepository itemOrderRepository, AuthenticationUser user) {
this.repository = repository;
this.cartRepository = cartRepository;
this.couponRepository = couponRepository;
this.itemOrderRepository = itemOrderRepository;
this.user = user;
}
@PostMapping("/settle")
public Result<TbCfOrder> settleAccount(@RequestBody String[] ids,@RequestParam(value = "toitableId", required = false) String toitableId) {
//String userId = user.userId();
List<TbCfCartRecordR> allByUserId = cartRepository.findAllByCartRecordIdIn(ids);
if( allByUserId.isEmpty() ){
return new Result<>(ResultCodeEnum.VALIDATE_ERROR.getCode(),"There are no items in the shopping cart");
}
TbCfOrder order = new TbCfOrder();
order.setCouponId(toitableId);
if( toitableId != null && !toitableId.isEmpty()){
Optional<TbCfCoupon> byId = couponRepository.findById(toitableId);
byId.ifPresent(order::setCoupon);
}
order.getItemOrderListFromCartList(allByUserId);
return new Result<>(order);
}
@PostMapping("/place")
public Result<TbCfOrder> placeOrder(@RequestBody OrderRequest tbCfOrder,
@RequestParam(value = "toitableId", required = false) String toitableId,
@RequestParam(value = "itemId", required = false) String itemId,
@RequestParam(value = "web", required = false) String web) throws IOException, URISyntaxException, ExecutionException, InterruptedException, TimeoutException {
String userId = user.userId();
int v_code = ResultCodeEnum.VALIDATE_ERROR.getCode();
if( tbCfOrder == null)
return new Result<>(v_code,"Empty body");
if( tbCfOrder.getIds() == null || tbCfOrder.getIds().length <= 0)
return new Result<>(v_code,"Empty body");
String addressId = tbCfOrder.getDeliveryAddressId();
if( addressId == null || addressId.isEmpty() ) return new Result<>(v_code,"Address id is required");
List<TbCfCartRecordR> allByUserId = cartRepository.findAllByCartRecordIdIn(tbCfOrder.getIds());
if( allByUserId.isEmpty() ){
return new Result<>(v_code,"There are no items in the shopping cart");
}
TbCfOrder order = new TbCfOrder();
order.setOrderId(IdUtil.createIdbyUUID());
order.setCouponId(toitableId);
if( toitableId != null && !toitableId.isEmpty()){
Optional<TbCfCoupon> byId = couponRepository.findById(toitableId);
byId.ifPresent(order::setCoupon);
}
order.setUserId(userId);
if ("web".equals(web)) {
order.setOrderSource(3);
} else {
order.setOrderSource(1);
}
order.getItemOrderListFromCartList(allByUserId);
TbCfOrder save = repository.save(order);
//order.getItemOrderList().forEach(itemOrderRepository::save);
List<String> collect = allByUserId.stream().map(TbCfCartRecordR::getCartRecordId).collect(Collectors.toList());
String[] strings = collect.toArray(new String[]{});
cartRepository.deleteAllByCartRecordIdIn(strings);
// implementation of coupon use
return new Result<>(save);
}
@GetMapping
public Result getUserOrderList(@RequestParam(value = "num", defaultValue = "0") Integer pageNum,
@RequestParam(value = "size", defaultValue = "20") Integer pageSize,
@RequestParam(value = "orderStatus", required = false) Integer orderStatus,
@RequestParam(value = "sort", defaultValue = "desc") String sort,
@RequestParam(value = "name", required = false) String name
) {
Page<TbCfOrder> list = repository.findAllByUserId(user.userId(), PageRequest.of(pageNum, pageSize, sort(sort)));
return new Result<>(list);
}
@GetMapping("/cancelOrder")
public Result cancelOrder(@RequestParam("orderId") String orderId,
@RequestParam("reason") String reason) {
Optional<TbCfOrder> byId = repository.findById(orderId);
if( byId.isPresent() ){
TbCfOrder order = byId.get();
order.setOrderStatus(OrderStatusEnum.CLOSE.getValue());
order.setRemarkInfo(reason);
repository.save(order);
return new Result();
}
return new Result<>(ResultCodeEnum.SERVICE_ERROR.getCode(),"Order not found!");
}
@DeleteMapping("/{orderId}")
public Result deleteOrder(@PathVariable("orderId") String orderId){
Optional<TbCfOrder> byId = repository.findById(orderId);
if( byId.isPresent() ){
TbCfOrder order = byId.get();
order.setEnableFlag(StateConstant.INVALID);
System.out.println(orderId);
repository.save(order);
}
return new Result(ResultCodeEnum.ILLEGAL_ARGUMENT.getCode(),"");
}
private Sort sort(String order){
String col = "orderTime";
return Sort.by( "desc".equals(order) ? desc(col) : asc(col));
}
}
package com.example.afrishop_v3.controllers; package com.example.afrishop_v3.controllers;
import com.example.afrishop_v3.base.Result; import com.example.afrishop_v3.base.Result;
import com.example.afrishop_v3.models.TbCfHomePage; import com.example.afrishop_v3.enums.ResultCodeEnum;
import com.example.afrishop_v3.repository.TbCfHomePageRepository; import com.example.afrishop_v3.models.*;
import com.example.afrishop_v3.repository.*;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.List; import java.util.*;
@RestController @RestController
@RequestMapping("/startPage")
public class TbCfHomePageEntityController { public class TbCfHomePageEntityController {
private final TbCfHomePageRepository repository; private final TbCfHomePageRepository repository;
private final TbCfSortRepository sortRepository;
private final TbCfClassificationRepository classificationRepository;
private final TbCfStoreRepository storeRepository;
private final TbCfPosterRepository posterRepository;
private final TbCfColumnRepository columnRepository;
public TbCfHomePageEntityController(TbCfHomePageRepository repository) { public TbCfHomePageEntityController(TbCfHomePageRepository repository, TbCfSortRepository sortRepository, TbCfClassificationRepository classificationRepository, TbCfStoreRepository storeRepository, TbCfPosterRepository posterRepository, TbCfColumnRepository columnRepository) {
this.repository = repository; this.repository = repository;
this.sortRepository = sortRepository;
this.classificationRepository = classificationRepository;
this.storeRepository = storeRepository;
this.posterRepository = posterRepository;
this.columnRepository = columnRepository;
} }
@GetMapping("/img") @GetMapping("/startPage/img")
public Result<List<TbCfHomePage>> getStartPageImage(@RequestParam(value = "version", defaultValue = "0") Integer version) { public Result<List<TbCfHomePage>> getStartPageImage(@RequestParam(value = "version", defaultValue = "0") Integer version) {
List<TbCfHomePage> all = repository.getAllByImgVersionAndEnableFlag(version, 1); List<TbCfHomePage> all = repository.getAllByImgVersionAndEnableFlag(version, 1);
return new Result<>(all); return new Result<>(all);
} }
@GetMapping("/home/middleColumn")
public Result getMiddleColumn( @RequestParam(value = "limit", defaultValue = "4") Integer limit){
Result result = new Result<>();
try {
List<TbCfSort> moduleList = sortRepository.findAll(Sort.by(Sort.Order.asc("sort")));
List<Map<String, Object>> list = new ArrayList<>();
if (moduleList != null && moduleList.size() > 0) {
for (TbCfSort module : moduleList) {
Map<String, Object> moduleMap = new LinkedHashMap<>();
String type = String.valueOf(module.getType());
//分类导航栏
if ("1".equals(type)) {
/*moduleMap.put("class_title", getTitleImage(1));*/
List<TbCfClassification> classificationList = classificationRepository.findAll();
moduleMap.put("classificationList", classificationList);
}
//爬虫品牌
if ("2".equals(type)) {
moduleMap.put("store_title", getTitleImage(2));
List<TbCfStore> storeStationList = storeRepository.findAll(PageRequest.of(0,limit)).toList();
moduleMap.put("storeStationList", storeStationList);
}
//海报图
if ("3".equals(type)) {
moduleMap.put("poster_title", getTitleImage(3));
List<TbCfPosters> postersList = posterRepository.findAll();
moduleMap.put("postersList", postersList);
}
list.add(moduleMap);
}
Map map = new HashMap();
List<TbCfColumn> hotColumnList = columnRepository.findAllByColumnType(4);
map.put("hot_title", hotColumnList);
list.add(map);
return new Result<>(list);
}
} catch (Exception e) {
result.setCode(ResultCodeEnum.SERVICE_ERROR.getCode());
result.setMessage(e.toString());
}
return result;
}
private List<TbCfColumn> getTitleImage(Integer type) {
return columnRepository.findAllByColumnType(type);
}
} }
package com.example.afrishop_v3.enums;
/**
* 发货状态
*
* @author G
*/
public enum DeliveryStatusEnum implements EnumItemable<DeliveryStatusEnum> {
/**
* 代购及物流状态
*/
PROCESSING("等待处理", 0),
PURCHASE("已采购并发货", 10),
ON_LOAD("已到达中国仓", 20),
ON_AFRICA("已到达非洲仓", 40),
ARRIVALS("买家已签收", 50);
private String label;
private Integer value;
DeliveryStatusEnum(String label, Integer value) {
this.label = label;
this.value = value;
}
@Override
public String getLabel() {
return this.label;
}
@Override
public Integer getValue() {
return this.value;
}
}
package com.example.afrishop_v3.enums;
/**
* 订单状态
*
* @author G
*/
public enum OrderStatusEnum implements EnumItemable<OrderStatusEnum> {
/**
* 订单状态枚举
*/
CANCEL("取消", 0),
PENDING_PAY("等待付款", 10),
PAID("已付款", 20),
SHIPPED("已发货", 40),
SUCCESS("交易成功", 50),
CLOSE("交易关闭", 60);
private String label;
private Integer value;
OrderStatusEnum(String label, Integer value) {
this.label = label;
this.value = value;
}
@Override
public String getLabel() {
return this.label;
}
@Override
public Integer getValue() {
return this.value;
}
}
package com.example.afrishop_v3.models;
import java.util.List;
/**
* @Auther: wudepeng
* @Date: 2019/11/28
* @Description:前端所需的支付数据
*/
public class FlutterKey {
private String public_key;
private List<TbCfUserInfo> userInfo;
public String getPublic_key() {
return public_key;
}
public void setPublic_key(String public_key) {
this.public_key = public_key;
}
public List<TbCfUserInfo> getUserInfo() {
return userInfo;
}
public void setUserInfo(List<TbCfUserInfo> userInfo) {
this.userInfo = userInfo;
}
}
package com.example.afrishop_v3.models;
/**
* @Auther: wudepeng
* @Date: 2019/11/11
* @Description: 持卡人信息
*/
public class FlutterWaveCard {
//卡号
private String card;
//银行卡背后3位数
private String cvv;
//到期月
private String month;
//到期年
private String year;
//email
private String email;
//手机号
private String phone;
//名字
private String firstname;
//姓氏
private String lastname;
//国家
private String country;
//支付的唯一参考
private String ref;
//退款金额
private String amount;
public String getCard() {
return card;
}
public void setCard(String card) {
this.card = card;
}
public String getCvv() {
return cvv;
}
public void setCvv(String cvv) {
this.cvv = cvv;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
package com.example.afrishop_v3.models;
public class OrderRequest {
private String[] ids;
private String deliveryAddressId;
public String getDeliveryAddressId() {
return deliveryAddressId;
}
public String[] getIds() {
return ids;
}
}
...@@ -26,18 +26,21 @@ public class TbCfCartRecordR { ...@@ -26,18 +26,21 @@ public class TbCfCartRecordR {
*/ */
@Id @Id
private String cartRecordId; private String cartRecordId;
/**
* 商品id
*/
@ManyToOne
@JoinColumn(name = "item_id",columnDefinition = "item_id")
private TbCfItemDetail itemDetail;
/** /**
* 用户id * 用户id
*/ */
private String userId; private String userId;
private String itemId;
private String itemImg;
private String itemTitle;
private String itemCategory;
/** /**
* 是否已经被勾选,0未勾选,1勾选 * 是否已经被勾选,0未勾选,1勾选
*/ */
...@@ -58,11 +61,25 @@ public class TbCfCartRecordR { ...@@ -58,11 +61,25 @@ public class TbCfCartRecordR {
* 商品SKU * 商品SKU
*/ */
private String itemSku; private String itemSku;
private String shopName;
private String shopUrl;
private String shopId;
/** /**
* 商品SKU * 商品SKU
*/ */
private Integer itemNum; private Integer itemNum;
@ManyToOne
private TbCfExpressTemplate template;
/**
* 状态 0:已删除 1:加入购物车 2:直接支付(预留)
*/
private Integer status;
/** /**
* 商品价格 * 商品价格
*/ */
...@@ -72,6 +89,10 @@ public class TbCfCartRecordR { ...@@ -72,6 +89,10 @@ public class TbCfCartRecordR {
return itemPrice; return itemPrice;
} }
public BigDecimal getItemPriceTotal() {
return itemPrice.multiply(BigDecimal.valueOf(itemNum));
}
public void setItemPrice(BigDecimal itemPrice) { public void setItemPrice(BigDecimal itemPrice) {
this.itemPrice = itemPrice; this.itemPrice = itemPrice;
} }
...@@ -90,16 +111,36 @@ public class TbCfCartRecordR { ...@@ -90,16 +111,36 @@ public class TbCfCartRecordR {
return cartRecordId; return cartRecordId;
} }
public String getItemImg() {
return itemImg;
}
/** /**
* 设置:商品id * 设置:商品分类
*/ */
public void setItemCategory(String itemCategory) {
public TbCfItemDetail getItemDetail() { this.itemCategory = itemCategory;
return itemDetail; }
/**
* 获取:商品分类
*/
public String getItemCategory() {
return itemCategory;
}
/**
* 设置:状态 0:已删除 1:加入购物车 2:直接支付(预留)
*/
public void setStatus(Integer status) {
this.status = status;
} }
public void setItemDetail(TbCfItemDetail itemDetail) {
this.itemDetail = itemDetail;
/**
* 获取:状态 0:已删除 1:加入购物车 2:直接支付(预留)
*/
public Integer getStatus() {
return status;
} }
/** /**
...@@ -130,6 +171,7 @@ public class TbCfCartRecordR { ...@@ -130,6 +171,7 @@ public class TbCfCartRecordR {
return checkFlag; return checkFlag;
} }
/** /**
* 设置:是否有效 * 设置:是否有效
*/ */
...@@ -137,6 +179,36 @@ public class TbCfCartRecordR { ...@@ -137,6 +179,36 @@ public class TbCfCartRecordR {
this.enableFlag = enableFlag; this.enableFlag = enableFlag;
} }
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemId() {
return itemId;
}
TbCfItemOrderR getOrderItem(String orderId){
return new TbCfItemOrderR(cartRecordId,orderId,itemId,itemNum,itemPrice,template,itemImg,itemSku,itemTitle,shopId,shopName,shopUrl);
}
public void setTemplate(TbCfExpressTemplate template) {
this.template = template;
}
public void setItemTitle(String itemTitle) {
this.itemTitle = itemTitle;
}
public String getItemTitle() {
return itemTitle;
}
public TbCfExpressTemplate getTemplate() {
return template;
}
/** /**
* 获取:是否有效 * 获取:是否有效
*/ */
...@@ -172,8 +244,8 @@ public class TbCfCartRecordR { ...@@ -172,8 +244,8 @@ public class TbCfCartRecordR {
return itemNum; return itemNum;
} }
public void increaseNum(Integer itemNum){ public void increaseNum(Integer itemNum) {
setItemNum(this.itemNum+itemNum); setItemNum(this.itemNum + itemNum);
} }
public void setItemNum(Integer itemNum) { public void setItemNum(Integer itemNum) {
......
package com.example.afrishop_v3.models;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
/**
* 首页分类导航实体
* 表名 tb_cf_classification
*
* @author lipengjun
* @date 2020-03-01 14:05:19
*/
@Entity
@Data
public class TbCfClassification{
/**
* 首页分类导航ID
*/
@Id
private String id;
/**
* 一级分类ID
*/
private String goodtypeId;
/**
* 标题
*/
private String classTitle;
/**
* 图片
*/
private String picture;
/**
* 排序
*/
private Integer sort;
/**
* 是否展示
*/
private String isShow;
/**
* 设置:首页分类导航ID
*/
public void setId(String id) {
this.id = id;
}
/**
* 获取:首页分类导航ID
*/
public String getId() {
return id;
}
/**
* 设置:一级分类ID
*/
public void setGoodtypeId(String goodtypeId) {
this.goodtypeId = goodtypeId;
}
/**
* 获取:一级分类ID
*/
public String getGoodtypeId() {
return goodtypeId;
}
/**
* 设置:标题
*/
public void setClassTitle(String classTitle) {
this.classTitle = classTitle;
}
/**
* 获取:标题
*/
public String getClassTitle() {
return classTitle;
}
/**
* 设置:图片
*/
public void setPicture(String picture) {
this.picture = picture;
}
/**
* 获取:图片
*/
public String getPicture() {
return picture;
}
/**
* 设置:排序
*/
public void setSort(Integer sort) {
this.sort = sort;
}
/**
* 获取:排序
*/
public Integer getSort() {
return sort;
}
/**
* 设置:是否展示
*/
public void setIsShow(String isShow) {
this.isShow = isShow;
}
/**
* 获取:是否展示
*/
public String getIsShow() {
return isShow;
}
}
package com.example.afrishop_v3.models;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Date;
/**
* 标题栏实体
* 表名 tb_cf_column
*
* @author lipengjun
* @date 2020-03-09 15:53:24
*/
@Entity
@Data
public class TbCfColumn{
/**
* 标题栏ID
*/
@Id
private String id;
/**
* 标题栏
*/
private String columnName;
/**
* 类型 1:爬虫 2:其他
*/
private Integer columnType;
/**
* 栏目图片
*/
private String columuPicture;
/**
* 排序
*/
private Integer sort;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updaeTime;
/**
* 设置:标题栏ID
*/
public void setId(String id) {
this.id = id;
}
/**
* 获取:标题栏ID
*/
public String getId() {
return id;
}
/**
* 设置:标题栏
*/
public void setColumnName(String columnName) {
this.columnName = columnName;
}
/**
* 获取:标题栏
*/
public String getColumnName() {
return columnName;
}
/**
* 设置:类型 1:爬虫 2:其他
*/
public void setColumnType(Integer columnType) {
this.columnType = columnType;
}
/**
* 获取:类型 1:爬虫 2:其他
*/
public Integer getColumnType() {
return columnType;
}
/**
* 设置:栏目图片
*/
public void setColumuPicture(String columuPicture) {
this.columuPicture = columuPicture;
}
/**
* 获取:栏目图片
*/
public String getColumuPicture() {
return columuPicture;
}
/**
* 设置:排序
*/
public void setSort(Integer sort) {
this.sort = sort;
}
/**
* 获取:排序
*/
public Integer getSort() {
return sort;
}
/**
* 设置:创建时间
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* 获取:创建时间
*/
public Date getCreateTime() {
return createTime;
}
/**
* 设置:更新时间
*/
public void setUpdaeTime(Date updaeTime) {
this.updaeTime = updaeTime;
}
/**
* 获取:更新时间
*/
public Date getUpdaeTime() {
return updaeTime;
}
}
package com.example.afrishop_v3.models;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* 优惠券表实体
* 表名 tb_cf_coupon
*
* @author G
* @date 2019-08-14 09:11:48
*/
@Entity
@Data
public class TbCfCoupon {
@Id
private String toitableId;
private String couponId;
private String couponCategoryId;
private String couponCategoryName;
private Integer couponUse;
private String couponTitle;
private String couponIcon;
private String withStationId;
private BigDecimal withAmount;
private BigDecimal deductAmount;
/**
* 发券数量
*/
private Integer quato;
/**
* 已领取数量 不更改,因为会被覆盖,改为查询统计来获取已经领取的优惠券数量
*/
private Integer takeCount;
/**
* 已使用数量 不更改,因为会被覆盖,改为查询统计来获取已经使用的优惠券数量
*/
private Integer usedCount;
/**
* 发放开始时间
*/
private Date startTime;
/**
* 发放结束时间
*/
private Date endTime;
/**
* 有效开始时间
*/
private Date validStartTime;
/**
* 有效结束时间
*/
private Date validEndTime;
/**
* 有效标志,0无效,1生效,2过期
*/
private Integer status;
/**
* 创建人
*/
private String createUserId;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改人
*/
private String updateUserId;
/**
* 修改时间
*/
private Date updateTime;
/**
* 设置是否是注册就是的优惠券,(0)默认状态,(1)是用户注册就送这张优惠券
*/
private Integer couponVaild;
/**
* 设置:设置是否是注册就是的优惠券,(0)默认状态,(1)是用户注册就送这张优惠券
*/
public String getToitableId() {
return toitableId;
}
public void setToitableId(String toitableId) {
this.toitableId = toitableId;
}
public String getCouponId() {
return couponId;
}
public void setCouponId(String couponId) {
this.couponId = couponId;
}
public String getCouponCategoryId() {
return couponCategoryId;
}
public void setCouponCategoryId(String couponCategoryId) {
this.couponCategoryId = couponCategoryId;
}
public String getCouponCategoryName() {
return couponCategoryName;
}
public void setCouponCategoryName(String couponCategoryName) {
this.couponCategoryName = couponCategoryName;
}
public Integer getCouponUse() {
return couponUse;
}
public void setCouponUse(Integer couponUse) {
this.couponUse = couponUse;
}
public String getCouponTitle() {
return couponTitle;
}
public void setCouponTitle(String couponTitle) {
this.couponTitle = couponTitle;
}
public String getCouponIcon() {
return couponIcon;
}
public void setCouponIcon(String couponIcon) {
this.couponIcon = couponIcon;
}
public String getWithStationId() {
return withStationId;
}
public void setWithStationId(String withStationId) {
this.withStationId = withStationId;
}
public BigDecimal getWithAmount() {
return withAmount;
}
public void setWithAmount(BigDecimal withAmount) {
this.withAmount = withAmount;
}
public BigDecimal getDeductAmount() {
return deductAmount;
}
public void setDeductAmount(BigDecimal deductAmount) {
this.deductAmount = deductAmount;
}
public Integer getQuato() {
return quato;
}
public void setQuato(Integer quato) {
this.quato = quato;
}
public Integer getTakeCount() {
return takeCount;
}
public void setTakeCount(Integer takeCount) {
this.takeCount = takeCount;
}
public Integer getUsedCount() {
return usedCount;
}
public void setUsedCount(Integer usedCount) {
this.usedCount = usedCount;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Date getValidStartTime() {
return validStartTime;
}
public void setValidStartTime(Date validStartTime) {
this.validStartTime = validStartTime;
}
public Date getValidEndTime() {
return validEndTime;
}
public void setValidEndTime(Date validEndTime) {
this.validEndTime = validEndTime;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCreateUserId() {
return createUserId;
}
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdateUserId() {
return updateUserId;
}
public void setUpdateUserId(String updateUserId) {
this.updateUserId = updateUserId;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getCouponVaild() {
return couponVaild;
}
public void setCouponVaild(Integer couponVaild) {
this.couponVaild = couponVaild;
}
}
package com.example.afrishop_v3.models;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* 财务明细实体
* 表名 tb_cf_finance
*
* @author G
* @date 2019-08-14 09:11:48
*/
@Entity
@Data
public class TbCfFinance{
/**
* 财务报表id
*/
@Id
private String finaceId;
/**
* 订单id
*/
private String orderId;
/**
* 用户id
*/
private String userId;
/**
* 支付款项
*/
private BigDecimal payAccount;
/**
* 支付流水号
*/
private String payId;
/**
* 支付方式
*/
private String payWayCode;
/**
* 支付时间
*/
private Date payTime;
/**
* 支付结果页面
*/
private String receiptUrl;
/**
* 设置:财务报表id
*/
public void setFinaceId(String finaceId) {
this.finaceId = finaceId;
}
/**
* 获取:财务报表id
*/
public String getFinaceId() {
return finaceId;
}
/**
* 设置:订单id
*/
public void setOrderId(String orderId) {
this.orderId = orderId;
}
/**
* 获取:订单id
*/
public String getOrderId() {
return orderId;
}
/**
* 设置:用户id
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* 获取:用户id
*/
public String getUserId() {
return userId;
}
/**
* 设置:支付款项
*/
public void setPayAccount(BigDecimal payAccount) {
this.payAccount = payAccount;
}
/**
* 获取:支付款项
*/
public BigDecimal getPayAccount() {
return payAccount;
}
/**
* 设置:支付流水号
*/
public void setPayId(String payId) {
this.payId = payId;
}
/**
* 获取:支付流水号
*/
public String getPayId() {
return payId;
}
/**
* 设置:支付方式
*/
public void setPayWayCode(String payWayCode) {
this.payWayCode = payWayCode;
}
/**
* 获取:支付方式
*/
public String getPayWayCode() {
return payWayCode;
}
/**
* 设置:支付时间
*/
public void setPayTime(Date payTime) {
this.payTime = payTime;
}
/**
* 获取:支付时间
*/
public Date getPayTime() {
return payTime;
}
public String getReceiptUrl() {
return receiptUrl;
}
public void setReceiptUrl(String receiptUrl) {
this.receiptUrl = receiptUrl;
}
}
package com.example.afrishop_v3.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* 商品详情实体
* 表名 tb_cf_item_detail
*
* @author lipengjun
* @date 2020-04-04 15:07:45
*/
@Entity
@Data
public class TbCfItemDetail{
/**
* 商品表记录id
*/
@Id
private String itemId;
/**
* 商品独立站ID
*/
private String goodsId;
/**
* 商品url
*/
@JsonIgnore
private String sourceItemId;
/**
* 来源站点id
*/
private String stationId;
/**
* 站点类型 1:自营商品 2:其他
*/
private Integer stationType;
/**
* 商品名称
*/
private String itemTitle;
/**
* 商品数量
*/
@JsonIgnore
private Integer itemNum;
/**
* 商品主图
*/
private String itemImg;
/**
* 商品单价
*/
private BigDecimal itemPrice;
/**
* 商品分类
*/
private String itemCategory;
/**
* 商品skus
*/
@JsonIgnore
private String itemSku;
/**
* 所属店铺id
*/
private String shopId;
/**
* 所属商铺名
*/
private String shopName;
/**
* 所属商铺链接
*/
private String shopUrl;
/**
* 状态 0:已删除 1:加入购物车 2:直接支付(预留)
*/
private Integer status;
/**
* 用户ID(预留)
*/
private String userId;
/**
* 加入时间
*/
private Date createTime;
private String descripitionName;
public String getDescripitionName() {
return descripitionName;
}
public void setDescripitionName(String descripitionName) {
this.descripitionName = descripitionName;
}
/**
* 设置:商品表记录id
*/
public void setItemId(String itemId) {
this.itemId = itemId;
}
/**
* 获取:商品表记录id
*/
public String getItemId() {
return itemId;
}
/**
* 设置:商品独立站ID
*/
public void setGoodsId(String goodsId) {
this.goodsId = goodsId;
}
/**
* 获取:商品独立站ID
*/
public String getGoodsId() {
return goodsId;
}
/**
* 设置:商品url
*/
public void setSourceItemId(String sourceItemId) {
this.sourceItemId = sourceItemId;
}
/**
* 获取:商品url
*/
public String getSourceItemId() {
return sourceItemId;
}
/**
* 设置:来源站点id
*/
public void setStationId(String stationId) {
this.stationId = stationId;
}
/**
* 获取:来源站点id
*/
public String getStationId() {
return stationId;
}
/**
* 设置:站点类型 1:自营商品 2:其他
*/
public void setStationType(Integer stationType) {
this.stationType = stationType;
}
/**
* 获取:站点类型 1:自营商品 2:其他
*/
public Integer getStationType() {
return stationType;
}
/**
* 设置:商品名称
*/
public void setItemTitle(String itemTitle) {
this.itemTitle = itemTitle;
}
/**
* 获取:商品名称
*/
public String getItemTitle() {
return itemTitle;
}
/**
* 设置:商品数量
*/
public void setItemNum(Integer itemNum) {
this.itemNum = itemNum;
}
/**
* 获取:商品数量
*/
public Integer getItemNum() {
return itemNum;
}
/**
* 设置:商品主图
*/
public void setItemImg(String itemImg) {
this.itemImg = itemImg;
}
/**
* 获取:商品主图
*/
public String getItemImg() {
return itemImg;
}
/**
* 设置:商品单价
*/
public void setItemPrice(BigDecimal itemPrice) {
this.itemPrice = itemPrice;
}
/**
* 获取:商品单价
*/
public BigDecimal getItemPrice() {
return itemPrice;
}
/**
* 设置:商品分类
*/
public void setItemCategory(String itemCategory) {
this.itemCategory = itemCategory;
}
/**
* 获取:商品分类
*/
public String getItemCategory() {
return itemCategory;
}
/**
* 设置:商品skus
*/
public void setItemSku(String itemSku) {
this.itemSku = itemSku;
}
/**
* 获取:商品skus
*/
public String getItemSku() {
return itemSku;
}
/**
* 设置:所属店铺id
*/
public void setShopId(String shopId) {
this.shopId = shopId;
}
/**
* 获取:所属店铺id
*/
public String getShopId() {
return shopId;
}
/**
* 设置:所属商铺名
*/
public void setShopName(String shopName) {
this.shopName = shopName;
}
/**
* 获取:所属商铺名
*/
public String getShopName() {
return shopName;
}
/**
* 设置:所属商铺链接
*/
public void setShopUrl(String shopUrl) {
this.shopUrl = shopUrl;
}
/**
* 获取:所属商铺链接
*/
public String getShopUrl() {
return shopUrl;
}
/**
* 设置:状态 0:已删除 1:加入购物车 2:直接支付(预留)
*/
public void setStatus(Integer status) {
this.status = status;
}
/**
* 获取:状态 0:已删除 1:加入购物车 2:直接支付(预留)
*/
public Integer getStatus() {
return status;
}
/**
* 设置:用户ID(预留)
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* 获取:用户ID(预留)
*/
public String getUserId() {
return userId;
}
/**
* 设置:加入时间
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* 获取:加入时间
*/
public Date getCreateTime() {
return createTime;
}
}
package com.example.afrishop_v3.models;
import com.example.afrishop_v3.base.StateConstant;
import com.example.afrishop_v3.enums.OrderStatusEnum;
import com.example.afrishop_v3.util.IdUtil;
import lombok.Data;
import org.hibernate.annotations.Where;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* 订单商品对应表实体
* 表名 tb_cf_item_order_r
*
* @author G
* @date 2019-08-14 09:11:48
*/
@Entity
@Data
@Table(name = "tb_cf_item_order_r")
@Where(clause = "enable_flag = 1")
public class TbCfItemOrderR {
/**
* 记录表
*/
@Id
private String orderItemId;
/**
* 商品id
*/
private String itemId;
/**
* 订单id
*/
private String orderId;
/**
* 是否有效
*/
private Integer enableFlag;
private Integer orderStatus;
private Integer deliveryFlag;
/**
* 是否已发送短信
*/
private Integer isSend;
private Date deliveryTime;
private Date closeTime;
private Date updateTime;
private Integer itemNum;
private String itemImg;
private String itemTitle;
private String itemSku;
private String shopName;
private String shopUrl;
private String shopId;
@ManyToOne
private TbCfOrder order;
@ManyToOne
private TbCfExpressTemplate template;
@Transient
private String cartRecordId;
TbCfItemOrderR(String id,String orderId,String itemId,Integer itemNum,BigDecimal itemPrice,TbCfExpressTemplate template,String itemImg,String itemSku,String itemTitle,String shopId,String shopName,String shopUrl){
this.itemNum = itemNum;
this.cartRecordId = id;
this.orderId = orderId;
this.orderItemId = IdUtil.createIdbyUUID();
this.itemPrice = itemPrice;
this.template = template;
this.itemId = itemId;
this.itemImg = itemImg;
this.itemSku = itemSku;
this.itemTitle = itemTitle;
this.enableFlag = StateConstant.VALID;
this.orderStatus = OrderStatusEnum.PENDING_PAY.getValue();
this.shopId = shopId;
this.shopName = shopName;
this.shopUrl = shopUrl;
}
TbCfItemOrderR(){
}
/**
* 商品价格
*/
private BigDecimal itemPrice;
public Integer getItemNum() {
return itemNum;
}
public void setItemNum(Integer itemNum) {
this.itemNum = itemNum;
}
public TbCfExpressTemplate getTemplate() {
return template;
}
/**
* 设置:记录表
*/
public void setOrderItemId(String orderItemId) {
this.orderItemId = orderItemId;
}
public BigDecimal getItemPriceTotal() {
return itemPrice.multiply(BigDecimal.valueOf(itemNum));
}
/**
* 获取:记录表
*/
public String getOrderItemId() {
return orderItemId;
}
/**
* 设置:商品id
*/
public void setItemId(String itemId) {
this.itemId = itemId;
}
/**
* 获取:商品id
*/
public String getItemId() {
return itemId;
}
/**
* 设置:订单id
*/
public void setOrderId(String orderId) {
this.orderId = orderId;
}
/**
* 获取:订单id
*/
public String getOrderId() {
return orderId;
}
/**
* 设置:是否有效
*/
public void setEnableFlag(Integer enableFlag) {
this.enableFlag = enableFlag;
}
/**
* 获取:是否有效
*/
public Integer getEnableFlag() {
return enableFlag;
}
public Integer getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(Integer orderStatus) {
this.orderStatus = orderStatus;
}
public Integer getDeliveryFlag() {
return deliveryFlag;
}
public void setDeliveryFlag(Integer deliveryFlag) {
this.deliveryFlag = deliveryFlag;
}
public Date getDeliveryTime() {
return deliveryTime;
}
public void setDeliveryTime(Date deliveryTime) {
this.deliveryTime = deliveryTime;
}
public Date getCloseTime() {
return closeTime;
}
public void setCloseTime(Date closeTime) {
this.closeTime = closeTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getIsSend() {
return isSend;
}
public void setIsSend(Integer isSend) {
this.isSend = isSend;
}
}
package com.example.afrishop_v3.models;
import com.example.afrishop_v3.base.StateConstant;
import com.example.afrishop_v3.enums.OrderStatusEnum;
import com.example.afrishop_v3.util.IdUtil;
import lombok.Data;
import org.hibernate.annotations.Where;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
/**
* 订单表实体
* 表名 tb_cf_order
*
* @author lipengjun
* @date 2020-04-24 15:51:42
*/
@Entity
@Data
@Where(clause = "enable_flag = 1")
public class TbCfOrder {
/**
* 订单id
*/
@Id
private String orderId;
/**
* 订单号
*/
private String orderNo;
/**
* 订单名
*/
private String orderName;
/**
* 订单创建时间
*/
private Date orderTime;
/**
* 更新时间
*/
private Date updateTime;
/**
* 订单来源 1:app 2:pc
*/
private Integer orderSource;
/**
* 成交时间
*/
private Date dealTime;
/**
* 交易关闭时间
*/
private Date closeTime;
/**
* 订单状态(0删除,10未付款,20已付款,40已发货,50交易成功,60交易关闭)
*/
private Integer orderStatus;
/**
* 用户id
*/
private String userId;
/**
* 用户名
*/
private String userName;
/**
* 收货地址Id
*/
private String deliveryAddressId;
/**
* 收货地址
*/
private String deliveryAddress;
/**
* 收货人
*/
private String deliveryName;
/**
* 收货人手机
*/
private String deliveryPhone;
/**
* 商品总价
*/
private BigDecimal itemsPrice;
/**
* 总价
*/
private BigDecimal totalPrice;
/**
* 实际付款
*/
private BigDecimal realityPay;
/**
* 发货标志、代购标志
*/
private Integer deliveryFlag;
/**
* 发货时间
*/
private Date deliveryTime;
/**
* 快递费
*/
private BigDecimal expressCost;
/**
* 优惠券id
*/
private String couponId;
/**
* 优惠券标题
*/
private String couponTitle;
/**
* 优惠券减免价格
*/
private BigDecimal couponPrice;
/**
* 税费
*/
private BigDecimal tax;
/**
* 手续费
*/
private BigDecimal fee;
/**
* 交易号
*/
private String payId;
/**
* 支付状态,10未支付,20已支付
*/
private Integer payStatus;
/**
* 删除标志 1未删除 0删除
*/
private Integer enableFlag;
/**
* 商品品名(废弃)
*/
private String descripitionName;
/**
* 订单关闭原因
*/
private String remarkInfo;
public TbCfOrder() {
this.orderStatus = OrderStatusEnum.PENDING_PAY.getValue();
this.enableFlag = StateConstant.VALID;
this.payStatus = OrderStatusEnum.PENDING_PAY.getValue();
this.orderTime = new Date();
}
@OneToMany(mappedBy = "orderId", cascade = CascadeType.ALL)
private List<TbCfItemOrderR> itemOrderList = new ArrayList<>();
/**
* 设置:订单id
*/
public void setOrderId(String orderId) {
this.orderId = orderId;
}
/**
* 获取:订单id
*/
public String getOrderId() {
return orderId;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
/**
* 设置:订单名
*/
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public List<TbCfItemOrderR> getItemOrderList() {
return itemOrderList;
}
public void getItemOrderListFromCartList(List<TbCfCartRecordR> cartList) {
itemOrderList = cartList.stream().map(f -> f.getOrderItem(orderId)).collect(Collectors.toList());
doSomeCalculations();
setOrderTime(new Date());
setDealTime(new Date());
setOrderNo(String.valueOf(IdUtil.createLongIdByDate()));
}
private void doSomeCalculations() {
itemsPrice = itemsPrice == null ? new BigDecimal(0.0) : itemsPrice;
expressCost = expressCost == null ? new BigDecimal(0.0) : expressCost;
fee = fee == null ? new BigDecimal(0.0) : fee;
tax = tax == null ? new BigDecimal(0.0) : tax;
List<TemplateVo> templateList = new ArrayList<>();
itemOrderList.forEach(item -> {
BigDecimal priceTotal = item.getItemPriceTotal();
TbCfExpressTemplate template = item.getTemplate();
itemsPrice = itemsPrice.add(priceTotal);
tax = tax.add(calculateDutyFee(BigDecimal.valueOf(item.getItemNum()), template));
fee = fee.add(calculateHandlingFee(BigDecimal.valueOf(item.getItemNum()), template));
if (template != null)
templateList.add(new TemplateVo(template, template.getTemplateId(), item.getItemNum(), itemsPrice));
});
Map<String, List<TemplateVo>> map = templateList.stream().collect(Collectors.groupingBy(TemplateVo::getTemplateId));
//按模板分组计算商品价格
List<TemplateVo> list = new ArrayList<>();
for (String key : map.keySet()) {
TemplateVo templateVo = new TemplateVo();
TbCfExpressTemplate _template = null;
Integer count = 0;
BigDecimal totalPrice = BigDecimal.ZERO;
for (TemplateVo template : map.get(key)) {
totalPrice = totalPrice.add(template.getItemPrice());
count += template.getItemCount();
_template = template.getTemplate();
}
templateVo.setTemplateId(key);
templateVo.setItemCount(count);
templateVo.setItemPrice(totalPrice);
templateVo.setTemplate(_template);
list.add(templateVo);
}
for (TemplateVo t : list) {
System.err.println(t);
//1.判断是否包邮4
//免邮价格
TbCfExpressTemplate express = t.getTemplate();
//if( express == null ) continue;
BigDecimal freePrice = express.getPostageFreePrice();
boolean b = t.getItemPrice().compareTo(freePrice) > 0;
if (b) {
//包邮
expressCost = expressCost.add(BigDecimal.ZERO);
} else {
//按运费模板计算
//续件
int extralNum = t.getItemCount() - express.getStartNum();
expressCost = expressCost.add(express.getExpressFee().add(express.getContinuationFee().multiply(new BigDecimal(extralNum))));
}
}
totalPrice = itemsPrice.add(fee).add(tax).add(expressCost);
countRealityPay();
}
@Transient
private TbCfCoupon coupon;
public void setCoupon(TbCfCoupon coupon) {
this.coupon = coupon;
}
private void countRealityPay() {
if (coupon != null) {
setCouponPrice(coupon.getDeductAmount());
setCouponId(coupon.getCouponId());
}
BigDecimal couponPrice = this.getCouponPrice();
//实际需要支付款项
if (couponPrice != null) {
BigDecimal realityPay = this.getTotalPrice().subtract(couponPrice);
//比0小则等于0
if (realityPay.compareTo(BigDecimal.ZERO) < 0) {
realityPay = BigDecimal.ZERO;
}
setRealityPay(realityPay);
} else {
setRealityPay(getTotalPrice());
}
}
@Transient
private List<String> usedList = new ArrayList<>();
private BigDecimal calculateHandlingFee(BigDecimal itemNum, TbCfExpressTemplate expressTemplate) {
if (expressTemplate == null) return BigDecimal.ZERO;
//计算手续费
BigDecimal handlingFee = expressTemplate.getHandlingFee()
.multiply(itemNum);
return handlingFee.setScale(BigDecimal.ROUND_DOWN, 2);
}
private BigDecimal calculateExpressCost(TbCfCartRecordR record, TbCfExpressTemplate express) {
BigDecimal decimal = new BigDecimal(0.0);
if (usedList.stream().anyMatch(f -> f.equals(express.getTemplateId()))) {
return decimal;
}
usedList.add(express.getTemplateId());
//计算手续费
BigDecimal freePrice = express.getPostageFreePrice();
boolean b = record.getItemPrice().compareTo(freePrice) > 0;
if (b) {
//包邮
return decimal.add(BigDecimal.ZERO);
} else {
int extralNum = record.getItemNum() - express.getStartNum();
return decimal.add(express.getExpressFee().add(express.getContinuationFee().multiply(new BigDecimal(extralNum))));
}
}
private BigDecimal calculateDutyFee(BigDecimal itemPrice, TbCfExpressTemplate expressTemplate) {
if (expressTemplate == null) return BigDecimal.ZERO;
//计算关税
BigDecimal dutyFee = expressTemplate.getTariff().multiply(itemPrice);
return dutyFee.setScale(BigDecimal.ROUND_DOWN, 2);
}
/**
* 获取:订单名
*/
public String getOrderName() {
return orderName;
}
/**
* 设置:订单创建时间
*/
public void setOrderTime(Date orderTime) {
this.orderTime = orderTime;
}
/**
* 获取:订单创建时间
*/
public Date getOrderTime() {
return orderTime;
}
/**
* 设置:更新时间
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
/**
* 获取:更新时间
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* 设置:订单来源 1:app 2:pc
*/
public void setOrderSource(Integer orderSource) {
this.orderSource = orderSource;
}
/**
* 获取:订单来源 1:app 2:pc
*/
public Integer getOrderSource() {
return orderSource;
}
/**
* 设置:成交时间
*/
public void setDealTime(Date dealTime) {
this.dealTime = dealTime;
}
/**
* 获取:成交时间
*/
public Date getDealTime() {
return dealTime;
}
/**
* 设置:交易关闭时间
*/
public void setCloseTime(Date closeTime) {
this.closeTime = closeTime;
}
/**
* 获取:交易关闭时间
*/
public Date getCloseTime() {
return closeTime;
}
/**
* 设置:订单状态(0删除,10未付款,20已付款,40已发货,50交易成功,60交易关闭)
*/
public void setOrderStatus(Integer orderStatus) {
this.orderStatus = orderStatus;
setItemStatuses(orderStatus);
}
private void setItemStatuses(Integer orderStatus) {
itemOrderList.forEach(f -> f.setOrderStatus(orderStatus));
}
/**
* 获取:订单状态(0删除,10未付款,20已付款,40已发货,50交易成功,60交易关闭)
*/
public Integer getOrderStatus() {
return orderStatus;
}
/**
* 设置:用户id
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* 获取:用户id
*/
public String getUserId() {
return userId;
}
/**
* 设置:用户名
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* 获取:用户名
*/
public String getUserName() {
return userName;
}
/**
* 设置:收货地址Id
*/
public void setDeliveryAddressId(String deliveryAddressId) {
this.deliveryAddressId = deliveryAddressId;
}
/**
* 获取:收货地址Id
*/
public String getDeliveryAddressId() {
return deliveryAddressId;
}
/**
* 设置:收货地址
*/
public void setDeliveryAddress(String deliveryAddress) {
this.deliveryAddress = deliveryAddress;
}
/**
* 获取:收货地址
*/
public String getDeliveryAddress() {
return deliveryAddress;
}
/**
* 设置:收货人
*/
public void setDeliveryName(String deliveryName) {
this.deliveryName = deliveryName;
}
/**
* 获取:收货人
*/
public String getDeliveryName() {
return deliveryName;
}
/**
* 设置:收货人手机
*/
public void setDeliveryPhone(String deliveryPhone) {
this.deliveryPhone = deliveryPhone;
}
/**
* 获取:收货人手机
*/
public String getDeliveryPhone() {
return deliveryPhone;
}
/**
* 设置:商品总价
*/
public void setItemsPrice(BigDecimal itemsPrice) {
this.itemsPrice = itemsPrice;
}
/**
* 获取:商品总价
*/
public BigDecimal getItemsPrice() {
return itemsPrice;
}
/**
* 设置:总价
*/
public void setTotalPrice(BigDecimal totalPrice) {
this.totalPrice = totalPrice;
}
/**
* 获取:总价
*/
public BigDecimal getTotalPrice() {
return totalPrice;
}
/**
* 设置:实际付款
*/
public void setRealityPay(BigDecimal realityPay) {
this.realityPay = realityPay;
}
/**
* 获取:实际付款
*/
public BigDecimal getRealityPay() {
return realityPay;
}
/**
* 设置:发货标志、代购标志
*/
public void setDeliveryFlag(Integer deliveryFlag) {
this.deliveryFlag = deliveryFlag;
setDeliveryFlagForItems(deliveryFlag);
}
private void setDeliveryFlagForItems(Integer deliveryFlag){
itemOrderList.forEach(f->f.setDeliveryFlag(deliveryFlag));
}
/**
* 获取:发货标志、代购标志
*/
public Integer getDeliveryFlag() {
return deliveryFlag;
}
/**
* 设置:发货时间
*/
public void setDeliveryTime(Date deliveryTime) {
this.deliveryTime = deliveryTime;
}
/**
* 获取:发货时间
*/
public Date getDeliveryTime() {
return deliveryTime;
}
/**
* 设置:快递费
*/
public void setExpressCost(BigDecimal expressCost) {
this.expressCost = expressCost;
}
/**
* 获取:快递费
*/
public BigDecimal getExpressCost() {
return expressCost;
}
/**
* 设置:优惠券id
*/
public void setCouponId(String couponId) {
this.couponId = couponId;
}
/**
* 获取:优惠券id
*/
public String getCouponId() {
return couponId;
}
/**
* 设置:优惠券标题
*/
public void setCouponTitle(String couponTitle) {
this.couponTitle = couponTitle;
}
/**
* 获取:优惠券标题
*/
public String getCouponTitle() {
return couponTitle;
}
/**
* 设置:优惠券减免价格
*/
public void setCouponPrice(BigDecimal couponPrice) {
this.couponPrice = couponPrice;
}
/**
* 获取:优惠券减免价格
*/
public BigDecimal getCouponPrice() {
return couponPrice;
}
/**
* 设置:税费
*/
public void setTax(BigDecimal tax) {
this.tax = tax;
}
/**
* 获取:税费
*/
public BigDecimal getTax() {
return tax;
}
/**
* 设置:手续费
*/
public void setFee(BigDecimal fee) {
this.fee = fee;
}
/**
* 获取:手续费
*/
public BigDecimal getFee() {
return fee;
}
/**
* 设置:交易号
*/
public void setPayId(String payId) {
this.payId = payId;
}
/**
* 获取:交易号
*/
public String getPayId() {
return payId;
}
/**
* 设置:支付状态,10未支付,20已支付
*/
public void setPayStatus(Integer payStatus) {
this.payStatus = payStatus;
}
/**
* 获取:支付状态,10未支付,20已支付
*/
public Integer getPayStatus() {
return payStatus;
}
/**
* 设置:删除标志 1未删除 0删除
*/
public void setEnableFlag(Integer enableFlag) {
this.enableFlag = enableFlag;
setEnableFlagForItems(enableFlag);
}
private void setEnableFlagForItems(Integer enableFlag){
itemOrderList.forEach(f->f.setEnableFlag(enableFlag));
}
/**
* 获取:删除标志 1未删除 0删除
*/
public Integer getEnableFlag() {
return enableFlag;
}
/**
* 设置:商品品名(废弃)
*/
public void setDescripitionName(String descripitionName) {
this.descripitionName = descripitionName;
}
/**
* 获取:商品品名(废弃)
*/
public String getDescripitionName() {
return descripitionName;
}
/**
* 设置:订单关闭原因
*/
public void setRemarkInfo(String remarkInfo) {
this.remarkInfo = remarkInfo;
}
/**
* 获取:订单关闭原因
*/
public String getRemarkInfo() {
return remarkInfo;
}
}
package com.example.afrishop_v3.models;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* 首页海报实体
* 表名 tb_cf_posters
*
* @author lipengjun
* @date 2020-03-01 16:59:28
*/
@Entity
@Data
public class TbCfPosters {
/**
* 海报ID
*/
@Id
private String id;
/**
* 标题
*/
private String postersTitle;
/**
* 类型 0:不跳转,1:商品 2:分类 3:
*/
private Integer postersType;
/**
* 图片
*/
private String postersPicture;
/**
* 是否展示
*/
private Integer isShow;
/**
* 跳转链接
*/
private String redirectUrl;
/**
* 备注
*/
private String remark;
/**
* 排序
*/
private Integer sort;
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
/**
* 设置:海报ID
*/
public void setId(String id) {
this.id = id;
}
/**
* 获取:海报ID
*/
public String getId() {
return id;
}
/**
* 设置:标题
*/
public void setPostersTitle(String postersTitle) {
this.postersTitle = postersTitle;
}
/**
* 获取:标题
*/
public String getPostersTitle() {
return postersTitle;
}
/**
* 设置:类型 0:不跳转,1:商品 2:分类 3:
*/
public void setPostersType(Integer postersType) {
this.postersType = postersType;
}
/**
* 获取:类型 0:不跳转,1:商品 2:分类 3:
*/
public Integer getPostersType() {
return postersType;
}
/**
* 设置:图片
*/
public void setPostersPicture(String postersPicture) {
this.postersPicture = postersPicture;
}
/**
* 获取:图片
*/
public String getPostersPicture() {
return postersPicture;
}
/**
* 设置:是否展示
*/
public void setIsShow(Integer isShow) {
this.isShow = isShow;
}
/**
* 获取:是否展示
*/
public Integer getIsShow() {
return isShow;
}
/**
* 设置:跳转链接
*/
public void setRedirectUrl(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
/**
* 获取:跳转链接
*/
public String getRedirectUrl() {
return redirectUrl;
}
/**
* 设置:备注
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* 获取:备注
*/
public String getRemark() {
return remark;
}
}
...@@ -7,6 +7,8 @@ import org.hibernate.annotations.Where; ...@@ -7,6 +7,8 @@ import org.hibernate.annotations.Where;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Date; import java.util.Date;
...@@ -122,10 +124,18 @@ public class TbCfStationItem { ...@@ -122,10 +124,18 @@ public class TbCfStationItem {
private String template; private String template;
@ManyToOne
@JoinColumn(columnDefinition = "template")
private TbCfExpressTemplate express;
@Formula(value = "(SELECT IFNULL(CEILING(SUM((a.item_score+a.service_score+a.logistics_score+a.price_score)/4)/COUNT(a.item_id)),5) FROM tb_cf_item_comment a WHERE a.item_id=item_id)") @Formula(value = "(SELECT IFNULL(CEILING(SUM((a.item_score+a.service_score+a.logistics_score+a.price_score)/4)/COUNT(a.item_id)),5) FROM tb_cf_item_comment a WHERE a.item_id=item_id)")
private int totalScore; private int totalScore;
public TbCfExpressTemplate getExpress() {
return express;
}
/** /**
* 设置:商品id * 设置:商品id
*/ */
......
package com.example.afrishop_v3.models;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Date;
/**
* 店铺管理实体
* 表名 tb_cf_store
*
* @author lipengjun
* @date 2019-09-05 16:51:07
*/
@Entity
@Data
public class TbCfStore {
/**
* 店铺id
*/
@Id
private String storeId;
/**
* 店铺编号
*/
private String storeCode;
/**
* 店铺名字
*/
private String storeName;
/**
* 店铺简介
*/
private String storeBrief;
/**
* 店铺链接
*/
private String storeUrl;
/**
* 店铺图片
*/
private String storeImg;
/**
* 所属平台
*/
private String platformCode;
/**
* 平台名
*/
private String platformName;
/**
* 启用状态
*/
private Integer enableFlag;
/**
* 创建日期
*/
private Date createTime;
/**
* 主营商品图片1
*/
@Column(columnDefinition = "item_img_1",name = "item_img_1")
private String itemImg1;
/**
* 主营商品图片2
*/
@Column(columnDefinition = "item_img_2",name = "item_img_2")
private String itemImg2;
/**
* 设置:店铺id
*/
public void setStoreId(String storeId) {
this.storeId = storeId;
}
/**
* 获取:店铺id
*/
public String getStoreId() {
return storeId;
}
/**
* 设置:店铺编号
*/
public void setStoreCode(String storeCode) {
this.storeCode = storeCode;
}
/**
* 获取:店铺编号
*/
public String getStoreCode() {
return storeCode;
}
/**
* 设置:店铺名字
*/
public void setStoreName(String storeName) {
this.storeName = storeName;
}
/**
* 获取:店铺名字
*/
public String getStoreName() {
return storeName;
}
/**
* 设置:店铺简介
*/
public void setStoreBrief(String storeBrief) {
this.storeBrief = storeBrief;
}
/**
* 获取:店铺简介
*/
public String getStoreBrief() {
return storeBrief;
}
/**
* 设置:店铺链接
*/
public void setStoreUrl(String storeUrl) {
this.storeUrl = storeUrl;
}
/**
* 获取:店铺链接
*/
public String getStoreUrl() {
return storeUrl;
}
/**
* 设置:店铺图片
*/
public void setStoreImg(String storeImg) {
this.storeImg = storeImg;
}
/**
* 获取:店铺图片
*/
public String getStoreImg() {
return storeImg;
}
/**
* 设置:所属平台
*/
public void setPlatformCode(String platformCode) {
this.platformCode = platformCode;
}
/**
* 获取:所属平台
*/
public String getPlatformCode() {
return platformCode;
}
/**
* 设置:平台名
*/
public void setPlatformName(String platformName) {
this.platformName = platformName;
}
/**
* 获取:平台名
*/
public String getPlatformName() {
return platformName;
}
/**
* 设置:启用状态
*/
public void setEnableFlag(Integer enableFlag) {
this.enableFlag = enableFlag;
}
/**
* 获取:启用状态
*/
public Integer getEnableFlag() {
return enableFlag;
}
/**
* 设置:创建日期
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* 获取:创建日期
*/
public Date getCreateTime() {
return createTime;
}
public String getItemImg1() {
return itemImg1;
}
public void setItemImg1(String itemImg1) {
this.itemImg1 = itemImg1;
}
public String getItemImg2() {
return itemImg2;
}
public void setItemImg2(String itemImg2) {
this.itemImg2 = itemImg2;
}
}
package com.example.afrishop_v3.models;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.io.Serializable;
import java.util.Date;
/**
* 实体
* 表名 tb_cf_toicoupon
*
* @author lipengjun
* @date 2019-11-22 19:32:08
*/
@Entity
@Data
public class TbCfToicoupon {
/**
* 发放/领取表id
*/
@Id
private String toitableId;
/**
* 优惠券id
*/
@ManyToOne
@JoinColumn(columnDefinition = "coupon_id")
private TbCfCoupon coupon;
/**
* 用户id
*/
private String userId;
/**
* 开始时间
*/
private Date startTime;
/**
* 结束时间
*/
private Date endTime;
/**
* 标识(1发放,2领取,3注册)
*/
private Integer identification;
/**
* 是否已使用(0已使用,1未使用)
*/
private Integer enableFlag;
/**
* 设置:发放/领取表id
*/
public void setToitableId(String toitableId) {
this.toitableId = toitableId;
}
/**
* 获取:发放/领取表id
*/
public String getToitableId() {
return toitableId;
}
/**
* 设置:优惠券id
*/
public void setCoupon(TbCfCoupon coupon) {
this.coupon = coupon;
}
/**
* 设置:用户id
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* 获取:用户id
*/
public String getUserId() {
return userId;
}
/**
* 设置:开始时间
*/
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
/**
* 获取:开始时间
*/
public Date getStartTime() {
return startTime;
}
/**
* 设置:结束时间
*/
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
/**
* 获取:结束时间
*/
public Date getEndTime() {
return endTime;
}
/**
* 设置:标识(1发放,2领取,3注册)
*/
public void setIdentification(Integer identification) {
this.identification = identification;
}
/**
* 获取:标识(1发放,2领取,3注册)
*/
public Integer getIdentification() {
return identification;
}
/**
* 设置:是否已使用(0已使用,1未使用)
*/
public void setEnableFlag(Integer enableFlag) {
this.enableFlag = enableFlag;
}
/**
* 获取:是否已使用(0已使用,1未使用)
*/
public Integer getEnableFlag() {
return enableFlag;
}
}
...@@ -5,6 +5,8 @@ import lombok.Setter; ...@@ -5,6 +5,8 @@ import lombok.Setter;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
...@@ -94,7 +96,9 @@ public class TbCfUserInfo { ...@@ -94,7 +96,9 @@ public class TbCfUserInfo {
/** /**
* 默认地址id * 默认地址id
*/ */
private String defaultAddressId; @ManyToOne
@JoinColumn(columnDefinition = "default_address_id")
private TbCfAddress address;
/** /**
* 发出邀请的用户 * 发出邀请的用户
*/ */
...@@ -355,17 +359,21 @@ public class TbCfUserInfo { ...@@ -355,17 +359,21 @@ public class TbCfUserInfo {
/** /**
* 设置:默认地址id * 设置:默认地址id
*/ */
public void setDefaultAddressId(String defaultAddressId) {
this.defaultAddressId = defaultAddressId; public void setAddress(TbCfAddress address) {
this.address = address;
}
public TbCfAddress getAddress() {
return address;
} }
/** /**
* 获取:默认地址id * 获取:默认地址id
*/ */
public String getDefaultAddressId() {
return defaultAddressId;
}
/** /**
*
* 设置:发出邀请的用户 * 设置:发出邀请的用户
*/ */
public void setInvitedUserId(String invitedUserId) { public void setInvitedUserId(String invitedUserId) {
......
package com.example.afrishop_v3.models;
import java.math.BigDecimal;
/**
* @Auther: wudepeng
* @Date: 2020/09/04
* @Description:The shipping template
*/
public class TemplateVo {
/**
* case List<TemplateVo> templateList = new ArrayList<>();
* templateList.add(new TemplateVo("ef57cb80e2e74a42850119c014b06c96",2,15.99));
*/
private String templateId;
private TbCfExpressTemplate template;
private Integer itemCount;
private BigDecimal itemPrice;//count*The price of a single item
public TemplateVo() {
}
public TemplateVo(TbCfExpressTemplate template,String templateId, Integer itemCount, BigDecimal itemPrice) {
this.template = template;
this.templateId = templateId;
this.itemCount = itemCount;
this.itemPrice = itemPrice;
}
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public TbCfExpressTemplate getTemplate() {
return template;
}
public void setTemplate(TbCfExpressTemplate template) {
this.template = template;
}
public Integer getItemCount() {
return itemCount;
}
public void setItemCount(Integer itemCount) {
this.itemCount = itemCount;
}
public BigDecimal getItemPrice() {
return itemPrice;
}
public void setItemPrice(BigDecimal itemPrice) {
this.itemPrice = itemPrice;
}
}
...@@ -6,6 +6,16 @@ public class LoginRequest { ...@@ -6,6 +6,16 @@ public class LoginRequest {
private String password; private String password;
public LoginRequest(){
}
public LoginRequest(String account,String password){
this.account = account;
this.password = password;
}
public String getAccount() { public String getAccount() {
return account; return account;
} }
......
package com.example.afrishop_v3.repository; package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfAddress; import com.example.afrishop_v3.models.TbCfAddress;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
public interface TbCfAddressRepository extends PagingAndSortingRepository<TbCfAddress,String> { public interface TbCfAddressRepository extends PagingAndSortingRepository<TbCfAddress,String> {
List<TbCfAddress> findAllByUserId(String userId); List<TbCfAddress> findAllByUserId(String userId);
@Transactional
@Modifying
@Query(value = "update tb_cf_address set default_flag=0 where user_id=:user_id",nativeQuery = true)
void resetToDefault(@Param("user_id") String userId);
} }
...@@ -7,12 +7,17 @@ import org.springframework.transaction.annotation.Transactional; ...@@ -7,12 +7,17 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
public interface TbCfCartRecordRRepository extends PagingAndSortingRepository<TbCfCartRecordR,String> { public interface TbCfCartRecordRRepository extends PagingAndSortingRepository<TbCfCartRecordR, String> {
int countByUserId(String userId); int countByUserId(String userId);
Optional<TbCfCartRecordR> findFirstByUserIdAndItemDetailItemIdAndItemSku(String userId, String itemId, String itemSku); Optional<TbCfCartRecordR> findFirstByUserIdAndItemIdAndItemSku(String userId, String itemId, String itemSku);
Optional<TbCfCartRecordR> findFirstByItemImgAndItemSku(String itemImg, String itemSku);
Optional<TbCfCartRecordR> findFirstBySourceItemIdAndItemSku(String itemImg, String itemSku);
List<TbCfCartRecordR> findAllByUserId(String userId); List<TbCfCartRecordR> findAllByUserId(String userId);
List<TbCfCartRecordR> findAllByCartRecordIdIn(String[] ids);
@Transactional @Transactional
......
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfClassification;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface TbCfClassificationRepository extends PagingAndSortingRepository<TbCfClassification,String> {
List<TbCfClassification> findAll();
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfColumn;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface TbCfColumnRepository extends PagingAndSortingRepository<TbCfColumn,String> {
List<TbCfColumn> findAllByColumnType(Integer columnType);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfCoupon;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface TbCfCouponRepository extends PagingAndSortingRepository<TbCfCoupon,String> {
List<TbCfCoupon> findAllByCouponVaild(Integer couponVaild);
}
...@@ -10,4 +10,6 @@ import java.util.List; ...@@ -10,4 +10,6 @@ import java.util.List;
public interface TbCfExpressTemplateRepository extends PagingAndSortingRepository<TbCfExpressTemplate,String> { public interface TbCfExpressTemplateRepository extends PagingAndSortingRepository<TbCfExpressTemplate,String> {
@Query(value = "select distinct a from #{#entityName} a WHERE a.templateId in (SELECT x.templateId FROM TbCfExpTemKeyword x WHERE x.keyword LIKE concat('%',:keyword,'%'))") @Query(value = "select distinct a from #{#entityName} a WHERE a.templateId in (SELECT x.templateId FROM TbCfExpTemKeyword x WHERE x.keyword LIKE concat('%',:keyword,'%'))")
List<TbCfExpressTemplate> getTemplateByKeyword(@Param("keyword") String keyword); List<TbCfExpressTemplate> getTemplateByKeyword(@Param("keyword") String keyword);
TbCfExpressTemplate findFirstByOrderByTemplateIdAsc();
} }
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfFinance;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface TbCfFinanceRepository extends PagingAndSortingRepository<TbCfFinance,String> {
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfItemDetail;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Optional;
public interface TbCfItemDetailRepository extends PagingAndSortingRepository<TbCfItemDetail,String> {
Optional<TbCfItemDetail> findFirstByItemImgAndItemSku(String itemImg, String itemSku);
Optional<TbCfItemDetail> findFirstBySourceItemIdAndItemSku(String itemImg, String itemSku);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfItemOrderR;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface TbCfItemOrderRepository extends PagingAndSortingRepository<TbCfItemOrderR,String> {
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfOrder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface TbCfOrderRepository extends PagingAndSortingRepository<TbCfOrder,String> {
Page<TbCfOrder> findAllByUserId(String userId, Pageable pageable);
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfPosters;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface TbCfPosterRepository extends PagingAndSortingRepository<TbCfPosters,String> {
List<TbCfPosters> findAll();
}
package com.example.afrishop_v3.repository; package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfSort; import com.example.afrishop_v3.models.TbCfSort;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface TbCfSortRepository extends PagingAndSortingRepository<TbCfSort,String> { public interface TbCfSortRepository extends PagingAndSortingRepository<TbCfSort,String> {
List<TbCfSort> findAll(Sort sort);
} }
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfStore;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface TbCfStoreRepository extends PagingAndSortingRepository<TbCfStore,String> {
}
package com.example.afrishop_v3.repository;
import com.example.afrishop_v3.models.TbCfToicoupon;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface TbCfToicouponRepository extends PagingAndSortingRepository<TbCfToicoupon,String> {
@Query("select a from #{#entityName} a WHERE a.enableFlag = 1 and a.userId = :user_id and CURRENT_TIMESTAMP between a.startTime and a.endTime order by a.coupon.deductAmount desc ")
List<TbCfToicoupon> queryUserAvailableCoupon(@Param("user_id") String userId);
@Query("select a from #{#entityName} a WHERE a.enableFlag = 0 and a.userId = :user_id order by a.coupon.deductAmount desc ")
List<TbCfToicoupon> queryUserUsedCoupon(@Param("user_id") String userId);
@Query("select a from #{#entityName} a WHERE a.enableFlag = 1 and a.userId = :user_id and CURRENT_TIMESTAMP not between a.startTime and a.endTime order by a.coupon.deductAmount desc ")
List<TbCfToicoupon> queryUserExpiredCoupon(@Param("user_id") String userId);
}
...@@ -7,5 +7,6 @@ import java.util.Optional; ...@@ -7,5 +7,6 @@ import java.util.Optional;
public interface UserRepository extends PagingAndSortingRepository<TbCfUserInfo,String> { public interface UserRepository extends PagingAndSortingRepository<TbCfUserInfo,String> {
Optional<TbCfUserInfo> findByAccount(String s); Optional<TbCfUserInfo> findByAccount(String s);
Optional<TbCfUserInfo> findByFirebaseUid(String s);
Optional<TbCfUserInfo> findFirstByEmail(String s); Optional<TbCfUserInfo> findFirstByEmail(String s);
} }
...@@ -58,7 +58,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { ...@@ -58,7 +58,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
http.cors().and().csrf().disable() http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/auth/**","/itemStation/**").permitAll() .authorizeRequests().antMatchers("/api/auth/**","/itemStation/**","/startPage/**","/home/**").permitAll()
.antMatchers("/api/test/**").permitAll() .antMatchers("/api/test/**").permitAll()
.anyRequest().authenticated(); .anyRequest().authenticated();
......
...@@ -20,7 +20,7 @@ public class UserDetailsServiceImpl implements UserDetailsService { ...@@ -20,7 +20,7 @@ public class UserDetailsServiceImpl implements UserDetailsService {
@Override @Override
@Transactional @Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
TbCfUserInfo user = userRepository.findByAccount(username) TbCfUserInfo user = userRepository.findByFirebaseUid(username)
.orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username)); .orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));
return UserDetailsImpl.build(user); return UserDetailsImpl.build(user);
......
package com.example.afrishop_v3.util;
import de.odysseus.staxon.json.JsonXMLConfig;
import de.odysseus.staxon.json.JsonXMLConfigBuilder;
import de.odysseus.staxon.json.JsonXMLInputFactory;
import de.odysseus.staxon.json.JsonXMLOutputFactory;
import de.odysseus.staxon.xml.util.PrettyXMLEventWriter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Auther: wudepeng
* @Date: 2020/02/26
* @Description:json,xml格式互换工具类
*/
public class DataUtils {
private static Logger logger = LoggerFactory.getLogger(DataUtils.class);
/**
* @Description: json string convert to xml string
* @author watermelon_code
* @date 2017年7月19日 上午10:50:32
*/
public static String json2xml(String json) {
StringReader input = new StringReader(json);
StringWriter output = new StringWriter();
JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();
try {
XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
writer = new PrettyXMLEventWriter(writer);
writer.add(reader);
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return output.toString();
}
/**
* @Description: json string convert to xml string ewidepay ues only
* @author watermelon_code
* @date 2017年7月19日 上午10:50:32
*/
public static String json2xmlPay(String json) {
StringReader input = new StringReader(json);
StringWriter output = new StringWriter();
JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();
try {
XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
writer = new PrettyXMLEventWriter(writer);
writer.add(reader);
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (output.toString().length() >= 38) {// remove <?xml version="1.0" encoding="UTF-8"?>
return "<xml>" + output.toString().substring(39) + "</xml>";
}
return output.toString();
}
/**
* @Description: xml string convert to json string
* @author watermelon_code
* @date 2017年7月19日 上午10:50:46
*/
public static String xml2json(String xml) {
StringReader input = new StringReader(xml);
StringWriter output = new StringWriter();
JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).autoPrimitive(true).prettyPrint(true).build();
try {
XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input);
XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);
writer.add(reader);
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return output.toString();
}
/**
* @Description: 去掉转换xml之后的换行和空格
* @author watermelon_code
* @date 2017年8月9日 下午4:05:44
*/
public static String json2xmlReplaceBlank(String json) {
String str = DataUtils.json2xml(json);
String dest = "";
if (str != null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
/**
* @author
* @date 2016-4-22
* @Description:将请求参数转换为xml格式的string
* @param parameters
* 请求参数
* @return
*/
@SuppressWarnings("rawtypes")
public static String getRequestXml(SortedMap<Object, Object> parameters) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = parameters.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
} else {
sb.append("<" + k + ">" + v + "</" + k + ">");
}
}
sb.append("</xml>");
return sb.toString();
}
/**
* @author mds
* @DateTime 2018年4月25日 上午11:32:59
* @serverComment
* xml转Map
* @param
* @return
*/
@SuppressWarnings("unchecked")
public static Map<String, String> xmlToMap(InputStream ins){
Map<String, String> map = new HashMap<String, String>();
SAXReader reader = new SAXReader();
Document doc = null;
try {
doc = reader.read(ins);
Element root = doc.getRootElement();
List<Element> list = root.elements();
for (Element e : list) {
map.put(e.getName(), e.getText());
}
return map;
} catch (DocumentException e) {
logger.error(e.getMessage(), e);
} finally {
try {
ins.close();
} catch (IOException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
}
}
return null;
}
/**
* XML格式字符串转换为Map
*
* @param xml XML字符串
* @return XML数据转换后的Map
* @throws Exception
*/
public static Map<String, String> xmlToMap(String xml) {
try {
Map<String, String> data = new HashMap<>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
Node node = nodeList.item(idx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element element = (org.w3c.dom.Element) node;
data.put(element.getNodeName(), element.getTextContent());
}
}
stream.close();
return data;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将Map转换为XML格式的字符串
*
* @param data Map类型数据
* @return XML格式的字符串
* @throws Exception
*/
public static String mapToXml(Map<String, String> data) throws Exception {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.newDocument();
org.w3c.dom.Element root = document.createElement("xml");
document.appendChild(root);
for (String key: data.keySet()) {
String value = data.get(key);
if (value == null) {
value = "";
}
value = value.trim();
org.w3c.dom.Element filed = document.createElement(key);
filed.appendChild(document.createTextNode(value));
root.appendChild(filed);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
writer.close();
return output;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* (多层)xml格式字符串转换为map
*
* @param xml xml字符串
* @return 第一个为Root节点,Root节点之后为Root的元素,如果为多层,可以通过key获取下一层Map
*/
public static Map<String, Object> multilayerXmlToMap(String xml) {
Document doc = null;
try {
doc = DocumentHelper.parseText(xml);
} catch (DocumentException e) {
logger.error("xml字符串解析,失败 --> {}", e);
}
Map<String, Object> map = new HashMap<>();
if (null == doc) {
return map;
}
// 获取根元素
Element rootElement = doc.getRootElement();
recursionXmlToMap(rootElement,map);
return map;
}
/**
* multilayerXmlToMap核心方法,递归调用
*
* @param element 节点元素
* @param outmap 用于存储xml数据的map
*/
@SuppressWarnings("unchecked")
private static void recursionXmlToMap(Element element, Map<String, Object> outmap) {
// 得到根元素下的子元素列表
List<Element> list = element.elements();
int size = list.size();
if (size == 0) {
// 如果没有子元素,则将其存储进map中
outmap.put(element.getName(), element.getTextTrim());
} else {
// innermap用于存储子元素的属性名和属性值
Map<String, Object> innermap = new HashMap<>();
// 遍历子元素
list.forEach(childElement -> recursionXmlToMap(childElement, innermap));
outmap.put(element.getName(), innermap);
}
}
/**
* (多层)map转换为xml格式字符串
*
* @param map 需要转换为xml的map
* @param isCDATA 是否加入CDATA标识符 true:加入 false:不加入
* @return xml字符串
*/
public static String multilayerMapToXml(Map<String, Object> map, boolean isCDATA){
String parentName = "xml";
Document doc = DocumentHelper.createDocument();
doc.addElement(parentName);
String xml = recursionMapToXml(doc.getRootElement(), parentName, map, isCDATA);
return formatXML(xml);
}
/**
* multilayerMapToXml核心方法,递归调用
*
* @param element 节点元素
* @param parentName 根元素属性名
* @param map 需要转换为xml的map
* @param isCDATA 是否加入CDATA标识符 true:加入 false:不加入
* @return xml字符串
*/
@SuppressWarnings("unchecked")
private static String recursionMapToXml(Element element, String parentName, Map<String, Object> map, boolean isCDATA) {
Element xmlElement = element.addElement(parentName);
map.keySet().forEach(key -> {
Object obj = map.get(key);
if (obj instanceof Map) {
recursionMapToXml(xmlElement, key, (Map<String, Object>)obj, isCDATA);
} else {
String value = obj == null ? "" : obj.toString();
if (isCDATA) {
xmlElement.addElement(key).addCDATA(value);
} else {
xmlElement.addElement(key).addText(value);
}
}
});
return xmlElement.asXML();
}
/**
* 格式化xml,显示为容易看的XML格式
*
* @param xml 需要格式化的xml字符串
* @return
*/
public static String formatXML(String xml) {
String requestXML = null;
try {
// 拿取解析器
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(xml));
if (null != document) {
StringWriter stringWriter = new StringWriter();
// 格式化,每一级前的空格
OutputFormat format = new OutputFormat(" ", true);
// xml声明与内容是否添加空行
format.setNewLineAfterDeclaration(false);
// 是否设置xml声明头部
format.setSuppressDeclaration(false);
// 是否分行
format.setNewlines(true);
XMLWriter writer = new XMLWriter(stringWriter, format);
writer.write(document);
writer.flush();
writer.close();
requestXML = stringWriter.getBuffer().toString();
}
return requestXML;
} catch (Exception e) {
logger.error("格式化xml,失败 --> {}", e);
return null;
}
}
}
package com.example.afrishop_v3.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.SecureRandom;
import java.util.*;
/**
*
* @author mds
* @DateTime 2018年4月25日 下午2:17:16
* @Comment https工具类
*/
public class HttpsUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpsUtil.class);
public static void main(String[] args) {
// System.out.println(findToken());
// System.out.println(findHtmToken("071MN2yB0H3dJg2M3eAB0Gi7yB0MN2yT"));
//System.out.println(findUserInfo("001cKtlS17xJN61n88kS1N7olS1cKtl-"));
}
/**
* @author wmt
* @DateTime 2019年4月17日 上午9:50:04
* @serverComment 请求微信code2Session接口获取openid等信息
* @return
*/
public static JSONObject findCode2Session(String code, String appId, String appSecret){
String url = "https://api.weixin.qq.com/sns/jscode2session";
Map<String, Object> param = new HashMap<String, Object>();
param.put("appid", appId);
param.put("secret", appSecret);
param.put("js_code", code);
param.put("grant_type", "authorization_code");
url = urlParams(url, param);
JSONObject jsonData = httpsReq(url, "GET", "");
return jsonData;
}
/**
* @author mds
* @DateTime 2018年4月25日 下午4:03:47
* @serverComment
* 获取基础支持token和ticket
* @return
*/
public static JSONObject findToken(){
String url = "https://api.weixin.qq.com/cgi-bin/token";
Map<String, Object> param = new HashMap<String, Object>();
param.put("grant_type", "client_credential");
param.put("appid", "wx495f97d037fd5f93");
param.put("secret", "7133214b34c3ee0dd294b1444ba46091");
url = urlParams(url, param);
JSONObject token = httpsReq(url, "GET", "");
if(token != null && !token.containsKey("errcode")){
param.clear();
String accessToken = token.getString("access_token");
url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
param.put("type", "jsapi");
param.put("access_token", accessToken);
JSONObject ticket = httpsReq(urlParams(url, param), "GET", "");
if(ticket != null && 0 == ticket.getIntValue("errcode")){
token.put("ticket", ticket.get("ticket"));
}
}
return token;
}
/**
* @author mds
* @DateTime 2018年4月25日 下午4:23:07
* @serverComment
* 通过code换取网页授权access_token
* @param code
* @return
*/
public static JSONObject findHtmToken(String code, String appId, String appSecret){
String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
Map<String, Object> param = new HashMap<String, Object>();
param.put("grant_type", "authorization_code");
param.put("appid", appId);
param.put("secret", appSecret);
param.put("code", code);
JSONObject token = httpsReq(urlParams(url, param), "GET", "");
return token;
}
/**
* @author mds
* @DateTime 2018年4月25日 下午4:47:09
* @serverComment
* code 获取用户信息
* @param code
* @return
*/
public static JSONObject findUserInfo(String code, String appId, String appSecret){
//获取网页授权access_token
JSONObject token = findHtmToken(code, appId, appSecret);
System.out.println("获取网页授权="+token);
if(!token.containsKey("errcode")){
String url = "https://api.weixin.qq.com/sns/userinfo";
Map<String, Object> param = new HashMap<String, Object>();
param.put("access_token", token.get("access_token"));
param.put("openid", token.get("openid"));
param.put("lang", "zh_CN");
JSONObject userInfo = httpsReq(urlParams(url, param), "GET", "");
return userInfo;
}
return null;
}
/**
* 发送Https请求并获取结果
*
*
* @param method
* @param data
* @return
*/
public static JSONObject httpsReq(String reqUrl, String method, String data) {
String result = (String)sendHttps(reqUrl, method, data, false);
if(StringUtils.isNotBlank(result)){
return JSON.parseObject(result);
}
return null;
}
/**
* 发送Https请求并获取结果
*
* 】
* @param method
* @param data
* @param xml 返回是否xml
* @return
*/
public static Object sendHttps(String reqUrl, String method, String data, boolean xml) {
StringBuffer result = new StringBuffer();
Map<String, String> resMap = new HashMap<String, String>();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new X509TM() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new SecureRandom());
// 获取SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
// 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
URL url = new URL(reqUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
// 设置连接参数
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod(method);// 设置请求方式
/*conn.setConnectTimeout(20000); //连接主机的超时时间(单位:毫秒)
conn.setReadTimeout(20000); //从主机读取数据的超时时间(单位:毫秒)
*/
if (method.equals("GET")) {
conn.connect();
}
if (StringUtils.isNotBlank(data)) {
OutputStream os = conn.getOutputStream();
os.write(data.getBytes("utf-8"));
os.close();
}
//获取返回信息
InputStream input = conn.getInputStream();
if(xml){
resMap = XmlUtil.xmlToMap(input);
}else{
InputStreamReader inputSR = new InputStreamReader(input, "utf-8");
BufferedReader bufRea = new BufferedReader(inputSR);
String str = null;
while ((str = bufRea.readLine()) != null) {
result.append(str);
}
// 清理
inputSR.close();
bufRea.close();
}
input.close();
input = null;
conn.disconnect();
} catch (ConnectException e) {
// TODO Auto-generated catch block
//System.out.println("网络连接超时...");
logger.error(e.getMessage(), e);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
}
if(xml){
return resMap;
}else{
return result.toString();
}
}
/**
* @author mds
* @DateTime 2018年4月25日 下午2:38:54
* @serverComment
* Map 转 url 参数
* @param param
* @return
*/
public static String urlParams(String url, Map<String, Object> param) {
if (param == null) {
return "";
}
StringBuffer params = new StringBuffer();
if(StringUtils.isNotBlank(url)){
params.append(url + "?");
}
for (Map.Entry<String, Object> entry : param.entrySet()) {
params.append(entry.getKey() + "=" + entry.getValue());
params.append("&");
}
String result = params.toString();
if (result.endsWith("&")) {
result = result.substring(0, result.length() - 1);
}
return result;
}
/**
* @author mds
* @DateTime 2018年5月2日 下午2:30:38
* @serverComment
* Map 转 url 参数
* @param params
* @return
*/
@SuppressWarnings("rawtypes")
public static String urlParams(String url, SortedMap<Object, Object> params){
//实际可以不排序
StringBuffer sb = new StringBuffer();
if(StringUtils.isNotBlank(url)){
sb.append(url + "?");
}
Set es = params.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v)) {
sb.append(k + "=" + v + "&");
}
}
sb.deleteCharAt(sb.length()-1);//删掉最后一个&
return sb.toString();
}
}
\ No newline at end of file
{
"type": "service_account",
"project_id": "afrishop-6e142",
"private_key_id": "b5e0248586e0deb7bb393a407a9f4bab0616bc8f",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDXVVzWwt5DnbT/\nVfuF874z054C+kHIixPlDk2Q9iFXyiFhEe5FulG4SpCb05hPKfkGVuVdn3YrfjRS\nlqfqyaADtvx2AoNoSQhMfHB1EG68WBBNaZROIE31ipFwZnaELJJ3c4LdTeqK1TE7\n5mpQFbgnFGreiC4DFBL365MGvXkj/8d/eIH7DqdRiu7QBusenE5iZSUoXogdVIHX\npQTWfZ4kJMrh1TWeSiT3ost0sxHNml5n6vCtNCeIUWIxLi6HWq9RuzVt0s7kXPbT\nJ3CpmhAeb5jYOnmFtWR8CvWMa5SqbWYNDK3nfoPkfTOnIBrHWklVyFMCbrxD/fZa\nHmlQGGhfAgMBAAECggEAM7mLFAF6P3a+GAmQ4iPjH/LoxWFU9PXHgSGW60fcSYjB\nzN3wROqVH7Y1l2DT+Mwlx+qOrRcVXSwzKFWNH15wZAQMD9LZuu60Ih9QKiaY2wAy\nZk4CtGOZJm6zMfNC68wDINNr73n8aX39lhxqlDMraaPDahH/L3ked1QsnJVd6JHj\nCxuhIUabPWm12jqrzfCM0IP/Px/Tdq309VRUFprjrWClCFPVPNkJn6d6KwKqLBKP\nWRdivTR6Lh4GFnCWb+n6c5JNQ8frv4nUhDSyMKIsqKT8YAZm0EKVWMI80gkGenjm\nN2W8ZRPsbaQeAGEw4ewYIS4+OccoWp/xrHZ6bNCY7QKBgQDu362Am5eBoCZolsZb\nd6j+PehXQFRPs8j91X0UqVfb09UudQsBSJVNKbvCKGIQdv2YlJuSOAyJOjLGs7Oy\nj6VZSNmwV7Svlbrao53VKpJwCTQpd4ECysFg34jC+8TSoshBScyKMdMZW23fXdUv\nGzZ6XxAfdTu7eXhsozG+i0ZZTQKBgQDmxZ+AXLadz0x8NRjRJPb+AOjy1bQjNw28\nuYCMskhRl2CnnyFTU6DqKzXmf406PgmEICrOqXcVRjifbyg8CN+7iAby6JT0S6we\nSGocM8n/LzMkKs/4/fo9mFYJnRYDICMgzmgnobpBPvAxofTeE2bxr6ht1UwkPK6g\nXl5tfWxSWwKBgA34hRRFhVnufPCXCOjmmbqs8j7QI145/KJj7xnbQak4vXonHEqp\n7RmDPFkBtaKS4wgegO7PWmRYRAn9DqB96ETNjvXSW139mt0Yvq1t/PySfTuDoscA\nBslcqYoF4aAUJzQyVcUrXtZX05hBy6sio1AK6U19tM2lMBbigJFNYgLtAoGBANt4\nAMv74HTOrCfH+3UT2Y4RYXloQevntLnSFW45M0vdUj+3t+LeOr/ZHma60Z4dV8F/\nMhbe1fC2mq0N8s69hcF8iVdEWDzJJsSaC8gMfMOiqNlxmd5r9CvWD6UO7ttEGgRe\nKHHgfhkE+TvKke0NuK6LZvwliUdBKrY7aURprrXXAoGAVQ0mHK+lMr/cABq3BqH2\nJWwXGmR6viQtKLxdAqKxN7NReh82zS6RW+A0cR+QWLOuRauFtgVf+mEQcscwcunM\nGsJZirPg2kcMrKJqZUgrTRVMQzkeYuoeFcdNYlCeK2hlx+HnmA3wHXBqwrIODrFP\nuJcwCrjs29a+iP7BeI52dGI=\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-ypj91@afrishop-6e142.iam.gserviceaccount.com",
"client_id": "110654393006448219899",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-ypj91%40afrishop-6e142.iam.gserviceaccount.com"
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论