天天看點

手把手教你完成App支付JAVA背景-支付寶支付JAVA支付寶參數擷取支付寶預付單

接着上一篇部落格,我們暫時完成了手機端的部分支付代碼,接下來,我們繼續寫背景的代碼。

背景基本需要到以下幾個參數,我都将他們寫在了properties檔案中:

支付寶參數

AliPay.payURL = https://openapi.alipay.com/gateway.do

商戶公鑰

AliPay.publicKey = xxx // 支付寶公鑰

AliPay.appId = xxx //APPid

AliPay.timeoutExpress = xxx 逾時時間

AliPay.notifyUrl = http://xxx 異步通知位址,背景寫的一個接口供支付寶伺服器推送支付結果,前端的支付結果最終取決于支付寶推送的結果。

附:在我的項目裡,支付流程是這樣子的
           

首先手機端選擇商品、數量等資訊,完成下單。此時,在資料庫,有一條下單記錄,該條記錄在半小時内有效,使用者需在半小時内完成支付,否則該筆交易将失敗。在有效時間内,使用者選擇支付時,背景提供擷取支付寶預付單的接口,手機端拿到預付單後,再調起支付寶發起支付,手機端支付完成後,再次調用背景的真實支付結果,最後展示給使用者。

我們的重點是支付,是以下單的接口就略過。下面:

擷取支付寶預付單

/**
	 * 拉取支付寶預付單
	 */
	@ValidatePermission(value = PermissionValidateType.Validate)
	@Override
	public BaseResult<Orders> getAliPay(BaseRequest<Orders> baseRequest)
	{
		LogUtil.debugLog(logger, baseRequest);
		BaseResult<Orders> baseResult = new BaseResult<>();
		Orders orders = baseRequest.getData(); // 擷取訂單的實體
		Double price = orders.getOrderAmount();
		if (price <= 0) // 一些必要的驗證,防止抓包惡意修改支付金額
		{
			baseResult.setState(-999);
			baseResult.setMsg("付款金額錯誤!");
			baseResult.setSuccess(false);
			return baseResult;
		}
		try
		{
			AlipayClient alipayClient = PayCommonUtil.getAliClient();
			AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
			AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
			model.setOutTradeNo(orders.getId() + "");// 訂單号。
			model.setTimeoutExpress(PropertyUtil.getInstance().getProperty("AliPay.timeoutExpress"));// 設定未付款支付寶交易的逾時時間,一旦逾時,該筆交易就會自動被關閉。當使用者進入支付寶收銀台頁面(不包括登入頁面),會觸發即刻建立支付寶交易,此時開始計時。取值範圍:1m~15d。m-分鐘,h-小時,d-天,1c-當天(1c-當天的情況下,無論交易何時建立,都在0點關閉)。
			// 該參數數值不接受小數點, 如 1.5h,可轉換為 90m。
			model.setTotalAmount("0.01");// 訂單總金額,機關為元,精确到小數點後兩位,取值範圍[0.01,100000000]這裡調試每次支付1分錢,在項目上線前應将此處改為訂單的總金額
			model.setProductCode("QUICK_MSECURITY_PAY");// 銷售産品碼,商家和支付寶簽約的産品碼,為固定值QUICK_MSECURITY_PAY
			request.setBizModel(model);
			request.setNotifyUrl(PropertyUtil.getInstance().getProperty("AliPay.notifyUrl")); // 設定背景異步通知的位址,在手機端支付成功後支付寶會通知背景,手機端的真實支付結果依賴于此位址
			// 根據不同的産品
			
				model.setBody(xxx);// 對一筆交易的具體描述資訊。如果是多種商品,請将商品描述字元串累加傳給body。
				model.setSubject("商品的标題/交易标題/訂單标題/訂單關鍵字等");
				break;
			// 這裡和普通的接口調用不同,使用的是sdkExecute
			AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
			// 可以直接給用戶端請求,無需再做處理。
			orders.setAliPayOrderString(response.getBody());
			baseResult.setData(orders);
		} catch (Exception e)
		{
			e.printStackTrace();
			baseResult.setState(-999);
			baseResult.setMsg("程式異常!");
			baseResult.setSuccess(false);
			logger.error(e.getMessage());
		}
		return baseResult;
	}
           

