springMVC框架 集成支付寶即時到賬(實踐)

上一篇文章介紹了支付寶即時到賬的官方Demo,上一篇文章寫的有點投機取巧了,不過我覺得還是有必要介紹一下的。

爲了可以更好的舉一反三。

下面就拿我項目中的部分代碼來實踐一下.

支付請求

首先,是提交表單

fund.jsp(這裏我表單只需要用戶填交易金額,其他的訂單號之類的全部後臺生成)

<form id="deposit"  name= "alipaysubmit" method="post" target="_blank">
		<input type="hidden" name="user.id" value= "<shiro:principal property="id"/>" />
			<table cellpadding="10">
				<tr>
					<td>賬戶餘額</td>
					<td class="balance" id="userBalance"></td>
				</tr>
				<tr>
					<td><i class="zfb"></i></td>
					<td style="padding-bottom: 0px;">親愛的<span
						class="suppliment_user" id="suppliment_user"></span>,您可以使用支付寶充值積善分,請填寫以下信息
					</td>
				</tr>
				<tr>
					<td></td>
					<td><label class="radio inline"> <input type="radio"
							name="amount" id="optionsRadios7" value="option7">自定義<input
							class="compliment_count" name="amount" placeholder="充值金額">元
					</label></td>
				</tr>
				<tr>
					<td></td>
					<td class="warm_prompt">溫馨提示:<br />1.採用支付寶充值,1元可以充值1積善值。<br />2.若出現已充值成功的提示,但積善值未到賬,可能是網絡或者系統繁忙導致,我們會在2個工作日內核對後爲您充值<br />3在充值過程中如出現網頁錯誤或打開緩慢時,請先查詢支付寶的交易記錄,檢查扣款是否成功;然後查看積善之家賬戶是否成功充值。若沒有確認,請不要反覆刷新頁面,以防止重複購買。
					</td>
				</tr>
				<tr>
					<td></td>
					<td><button class="affirm-donate" id="rechange">立即充值</button></td>
				</tr>
			</table>
</form>
fund.js

	$('#rechange').click(function(e) {
		//$this = $("#deposit");
		e.preventDefault();
		var postData = $.toJSON(form2js('deposit', '.', true));
		console.log(postData);
		$.ajax({
			url : $CONFIG.base_url+ "/api/fund_detail/web/deposit",
			type : "POST",
			data : postData,
			contentType : "application/json",
			success : function(data) {
				
				data.total_fee = data.total_fee/100;//測試成功後請刪除
				console.log(data);
				console.log(data.sHtmlText);
				$("#deposit").append(data.sHtmlText);//後臺會返回一個新的交易表單,並自動提交。所以隨便放一個地方就OK
			},
			error : function() {
			}
		});
	});

下面就是後臺代碼:

AlipayController.java(裏面的User FundDetail都是我自己定義的實體類,與支付本身沒有關係)部分配置在AlipayConfig中,跟上篇文章的一模一樣,這這裏就不寫了

	@RequestMapping(value = "/web/deposit", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> deposit(@RequestBody FundDetail newfundDetail,Model model) {
		Date date = new Date();
		User user = new User();
		FundDetail fundDetail = new FundDetail();
		Map<String, String> sParaTemp = new HashMap<String, String>();
		// 支付類型
		// 必填,不能修改
		String payment_type = "1";
		// 服務器異步通知頁面路徑
		// 需http://格式的完整路徑,不能加?id=123這類自定義參數
		String notify_url = "http://jishanjia.lanbaoo.com/api/alipay/async";
		// 頁面跳轉同步通知頁面路徑
		// 需http://格式的完整路徑,不能加?id=123這類自定義參數,不能寫成http://localhost/
		String return_url = "http://jishanjia.lanbaoo.com/alipay/return_url";
		// 商戶訂單號.
		// 商戶網站訂單系統中唯一訂單號,必填
		//String out_trade_no = date.getTime() + "";
		// 訂單名稱
		// 必填
		String subject = "充值積善值";
		// 防釣魚時間戳
		// 若要使用請調用類文件submit中的query_timestamp函數
		String anti_phishing_key = "";
		// 客戶端的IP地址
		// 非局域網的外網IP地址,如:221.0.0.1
		String exter_invoke_ip = "";
		
		user = userService.getUser(newfundDetail.getUser().getId());
		fundDetail.setUser(user);
		fundDetail.setActionType(3);
		fundDetail.setTradeNo(date.getTime()+user.getId().toString());
		fundDetail.setAmount(newfundDetail.getAmount());
		fundDetailService.addFundDetail(fundDetail);
		
		Double total_fee = (double) (fundDetail.getAmount()/100d);//測試結束後刪除
		sParaTemp.put("total_fee", total_fee.toString());
		sParaTemp.put("service", "create_direct_pay_by_user");
		sParaTemp.put("partner", AlipayConfig.partner);
		sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", payment_type);
		sParaTemp.put("notify_url", notify_url);
		sParaTemp.put("return_url", return_url);
		sParaTemp.put("seller_id", AlipayConfig.seller_id);
		sParaTemp.put("out_trade_no", date.getTime()+user.getId().toString());
		sParaTemp.put("subject", subject);
		sParaTemp.put("anti_phishing_key", anti_phishing_key);
		sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
		sParaTemp.put("key", AlipayConfig.key);
		
		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","確認");
		
		model.addAttribute("sHtmlText", sHtmlText);
		model.addAttribute("fundDetail", fundDetail);
		
		return new ResponseEntity(model, HttpStatus.OK);
	}
到此一次交易就成功了

異步通知和跳轉:

AlipayNotifyController.java(對應上面的notify_url)

@RequestMapping(value = "/async",method = RequestMethod.GET)
	@ResponseBody
	public String async(HttpServletRequest request){
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]: valueStr + values[i] + ",";
			}
			//亂碼解決,這段代碼在出現亂碼時使用。如果mysign和sign不相等也可以使用這段代碼轉化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		String tradeNo = request.getParameter("out_trade_no");
		String tradeStatus = request.getParameter("trade_status");
		//String notifyId = request.getParameter("notify_id");
		if(AlipayNotify.verify(params)){//驗證成功
			if(tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {
				FundDetail fundDetail = new FundDetail();
				fundDetail = fundDetailService.getFundDetail(tradeNo);
				fundDetail.setActionType(1);
				fundDetailService.updateFundDetail(fundDetail);
				User user = new User();
				user = userService.getUser(fundDetail.getUser().getId());
				user.setFund(user.getFund() + fundDetail.getAmount());
				userService.updateUser(user);
				System.out.println(">>>>>充值成功" + tradeNo);
			}
			return "success";
		}else{//驗證失敗
			return "fail";
		}
	}

return_url跟notify_url差不多。在return_url控制交易成功後的跳轉頁面就可以了.


至此,一次支付寶即時到賬交易就完成了

Zemo手打,轉載請標明出處:http://blog.csdn.net/zemochen/article/details/19177563




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章