1. 程式人生 > >支付寶實時到賬的MVC示例

支付寶實時到賬的MVC示例

專案結構

在這裡插入圖片描述

PaymentController.cs

using AlipayIntegrationMVC.ViewModels;
using Com.Alipay;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AlipayIMVC.Controllers
{
    public class PaymentController
: Controller { public ActionResult Buy() { return View(); } [HttpPost] public void SubmitAlipay() { ////////////////////////////////////////////請求引數//////////////////////////////////////////// //支付型別 string payment_type = "1"; //必填,不能修改 //伺服器非同步通知頁面路徑 string
notify_url = "http://www.商戶網址.com/payment/alipaynotify"; //需http://格式的完整路徑,不能加?id=123這類自定義引數 //頁面跳轉同步通知頁面路徑 string return_url = "http://www.商戶網址.com/payment/alipayreturn"; //需http://格式的完整路徑,不能加?id=123這類自定義引數,不能寫成http://localhost/ //賣家支付寶帳戶 string seller_email =
""; //必填 //商戶訂單號 string out_trade_no = "換成唯一訂單號"; //商戶網站訂單系統中唯一訂單號,必填 //訂單名稱 string subject = "換成訂單名稱"; //必填 //付款金額 string total_fee = "0.01"; //必填 //訂單描述 string body = "換成訂單描述"; //商品展示地址 string show_url = "http://www.商戶網址.com/"; //需以http://開頭的完整路徑,例如:http://www.商戶網址.com/myorder.html //防釣魚時間戳 string anti_phishing_key = ""; //若要使用請呼叫類檔案submit中的query_timestamp函式 //客戶端的IP地址 string exter_invoke_ip = ""; //非區域網的外網IP地址,如:221.0.0.1 //////////////////////////////////////////////////////////////////////////////////////////////// //把請求引數打包成陣列 SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>(); sParaTemp.Add("partner", Config.Partner); sParaTemp.Add("_input_charset", Config.Input_charset.ToLower()); sParaTemp.Add("service", "create_direct_pay_by_user"); sParaTemp.Add("payment_type", payment_type); sParaTemp.Add("notify_url", notify_url); sParaTemp.Add("return_url", return_url); sParaTemp.Add("seller_email", seller_email); sParaTemp.Add("out_trade_no", out_trade_no); sParaTemp.Add("subject", subject); sParaTemp.Add("total_fee", total_fee); sParaTemp.Add("body", body); sParaTemp.Add("show_url", show_url); sParaTemp.Add("anti_phishing_key", anti_phishing_key); sParaTemp.Add("exter_invoke_ip", exter_invoke_ip); //建立請求 string sHtmlText = Submit.BuildRequest(sParaTemp, "get", "確認"); Response.Write(sHtmlText); } // 同步呼叫,只發生一次 public ActionResult AlipayReturn() { var model = new AlipayReturnViewModel(); SortedDictionary<string, string> sPara = GetRequestGet(); if (sPara.Count > 0)//判斷是否有帶返回引數 { Notify aliNotify = new Notify(); bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]); if (verifyResult)//驗證成功 { ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //請在這裡加上商戶的業務邏輯程式程式碼 //——請根據您的業務邏輯來編寫程式(以下程式碼僅作參考)—— //獲取支付寶的通知返回引數,可參考技術文件中頁面跳轉同步通知引數列表 //商戶訂單號 model.out_trade_no = Request.QueryString["out_trade_no"]; //支付寶交易號 model.trade_no = Request.QueryString["trade_no"]; //交易狀態 model.trade_status = Request.QueryString["trade_status"]; if (Request.QueryString["trade_status"] == "TRADE_FINISHED" || Request.QueryString["trade_status"] == "TRADE_SUCCESS") { //判斷該筆訂單是否在商戶網站中已經做過處理 //如果沒有做過處理,根據訂單號(out_trade_no)在商戶網站的訂單系統中查到該筆訂單的詳細,並執行商戶的業務程式 //如果有做過處理,不執行商戶的業務程式 model.message = "支付成功"; } else { model.message = "支付失敗"; } //——請根據您的業務邏輯來編寫程式(以上程式碼僅作參考)—— ///////////////////////////////////////////////////////////////////////////////////////////////////////////// } else//驗證失敗 { model.message = ("驗證失敗"); } } else { model.message = ("無返回引數"); } return View(model); } /// <summary> /// 獲取支付寶GET過來通知訊息,並以“引數名=引數值”的形式組成陣列 /// </summary> /// <returns>request回來的資訊組成的陣列</returns> public SortedDictionary<string, string> GetRequestGet() { int i = 0; SortedDictionary<string, string> sArray = new SortedDictionary<string, string>(); NameValueCollection coll; //Load Form variables into NameValueCollection variable. coll = Request.QueryString; // Get names of all forms into a string array. String[] requestItem = coll.AllKeys; for (i = 0; i < requestItem.Length; i++) { sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]); } return sArray; } // 非同步呼叫,支付寶會在24小時內多次呼叫,直到成功為止 public ActionResult AlipayNotify() { SortedDictionary<string, string> sPara = GetRequestPost(); if (sPara.Count > 0)//判斷是否有帶返回引數 { Notify aliNotify = new Notify(); bool verifyResult = aliNotify.Verify(sPara, Request.Form["notify_id"], Request.Form["sign"]); if (verifyResult)//驗證成功 { ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //請在這裡加上商戶的業務邏輯程式程式碼 //——請根據您的業務邏輯來編寫程式(以下程式碼僅作參考)—— //獲取支付寶的通知返回引數,可參考技術文件中伺服器非同步通知引數列表 //商戶訂單號 string out_trade_no = Request.Form["out_trade_no"]; //支付寶交易號 string trade_no = Request.Form["trade_no"]; //交易狀態 string trade_status = Request.Form["trade_status"]; if (Request.Form["trade_status"] == "TRADE_FINISHED") { //判斷該筆訂單是否在商戶網站中已經做過處理 //如果沒有做過處理,根據訂單號(out_trade_no)在商戶網站的訂單系統中查到該筆訂單的詳細,並執行商戶的業務程式 //如果有做過處理,不執行商戶的業務程式 //注意: //該種交易狀態只在兩種情況下出現 //1、開通了普通即時到賬,買家付款成功後。 //2、開通了高階即時到賬,從該筆交易成功時間算起,過了簽約時的可退款時限(如:三個月以內可退款、一年以內可退款等)後。 } else if (Request.Form["trade_status"] == "TRADE_SUCCESS") { //判斷該筆訂單是否在商戶網站中已經做過處理 //如果沒有做過處理,根據訂單號(out_trade_no)在商戶網站的訂單系統中查到該筆訂單的詳細,並執行商戶的業務程式 //如果有做過處理,不執行商戶的業務程式 //注意: //該種交易狀態只在一種情況下出現——開通了高階即時到賬,買家付款成功後。 } else { } //——請根據您的業務邏輯來編寫程式(以上程式碼僅作參考)—— Response.Write("success"); //請不要修改或刪除 ///////////////////////////////////////////////////////////////////////////////////////////////////////////// } else//驗證失敗 { Response.Write("fail"); } } else { Response.Write("無通知引數"); } return View(); } /// <summary> /// 獲取支付寶POST過來通知訊息,並以“引數名=引數值”的形式組成陣列 /// </summary> /// <returns>request回來的資訊組成的陣列</returns> public SortedDictionary<string, string> GetRequestPost() { int i = 0; SortedDictionary<string, string> sArray = new SortedDictionary<string, string>(); NameValueCollection coll; //Load Form variables into NameValueCollection variable. coll = Request.Form; // Get names of all forms into a string array. String[] requestItem = coll.AllKeys; for (i = 0; i < requestItem.Length; i++) { sArray.Add(requestItem[i], Request.Form[requestItem[i]]); } return sArray; } } }

AlipayReturnViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AlipayIMVC.ViewModels
{
    public class AlipayReturnViewModel
    {
        //商戶訂單號
        public string out_trade_no { get; set; }
        //支付寶交易號
        public string trade_no { get; set; }
        //交易狀態
        public string trade_status { get; set; }
        public string message { get; set; }
    }
}

Buy.cshtml

@{
    ViewBag.Title = "Buy";
    Layout = "~/Views/_layoutCMS.cshtml";
}

<script type="text/javascript">
    function SelectBank(n) {
        $('$bank' + n).checked = true;
    }
</script>

<h1>支付寶支付1分錢測試</h1>

@using (Html.BeginForm("SubmitAlipay", "Payment", FormMethod.Post, new { @class = "form-horizontal", id = "profile-form" }))
{
    <div class="row">
        <label class="col-sm-1 no-padding-right">單價</label>
        <label class="col-sm-3"> ¥0.01 </label>
        <label class="col-sm-1 no-padding-right">數量</label>
        <label class="col-sm-3"> <input id="qty" name="qty" value="1" /> </label>
        <label class="col-sm-1 no-padding-right">總金額</label>
        <label class="col-sm-3"> ¥0.01 </label>
    </div>
    <div class="row col-xs-12">
        <h4 class="header blue smaller">
            請選擇支付方式
        </h4>
        <ul class="alipay_content">
            <li>
                <input type="radio" name="pay_bank" value="directPay" checked="checked" id="bank0" />&nbsp;<img src="/assets/images/alipay.gif" onclick="javascript:SelectBank(0);" class="alipay" alt="支付寶" />
            </li>
        </ul>
        <div class="clearfix"></div>
        <ul class="alipay_content">
            <li>
                <input type="radio" name="pay_bank" value="ICBCB2C" id="bank1" />&nbsp;<span onclick="javascript:SelectBank(1);" class="icon ICBC"></span>
            </li>
            <li>
                <input type="radio" name="pay_bank" value="CMB" id="bank2" />&nbsp;<span onclick="javascript:SelectBank(2);" class="icon CMB"></span>
            </li>
            <li>
                <input type="radio" name="pay_bank" value="CCB" id="bank3" />&nbsp;<span onclick="javascript:SelectBank(3);" class="icon CCB"></span>
            </li>
            <li>
                <input type="radio" name="pay_bank" value="BOCB2C" id="bank4" />&nbsp;<span onclick="javascript:SelectBank(4);" class="icon BOC"></span>
            </li>
            <li>
                <input type="radio" name="pay_bank" value="ABC" id="bank5" />&nbsp;<span onclick="javascript:SelectBank(5);" class="icon ABC"></span>
            </li>
            <li>
                <input type="radio" name="pay_bank" value="COMM" id="bank6" />&nbsp;<span onclick="javascript:SelectBank(6);" class="icon COMM"></span>
            </li>
            <li>
                <input ty