在上面一段代碼中,我們已經将支付寶服務端生成的預付單資訊傳回給了用戶端,至此,用戶端已經可以支付。支付結果支付寶将會異步給背景通知,下面是異步通知的代碼:

/**
	 * 支付寶異步通知
	 */
	@ValidatePermission
	@RequestMapping(value = "/notify/ali", method = RequestMethod.POST, consumes = "application/json", produces = "text/html;charset=UTF-8") 
	@ResponseBody
	public String ali(HttpServletRequest request)
	{
		Map<String, String> params = new HashMap<String, String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();)
		{
			String name = (String) iter.next();
			String[] values = requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++)
			{
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			logger.debug("name:" + name + "    value:" + valueStr);
			// 亂碼解決,這段代碼在出現亂碼時使用。
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		// 切記alipaypublickey是支付寶的公鑰,請去open.alipay.com對應應用下檢視。
		boolean flag = true; // 校驗公鑰正确性防止意外
		try
		{
			flag = AlipaySignature.rsaCheckV1(params, PropertyUtil.getInstance().getProperty("AliPay.AliPay.publicKey"),
					"utf-8", "RSA2");
		} catch (AlipayApiException e)
		{
			e.printStackTrace();
		}
		if (flag)
		{
			Integer ordersId = Integer.parseInt(params.get("out_trade_no"));
			String tradeStatus = params.get("trade_status");
			Orders orders = new Orders();
			orders.setId(ordersId);
			orders.setPayWay("2"); // 支付方式為支付寶
			// orders.setOrderState("1"); // 訂單狀态位已支付
			switch (tradeStatus) // 判斷交易結果
			{
			case "TRADE_FINISHED": // 完成
				orders.setOrderState("1");
				break;
			case "TRADE_SUCCESS": // 完成
				orders.setOrderState("1");
				break;
			case "WAIT_BUYER_PAY": // 待支付
				orders.setOrderState("0");
				break;
			case "TRADE_CLOSED": // 交易關閉
				orders.setOrderState("0");
				break;
			default:
				break;
			}
			ordersService.updateByPrimaryKeySelective(orders); // 更新背景交易狀态
		}
		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
		AlipayNotice alipayNotice = new AlipayNotice();
		try // set一堆日期和屬性
		{
			alipayNotice.setAppId(params.get("app_id")); 
			alipayNotice.setBody(params.get("body"));
			alipayNotice.setBuyerId(params.get("buyer_id"));
			alipayNotice.setBuyerLogonId(params.get("buyer_logon_id"));
			alipayNotice.setBuyerPayAmount(Double.parseDouble(params.get("buyer_pay_amount")));
			alipayNotice.setCharset(params.get("charset"));
			alipayNotice.setFundBillList(params.get("fund_bill_list"));
			alipayNotice.setGmtClose(f.parse(params.get("gmt_close")));
			alipayNotice.setGmtCreate(f.parse(params.get("gmt_create")));
			alipayNotice.setGmtPayment(f.parse(params.get("gmt_payment")));
			alipayNotice.setGmtRefund(f1.parse(params.get("gmt_refund")));
			alipayNotice.setNotifyTime(f.parse(params.get("notify_time")));
		} catch (ParseException e)
		{
			PayCommonUtil.saveE("C\\logs\\aliParseException", e); // 由于需要在外網測試,是以将錯誤日志儲存一下友善調試
			logger.error("--------------------------------日期轉換異常");
			e.printStackTrace();
		}
		try
		{
			alipayNotice.setInvoiceAmount(Double.parseDouble(params.get("invoice_amount")));
			alipayNotice.setNotifyId(params.get("notify_id"));
			alipayNotice.setNotifyType(params.get("notify_type"));
			alipayNotice.setOutBizNo(params.get("out_biz_no"));
			alipayNotice.setOutTradeNo(params.get("out_trade_no"));
			alipayNotice.setPassbackParams(params.get("passback_params"));
			alipayNotice.setPointAmount(Double.parseDouble(params.get("point_amount")));
			alipayNotice.setReceiptAmount(Double.parseDouble(params.get("receipt_amount")));
			alipayNotice.setRefundFee(Double.parseDouble(params.get("refund_fee")));
			alipayNotice.setSellerEmail(params.get("seller_email"));
			alipayNotice.setSellerId(params.get("seller_id"));
			alipayNotice.setSign(params.get("sign"));
			alipayNotice.setSignType(params.get("sign_type"));
			alipayNotice.setSubject(params.get("subject"));
			alipayNotice.setTotalAmount(Double.parseDouble(params.get("total_amount")));
			alipayNotice.setTradeNo(params.get("trade_no"));
			alipayNotice.setTradeStatus(params.get("trade_status"));
			alipayNotice.setVersion(params.get("version"));
			alipayNotice.setVoucherDetailList(params.get("voucher_detail_list"));
			alipayNotice.setCreateTime(new Date());
			PayCommonUtil.saveLog("C\\logs\\支付寶實體類.txt", alipayNotice.toString());
			int res = alipayNoticeMapper.insertSelective(alipayNotice); // 儲存結果
			PayCommonUtil.saveLog("C\\logs\\支付寶結果.txt", res + "");
			return "success";
		} catch (Exception e)
		{
			PayCommonUtil.saveE("C\\logs\\支付寶異常了.txt", e);
		}
		logger.debug("----------------------------執行到了最後!!!--------------");
		return "success";
	}
           

至此,支付寶支付的核心代碼已完成。由于在外網調試,很多地方不太友善是以我隻能将他們儲存txt檢視異常,如果有更好的辦法請留言一起改進。

這裡用到了大量的工具類:(也包含了微信的工具類)我直接貼出來給大家做參考,也可以點選這裡下載下傳,(現在下載下傳必須扣積分,積分多的可以直接下),有不足之處希望大家提出來共同進步。

package com.loveFly.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;

public class PayCommonUtil
{
	public static final String TIME = "yyyyMMddHHmmss";

	/**
	 * 建立支付寶交易對象
	 */
	public static AlipayClient getAliClient()
	{
		AlipayClient alipayClient = new DefaultAlipayClient(PropertyUtil.getInstance().getProperty("AliPay.payURL"),
				PropertyUtil.getInstance().getProperty("AliPay.appId"),
				PropertyUtil.getInstance().getProperty("AliPay.privateKey"), "json", "utf-8",
				PropertyUtil.getInstance().getProperty("AliPay.publicKey"), "RSA2");
		return alipayClient;
	}

	/**
	 * 建立微信交易對象
	 */
	public static SortedMap<Object, Object> getWXPrePayID()
	{
		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		parameters.put("appid", PropertyUtil.getInstance().getProperty("WxPay.appid"));
		parameters.put("mch_id", PropertyUtil.getInstance().getProperty("WxPay.mchid"));
		parameters.put("nonce_str", PayCommonUtil.CreateNoncestr());
		parameters.put("fee_type", "CNY");
		parameters.put("notify_url", PropertyUtil.getInstance().getProperty("WxPay.notifyurl"));
		parameters.put("trade_type", "APP");
		return parameters;
	}

	/**
	 * 再次簽名,支付
	 */
	public static SortedMap<Object, Object> startWXPay(String result)
	{
		try
		{
			Map<String, String> map = XMLUtil.doXMLParse(result);
			SortedMap<Object, Object> parameterMap = new TreeMap<Object, Object>();
			parameterMap.put("appid", PropertyUtil.getInstance().getProperty("WxPay.appid"));
			parameterMap.put("partnerid", PropertyUtil.getInstance().getProperty("WxPay.mchid"));
			parameterMap.put("prepayid", map.get("prepay_id"));
			parameterMap.put("package", "Sign=WXPay");
			parameterMap.put("noncestr", PayCommonUtil.CreateNoncestr());
			// 本來生成的時間戳是13位,但是ios必須是10位,是以截取了一下
			parameterMap.put("timestamp",
					Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0, 10)));
			String sign = PayCommonUtil.createSign("UTF-8", parameterMap);
			parameterMap.put("sign", sign);
			return parameterMap;
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 建立随機數
	 * 
	 * @param length
	 * @return
	 */
	public static String CreateNoncestr()
	{
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String res = "";
		for (int i = 0; i < 16; i++)
		{
			Random rd = new Random();
			res += chars.charAt(rd.nextInt(chars.length() - 1));
		}
		return res;
	}

	/**
	 * 是否簽名正确,規則是:按參數名稱a-z排序,遇到空值的參數不參加簽名。
	 * 
	 * @return boolean
	 */
	public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams)
	{
		StringBuffer sb = new StringBuffer();
		Set es = packageParams.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 (!"sign".equals(k) && null != v && !"".equals(v))
			{
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + PropertyUtil.getInstance().getProperty("WxPay.key"));
		// 算出摘要
		String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
		String tenpaySign = ((String) packageParams.get("sign")).toLowerCase();
		// System.out.println(tenpaySign + " " + mysign);
		return tenpaySign.equals(mysign);
	}

	/**
	 * @Description:建立sign簽名
	 * @param characterEncoding
	 *            編碼格式
	 * @param parameters
	 *            請求參數
	 * @return
	 */
	public static String createSign(String characterEncoding, SortedMap<Object, Object> parameters)
	{
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext())
		{
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			Object v = entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k))
			{
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + PropertyUtil.getInstance().getProperty("WxPay.key"));
		String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
		return sign;
	}

	/**
	 * @Description:将請求參數轉換為xml格式的string
	 * @param parameters
	 *            請求參數
	 * @return
	 */
	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))
			{
				sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
			} else
			{
				sb.append("<" + k + ">" + v + "</" + k + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}

	/**
	 * @Description:傳回給微信的參數
	 * @param return_code
	 *            傳回編碼
	 * @param return_msg
	 *            傳回資訊
	 * @return
	 */
	public static String setXML(String return_code, String return_msg)
	{
		return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg
				+ "]]></return_msg></xml>";
	}

	/**
	 * 發送https請求
	 * 
	 * @param requestUrl
	 *            請求位址
	 * @param requestMethod
	 *            請求方式(GET、POST)
	 * @param outputStr
	 *            送出的資料
	 * @return 傳回微信伺服器響應的資訊
	 */
	public static String httpsRequest(String requestUrl, String requestMethod, String outputStr)
	{
		try
		{
			// 建立SSLContext對象,并使用我們指定的信任管理器初始化
			TrustManager[] tm =
			{ new TrustManagerUtil() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 從上述SSLContext對象中得到SSLSocketFactory對象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			// conn.setSSLSocketFactory(ssf);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// 設定請求方式(GET/POST)
			conn.setRequestMethod(requestMethod);
			conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
			// 當outputStr不為null時向輸出流寫資料
			if (null != outputStr)
			{
				OutputStream outputStream = conn.getOutputStream();
				// 注意編碼格式
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			// 從輸入流讀取傳回内容
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null)
			{
				buffer.append(str);
			}
			// 釋放資源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			conn.disconnect();
			return buffer.toString();
		} catch (ConnectException ce)
		{
			// log.error("連接配接逾時:{}", ce);
		} catch (Exception e)
		{
			// log.error("https請求異常:{}", e);
		}
		return null;
	}

	/**
	 * 發送https請求
	 * 
	 * @param requestUrl
	 *            請求位址
	 * @param requestMethod
	 *            請求方式(GET、POST)
	 * @param outputStr
	 *            送出的資料
	 * @return JSONObject(通過JSONObject.get(key)的方式擷取json對象的屬性值)
	 */
	public static JSONObject httpsRequest(String requestUrl, String requestMethod)
	{
		JSONObject jsonObject = null;
		try
		{
			// 建立SSLContext對象,并使用我們指定的信任管理器初始化
			TrustManager[] tm =
			{ new TrustManagerUtil() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 從上述SSLContext對象中得到SSLSocketFactory對象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			// conn.setSSLSocketFactory(ssf);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(3000);
			// 設定請求方式(GET/POST)
			conn.setRequestMethod(requestMethod);
			// conn.setRequestProperty("content-type",
			// "application/x-www-form-urlencoded");
			// 當outputStr不為null時向輸出流寫資料
			// 從輸入流讀取傳回内容
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null)
			{
				buffer.append(str);
			}
			// 釋放資源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			conn.disconnect();
			jsonObject = JSONObject.parseObject(buffer.toString());
		} catch (ConnectException ce)
		{
			// log.error("連接配接逾時:{}", ce);
		} catch (Exception e)
		{
			System.out.println(e);
			// log.error("https請求異常:{}", e);
		}
		return jsonObject;
	}

	public static String urlEncodeUTF8(String source)
	{
		String result = source;
		try
		{
			result = java.net.URLEncoder.encode(source, "utf-8");
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 接收微信的異步通知
	 * 
	 * @throws IOException
	 */
	public static String reciverWx(HttpServletRequest request) throws IOException
	{
		InputStream inputStream;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = in.readLine()) != null)
		{
			sb.append(s);
		}
		in.close();
		inputStream.close();
		return sb.toString();
	}

	/**
	 * 産生num位的随機數
	 * 
	 * @return
	 */
	public static String getRandByNum(int num)
	{
		String length = "1";
		for (int i = 0; i < num; i++)
		{
			length += "0";
		}
		Random rad = new Random();
		String result = rad.nextInt(Integer.parseInt(length)) + "";
		if (result.length() != num)
		{
			return getRandByNum(num);
		}
		return result;
	}

	/**
	 * 傳回目前時間字元串
	 * 
	 * @return yyyyMMddHHmmss
	 */
	public static String getDateStr()
	{
		SimpleDateFormat sdf = new SimpleDateFormat(TIME);
		return sdf.format(new Date());
	}

	/**
	 * 将日志儲存至指定路徑
	 * 
	 * @param path
	 * @param str
	 */
	public static void saveLog(String path, String str)
	{
		File file = new File(path);
		FileOutputStream fos = null;
		try
		{
			fos = new FileOutputStream(path);
			fos.write(str.getBytes());
			fos.close();
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public static void saveE(String path, Exception exception)
	{
		try {
            int i = 1 / 0;
        } catch (final Exception e) {
            try {
                new PrintWriter(new BufferedWriter(new FileWriter(
                		path, true)), true).println(new Object() {
                    public String toString() {
                        StringWriter stringWriter = new StringWriter();
                        PrintWriter writer = new PrintWriter(stringWriter);
                        e.printStackTrace(writer);
                        StringBuffer buffer = stringWriter.getBuffer();
                        return buffer.toString();
                    }
                });
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
		
	}
}

           

這裡我自己建了一個類記錄支付寶的通知内容并儲存在背景資料庫:AlipayNotice

public class AlipayNotice {
    /**
     * ID
     */
    private Integer id;

    /**
     * 通知時間
     */
    private Date notifyTime;

    /**
     * 通知類型
     */
    private String notifyType;

    /**
     * 通知校驗ID
     */
    private String notifyId;

    /**
     * 支付寶配置設定給開發者的應用Id
     */
    private String appId;

    /**
     * 編碼格式
     */
    private String charset;

    /**
     * 接口版本
     */
    private String version;

    /**
     * 簽名類型
     */
    private String signType;

    /**
     * 簽名
     */
    private String sign;

    /**
     * 支付寶交易号
     */
    private String tradeNo;

    /**
     * 商戶訂單号
     */
    private String outTradeNo;

    /**
     * 商戶業務号
     */
    private String outBizNo;

    /**
     * 買家支付寶使用者号
     */
    private String buyerId;

    /**
     * 買家支付寶賬号
     */
    private String buyerLogonId;

    /**
     * 賣家支付寶使用者号
     */
    private String sellerId;

    /**
     * 賣家支付寶賬号
     */
    private String sellerEmail;

    /**
     * 交易狀态
     */
    private String tradeStatus;

    /**
     * 訂單金額
     */
    private Double totalAmount;

    /**
     * 實收金額
     */
    private Double receiptAmount;

    /**
     * 開票金額
     */
    private Double invoiceAmount;

    /**
     * 付款金額
     */
    private Double buyerPayAmount;

    /**
     * 集分寶金額
     */
    private Double pointAmount;

    /**
     * 總退款金額
     */
    private Double refundFee;

    /**
     * 訂單标題
     */
    private String subject;

    /**
     * 商品描述
     */
    private String body;

    /**
     * 交易建立時間
     */
    private Date gmtCreate;

    /**
     * 交易付款時間
     */
    private Date gmtPayment;

    /**
     * 交易退款時間
     */
    private Date gmtRefund;

    /**
     * 交易結束時間
     */
    private Date gmtClose;

    /**
     * 支付金額資訊
     */
    private String fundBillList;

    /**
     * 回傳參數
     */
    private String passbackParams;

    /**
     * 優惠券資訊
     */
    private String voucherDetailList;

    /**
     * 資料插入時間
     */
    private Date createTime;

    /**
     * ID
     */
    public Integer getId() {
        return id;
    }

    /**
     * ID
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * 通知時間
     */
    public Date getNotifyTime() {
        return notifyTime;
    }

    /**
     * 通知時間
     */
    public void setNotifyTime(Date notifyTime) {
        this.notifyTime = notifyTime;
    }

    /**
     * 通知類型
     */
    public String getNotifyType() {
        return notifyType;
    }

    /**
     * 通知類型
     */
    public void setNotifyType(String notifyType) {
        this.notifyType = notifyType == null ? null : notifyType.trim();
    }

    /**
     * 通知校驗ID
     */
    public String getNotifyId() {
        return notifyId;
    }

    /**
     * 通知校驗ID
     */
    public void setNotifyId(String notifyId) {
        this.notifyId = notifyId == null ? null : notifyId.trim();
    }

    /**
     * 支付寶配置設定給開發者的應用Id
     */
    public String getAppId() {
        return appId;
    }

    /**
     * 支付寶配置設定給開發者的應用Id
     */
    public void setAppId(String appId) {
        this.appId = appId == null ? null : appId.trim();
    }

    /**
     * 編碼格式
     */
    public String getCharset() {
        return charset;
    }

    /**
     * 編碼格式
     */
    public void setCharset(String charset) {
        this.charset = charset == null ? null : charset.trim();
    }

    /**
     * 接口版本
     */
    public String getVersion() {
        return version;
    }

    /**
     * 接口版本
     */
    public void setVersion(String version) {
        this.version = version == null ? null : version.trim();
    }

    /**
     * 簽名類型
     */
    public String getSignType() {
        return signType;
    }

    /**
     * 簽名類型
     */
    public void setSignType(String signType) {
        this.signType = signType == null ? null : signType.trim();
    }

    /**
     * 簽名
     */
    public String getSign() {
        return sign;
    }

    /**
     * 簽名
     */
    public void setSign(String sign) {
        this.sign = sign == null ? null : sign.trim();
    }

    /**
     * 支付寶交易号
     */
    public String getTradeNo() {
        return tradeNo;
    }

    /**
     * 支付寶交易号
     */
    public void setTradeNo(String tradeNo) {
        this.tradeNo = tradeNo == null ? null : tradeNo.trim();
    }

    /**
     * 商戶訂單号
     */
    public String getOutTradeNo() {
        return outTradeNo;
    }

    /**
     * 商戶訂單号
     */
    public void setOutTradeNo(String outTradeNo) {
        this.outTradeNo = outTradeNo == null ? null : outTradeNo.trim();
    }

    /**
     * 商戶業務号
     */
    public String getOutBizNo() {
        return outBizNo;
    }

    /**
     * 商戶業務号
     */
    public void setOutBizNo(String outBizNo) {
        this.outBizNo = outBizNo == null ? null : outBizNo.trim();
    }

    /**
     * 買家支付寶使用者号
     */
    public String getBuyerId() {
        return buyerId;
    }

    /**
     * 買家支付寶使用者号
     */
    public void setBuyerId(String buyerId) {
        this.buyerId = buyerId == null ? null : buyerId.trim();
    }

    /**
     * 買家支付寶賬号
     */
    public String getBuyerLogonId() {
        return buyerLogonId;
    }

    /**
     * 買家支付寶賬号
     */
    public void setBuyerLogonId(String buyerLogonId) {
        this.buyerLogonId = buyerLogonId == null ? null : buyerLogonId.trim();
    }

    /**
     * 賣家支付寶使用者号
     */
    public String getSellerId() {
        return sellerId;
    }

    /**
     * 賣家支付寶使用者号
     */
    public void setSellerId(String sellerId) {
        this.sellerId = sellerId == null ? null : sellerId.trim();
    }

    /**
     * 賣家支付寶賬号
     */
    public String getSellerEmail() {
        return sellerEmail;
    }

    /**
     * 賣家支付寶賬号
     */
    public void setSellerEmail(String sellerEmail) {
        this.sellerEmail = sellerEmail == null ? null : sellerEmail.trim();
    }

    /**
     * 交易狀态
     */
    public String getTradeStatus() {
        return tradeStatus;
    }

    /**
     * 交易狀态
     */
    public void setTradeStatus(String tradeStatus) {
        this.tradeStatus = tradeStatus == null ? null : tradeStatus.trim();
    }

    /**
     * 訂單金額
     */
    public Double getTotalAmount() {
        return totalAmount;
    }

    /**
     * 訂單金額
     */
    public void setTotalAmount(Double totalAmount) {
        this.totalAmount = totalAmount;
    }

    /**
     * 實收金額
     */
    public Double getReceiptAmount() {
        return receiptAmount;
    }

    /**
     * 實收金額
     */
    public void setReceiptAmount(Double receiptAmount) {
        this.receiptAmount = receiptAmount;
    }

    /**
     * 開票金額
     */
    public Double getInvoiceAmount() {
        return invoiceAmount;
    }

    /**
     * 開票金額
     */
    public void setInvoiceAmount(Double invoiceAmount) {
        this.invoiceAmount = invoiceAmount;
    }

    /**
     * 付款金額
     */
    public Double getBuyerPayAmount() {
        return buyerPayAmount;
    }

    /**
     * 付款金額
     */
    public void setBuyerPayAmount(Double buyerPayAmount) {
        this.buyerPayAmount = buyerPayAmount;
    }

    /**
     * 集分寶金額
     */
    public Double getPointAmount() {
        return pointAmount;
    }

    /**
     * 集分寶金額
     */
    public void setPointAmount(Double pointAmount) {
        this.pointAmount = pointAmount;
    }

    /**
     * 總退款金額
     */
    public Double getRefundFee() {
        return refundFee;
    }

    /**
     * 總退款金額
     */
    public void setRefundFee(Double refundFee) {
        this.refundFee = refundFee;
    }

    /**
     * 訂單标題
     */
    public String getSubject() {
        return subject;
    }

    /**
     * 訂單标題
     */
    public void setSubject(String subject) {
        this.subject = subject == null ? null : subject.trim();
    }

    /**
     * 商品描述
     */
    public String getBody() {
        return body;
    }

    /**
     * 商品描述
     */
    public void setBody(String body) {
        this.body = body == null ? null : body.trim();
    }

    /**
     * 交易建立時間
     */
    public Date getGmtCreate() {
        return gmtCreate;
    }

    /**
     * 交易建立時間
     */
    public void setGmtCreate(Date gmtCreate) {
        this.gmtCreate = gmtCreate;
    }

    /**
     * 交易付款時間
     */
    public Date getGmtPayment() {
        return gmtPayment;
    }

    /**
     * 交易付款時間
     */
    public void setGmtPayment(Date gmtPayment) {
        this.gmtPayment = gmtPayment;
    }

    /**
     * 交易退款時間
     */
    public Date getGmtRefund() {
        return gmtRefund;
    }

    /**
     * 交易退款時間
     */
    public void setGmtRefund(Date gmtRefund) {
        this.gmtRefund = gmtRefund;
    }

    /**
     * 交易結束時間
     */
    public Date getGmtClose() {
        return gmtClose;
    }

    /**
     * 交易結束時間
     */
    public void setGmtClose(Date gmtClose) {
        this.gmtClose = gmtClose;
    }

    /**
     * 支付金額資訊
     */
    public String getFundBillList() {
        return fundBillList;
    }

    /**
     * 支付金額資訊
     */
    public void setFundBillList(String fundBillList) {
        this.fundBillList = fundBillList == null ? null : fundBillList.trim();
    }

    /**
     * 回傳參數
     */
    public String getPassbackParams() {
        return passbackParams;
    }

    /**
     * 回傳參數
     */
    public void setPassbackParams(String passbackParams) {
        this.passbackParams = passbackParams == null ? null : passbackParams.trim();
    }

    /**
     * 優惠券資訊
     */
    public String getVoucherDetailList() {
        return voucherDetailList;
    }

    /**
     * 優惠券資訊
     */
    public void setVoucherDetailList(String voucherDetailList) {
        this.voucherDetailList = voucherDetailList == null ? null : voucherDetailList.trim();
    }

    /**
     * 資料插入時間
     */
    public Date getCreateTime() {
        return createTime;
    }

    /**
     * 資料插入時間
     */
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
           

到此支付寶支付流程已經走完,如果你對支付流程不是很了解,建議先多看看流程圖,會對你在處理業務邏輯上有很大的幫助。