調用支付寶轉帳接口(單筆)

下面這幾個類都是支付寶demo裏面的,直接拿過來用就能夠javascript

using System.Web;
using System.Text;
using System.IO;
using System.Net;
using System;
using System.Collections.Generic;

namespace Com.Alipay
{
    public class Config
    {
        #region 字段
        private static string partner = "";
        private static string key = "";
        private static string input_charset = "";
        private static string sign_type = "";
        #endregion
        static Config()
        {
            //合做身份者ID,以2088開頭由16位純數字組成的字符串
            partner = "公司的";
            //交易安全檢驗碼,由數字和字母組成的32位字符串
            key = "公司的";
            //字符編碼格式 目前支持 gbk 或 utf-8
            input_charset = "utf-8";
            //簽名方式,選擇項:RSA、DSA、MD5
            sign_type = "MD5";
        }
        #region 屬性
        /// <summary>
        /// 獲取或設置合做者身份ID
        /// </summary>
        public static string Partner
        {
            get { return partner; }
            set { partner = value; }
        }

        /// <summary>
        /// 獲取或設交易安全校驗碼
        /// </summary>
        public static string Key
        {
            get { return key; }
            set { key = value; }
        }

        /// <summary>
        /// 獲取字符編碼格式
        /// </summary>
        public static string Input_charset
        {
            get { return input_charset; }
        }

        /// <summary>
        /// 獲取簽名方式
        /// </summary>
        public static string Sign_type
        {
            get { return sign_type; }
        }
        #endregion
    }
}

  

using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Net;
using System;
using System.Collections.Generic;
using System.Xml;

namespace Com.Alipay
{
    public class Core
    {

        public Core()
        {
        }

        /// <summary>
        /// 除去數組中的空值和簽名參數並以字母a到z的順序排序
        /// </summary>
        /// <param name="dicArrayPre">過濾前的參數組</param>
        /// <returns>過濾後的參數組</returns>
        public static Dictionary<string, string> FilterPara(SortedDictionary<string, string> dicArrayPre)
        {
            Dictionary<string, string> dicArray = new Dictionary<string, string>();
            foreach (KeyValuePair<string, string> temp in dicArrayPre)
            {
                if (temp.Key.ToLower() != "sign" && temp.Key.ToLower() != "sign_type" && temp.Value != "" && temp.Value != null)
                {
                    dicArray.Add(temp.Key, temp.Value);
                }
            }
            return dicArray;
        }
        /// <summary>
        /// 把數組全部元素,按照「參數=參數值」的模式用「&」字符拼接成字符串
        /// </summary>
        /// <param name="sArray">須要拼接的數組</param>
        /// <returns>拼接完成之後的字符串</returns>
        public static string CreateLinkString(Dictionary<string, string> dicArray)
        {
            StringBuilder prestr = new StringBuilder();
            foreach (KeyValuePair<string, string> temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }

            //去掉最後一個&字符
            int nLen = prestr.Length;
            prestr.Remove(nLen-1,1);

            return prestr.ToString();
        }
        /// <summary>
        /// 把數組全部元素,按照「參數=參數值」的模式用「&」字符拼接成字符串,並對參數值作urlencode
        /// </summary>
        /// <param name="sArray">須要拼接的數組</param>
        /// <param name="code">字符編碼</param>
        /// <returns>拼接完成之後的字符串</returns>
        public static string CreateLinkStringUrlencode(Dictionary<string, string> dicArray, Encoding code)
        {
            StringBuilder prestr = new StringBuilder();
            foreach (KeyValuePair<string, string> temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + HttpUtility.UrlEncode(temp.Value, code) + "&");
            }

            //去掉最後一個&字符
            int nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);

            return prestr.ToString();
        }
        /// <summary>
        /// 寫日誌,方便測試(看網站需求,也能夠改爲把記錄存入數據庫)
        /// </summary>
        /// <param name="sWord">要寫入日誌裏的文本內容</param>
        public static void LogResult(string sWord)
        {
            string strPath = HttpContext.Current.Server.MapPath("log");
            strPath = strPath + "\\" + DateTime.Now.ToString().Replace(":", "") + ".txt";
            StreamWriter fs = new StreamWriter(strPath, false, System.Text.Encoding.Default);
            fs.Write(sWord);
            fs.Close();
        }
        /// <summary>
        /// 獲取文件的md5摘要
        /// </summary>
        /// <param name="sFile">文件流</param>
        /// <returns>MD5摘要結果</returns>
        public static string GetAbstractToMD5(Stream sFile)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(sFile);
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }
        /// <summary>
        /// 獲取文件的md5摘要
        /// </summary>
        /// <param name="dataFile">文件流</param>
        /// <returns>MD5摘要結果</returns>
        public static string GetAbstractToMD5(byte[] dataFile)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(dataFile);
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }
    }
}
using System.Web;
using System.Text;
using System.IO;
using System.Net;
using System;
using System.Collections.Generic;

namespace Com.Alipay
{
    public class Notify
    {
        #region 字段
        private string _partner = "";               //合做身份者ID
        private string _key = "";                   //商戶的私鑰
        private string _input_charset = "";         //編碼格式
        private string _sign_type = "";             //簽名方式

        //支付寶消息驗證地址
        private string Https_veryfy_url = "https://mapi.alipay.com/gateway.do?service=notify_verify&";
        #endregion
        /// <summary>
        /// 構造函數
        /// 從配置文件中初始化變量
        /// </summary>
        /// <param name="inputPara">通知返回參數數組</param>
        /// <param name="notify_id">通知驗證ID</param>
        public Notify()
        {
            //初始化基礎配置信息
            _partner = Config.Partner.Trim();
            _key = Config.Key.Trim();
            _input_charset = Config.Input_charset.Trim().ToLower();
            _sign_type = Config.Sign_type.Trim().ToUpper();
        }
        /// <summary>
        ///  驗證消息是不是支付寶發出的合法消息
        /// </summary>
        /// <param name="inputPara">通知返回參數數組</param>
        /// <param name="notify_id">通知驗證ID</param>
        /// <param name="sign">支付寶生成的簽名結果</param>
        /// <returns>驗證結果</returns>
        public bool Verify(SortedDictionary<string, string> inputPara, string notify_id, string sign)
        {
            //獲取返回時的簽名驗證結果
            bool isSign = GetSignVeryfy(inputPara, sign);
            //獲取是不是支付寶服務器發來的請求的驗證結果
            string responseTxt = "false";
            if (notify_id != null && notify_id != "") { responseTxt = GetResponseTxt(notify_id); }

            //寫日誌記錄(若要調試,請取消下面兩行註釋)
            //string sWord = "responseTxt=" + responseTxt + "\n isSign=" + isSign.ToString() + "\n 返回回來的參數:" + GetPreSignStr(inputPara) + "\n ";
            //Core.LogResult(sWord);

            //判斷responsetTxt是否爲true,isSign是否爲true
            //responsetTxt的結果不是true,與服務器設置問題、合做身份者ID、notify_id一分鐘失效有關
            //isSign不是true,與安全校驗碼、請求時的參數格式(如:帶自定義參數等)、編碼格式有關
            if (responseTxt == "true" && isSign)//驗證成功
            {
                return true;
            }
            else//驗證失敗
            {
                return false;
            }
        }
        /// <summary>
        /// 獲取待簽名字符串(調試用)
        /// </summary>
        /// <param name="inputPara">通知返回參數數組</param>
        /// <returns>待簽名字符串</returns>
        private string GetPreSignStr(SortedDictionary<string, string> inputPara)
        {
            Dictionary<string, string> sPara = new Dictionary<string, string>();
            //過濾空值、sign與sign_type參數
            sPara = Core.FilterPara(inputPara);
            //獲取待簽名字符串
            string preSignStr = Core.CreateLinkString(sPara);
            return preSignStr;
        }
        /// <summary>
        /// 獲取返回時的簽名驗證結果
        /// </summary>
        /// <param name="inputPara">通知返回參數數組</param>
        /// <param name="sign">對比的簽名結果</param>
        /// <returns>簽名驗證結果</returns>
        private bool GetSignVeryfy(SortedDictionary<string, string> inputPara, string sign)
        {
            Dictionary<string, string> sPara = new Dictionary<string, string>();
            //過濾空值、sign與sign_type參數
            sPara = Core.FilterPara(inputPara);
            //獲取待簽名字符串
            string preSignStr = Core.CreateLinkString(sPara);
            //得到簽名驗證結果
            bool isSgin = false;
            if (sign != null && sign != "")
            {
                switch (_sign_type)
                {
                    case "MD5":
                        isSgin = AlipayMD5.Verify(preSignStr, sign, _key, _input_charset);
                        break;
                    default:
                        break;
                }
            }

            return isSgin;
        }
        /// <summary>
        /// 獲取是不是支付寶服務器發來的請求的驗證結果
        /// </summary>
        /// <param name="notify_id">通知驗證ID</param>
        /// <returns>驗證結果</returns>
        private string GetResponseTxt(string notify_id)
        {
            string veryfy_url = Https_veryfy_url + "partner=" + _partner + "&notify_id=" + notify_id;

            //獲取遠程服務器ATN結果,驗證是不是支付寶服務器發來的請求
            string responseTxt = Get_Http(veryfy_url, 120000);

            return responseTxt;
        }
        /// <summary>
        /// 獲取遠程服務器ATN結果
        /// </summary>
        /// <param name="strUrl">指定URL路徑地址</param>
        /// <param name="timeout">超時時間設置</param>
        /// <returns>服務器ATN結果</returns>
        private string Get_Http(string strUrl, int timeout)
        {
            string strResult;
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                myReq.Timeout = timeout;
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream myStream = HttpWResp.GetResponseStream();
                StreamReader sr = new StreamReader(myStream, Encoding.Default);
                StringBuilder strBuilder = new StringBuilder();
                while (-1 != sr.Peek())
                {
                    strBuilder.Append(sr.ReadLine());
                }

                strResult = strBuilder.ToString();
            }
            catch (Exception exp)
            {
                strResult = "錯誤:" + exp.Message;
            }

            return strResult;
        }
    }
}
using System.Web;
using System.Text;
using System.IO;
using System.Net;
using System;
using System.Collections.Generic;
using System.Xml;

namespace Com.Alipay
{
    public class Submit
    {
        #region 字段
        //支付寶網關地址(新)
        private static string GATEWAY_NEW = "https://mapi.alipay.com/gateway.do?";
        //商戶的私鑰
        private static string _key = "";
        //編碼格式
        private static string _input_charset = "";
        //簽名方式
        private static string _sign_type = "";
        #endregion

        static Submit()
        {
            _key = Config.Key.Trim();
            _input_charset = Config.Input_charset.Trim().ToLower();
            _sign_type = Config.Sign_type.Trim().ToUpper();
        }

        /// <summary>
        /// 生成請求時的簽名
        /// </summary>
        /// <param name="sPara">請求給支付寶的參數數組</param>
        /// <returns>簽名結果</returns>
        private static string BuildRequestMysign(Dictionary<string, string> sPara)
        {
            //把數組全部元素,按照「參數=參數值」的模式用「&」字符拼接成字符串
            string prestr = Core.CreateLinkString(sPara);
            //把最終的字符串簽名,得到簽名結果
            string mysign = "";
            switch (_sign_type)
            {
                case "MD5":
                    mysign = AlipayMD5.Sign(prestr, _key, _input_charset);
                    break;
                default:
                    mysign = "";
                    break;
            }

            return mysign;
        }

        /// <summary>
        /// 生成要請求給支付寶的參數數組
        /// </summary>
        /// <param name="sParaTemp">請求前的參數數組</param>
        /// <returns>要請求的參數數組</returns>
        private static Dictionary<string, string> BuildRequestPara(SortedDictionary<string, string> sParaTemp)
        {
            //待簽名請求參數數組
            Dictionary<string, string> sPara = new Dictionary<string, string>();
            //簽名結果
            string mysign = "";

            //過濾簽名參數數組
            sPara = Core.FilterPara(sParaTemp);

            //得到簽名結果
            mysign = BuildRequestMysign(sPara);

            //簽名結果與簽名方式加入請求提交參數組中
            sPara.Add("sign", mysign);
            sPara.Add("sign_type", _sign_type);

            return sPara;
        }

        /// <summary>
        /// 生成要請求給支付寶的參數數組
        /// </summary>
        /// <param name="sParaTemp">請求前的參數數組</param>
        /// <param name="code">字符編碼</param>
        /// <returns>要請求的參數數組字符串</returns>
        private static string BuildRequestParaToString(SortedDictionary<string, string> sParaTemp, Encoding code)
        {
            //待簽名請求參數數組
            Dictionary<string, string> sPara = new Dictionary<string, string>();
            sPara = BuildRequestPara(sParaTemp);

            //把參數組中全部元素,按照「參數=參數值」的模式用「&」字符拼接成字符串,並對參數值作urlencode
            string strRequestData = Core.CreateLinkStringUrlencode(sPara, code);

            return strRequestData;
        }

        /// <summary>
        /// 創建請求,以表單HTML形式構造(默認)
        /// </summary>
        /// <param name="sParaTemp">請求參數數組</param>
        /// <param name="strMethod">提交方式。兩個值可選:post、get</param>
        /// <param name="strButtonValue">確認按鈕顯示文字</param>
        /// <returns>提交表單HTML文本</returns>
        public static string BuildRequest(SortedDictionary<string, string> sParaTemp, string strMethod, string strButtonValue)
        {
            //待請求參數數組
            Dictionary<string, string> dicPara = new Dictionary<string, string>();
            dicPara = BuildRequestPara(sParaTemp);

            StringBuilder sbHtml = new StringBuilder();

            sbHtml.Append("<form id='alipaysubmit' name='alipaysubmit' action='" + GATEWAY_NEW + "_input_charset=" + _input_charset + "' method='" + strMethod.ToLower().Trim() + "'>");

            foreach (KeyValuePair<string, string> temp in dicPara)
            {
                sbHtml.Append("<input type='hidden' name='" + temp.Key + "' value='" + temp.Value + "'/>");
            }
            //submit按鈕控件請不要含有name屬性
            sbHtml.Append("<input type='submit' value='" + strButtonValue + "' style='display:none;'></form>");

            sbHtml.Append("<script>document.forms['alipaysubmit'].submit();</script>");

            return sbHtml.ToString();
        }
        /// <summary>
        /// 創建請求,以模擬遠程HTTP的POST請求方式構造並獲取支付寶的處理結果
        /// </summary>
        /// <param name="sParaTemp">請求參數數組</param>
        /// <returns>支付寶處理結果</returns>
        public static string BuildRequest(SortedDictionary<string, string> sParaTemp)
        {
            Encoding code = Encoding.GetEncoding(_input_charset);

            //待請求參數數組字符串
            string strRequestData = BuildRequestParaToString(sParaTemp,code);

            //把數組轉換成流中所需字節數組類型
            byte[] bytesRequestData = code.GetBytes(strRequestData);

            //構造請求地址
            string strUrl = GATEWAY_NEW + "_input_charset=" + _input_charset;

            //請求遠程HTTP
            string strResult = "";
            try
            {
                //設置HttpWebRequest基本信息
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                myReq.Method = "post";
                myReq.ContentType = "application/x-www-form-urlencoded";

                //填充POST數據
                myReq.ContentLength = bytesRequestData.Length;
                Stream requestStream = myReq.GetRequestStream();
                requestStream.Write(bytesRequestData, 0, bytesRequestData.Length);
                requestStream.Close();

                //發送POST數據請求服務器
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream myStream = HttpWResp.GetResponseStream();

                //獲取服務器返回信息
                StreamReader reader = new StreamReader(myStream, code);
                StringBuilder responseData = new StringBuilder();
                String line;
                while ((line = reader.ReadLine()) != null)
                {
                    responseData.Append(line);
                }

                //釋放
                myStream.Close();

                strResult = responseData.ToString();
            }
            catch (Exception exp)
            {
                strResult = "報錯:"+exp.Message;
            }

            return strResult;
        }
        /// <summary>
        /// 創建請求,以模擬遠程HTTP的POST請求方式構造並獲取支付寶的處理結果,帶文件上傳功能
        /// </summary>
        /// <param name="sParaTemp">請求參數數組</param>
        /// <param name="strMethod">提交方式。兩個值可選:post、get</param>
        /// <param name="fileName">文件絕對路徑</param>
        /// <param name="data">文件數據</param>
        /// <param name="contentType">文件內容類型</param>
        /// <param name="lengthFile">文件長度</param>
        /// <returns>支付寶處理結果</returns>
        public static string BuildRequest(SortedDictionary<string, string> sParaTemp, string strMethod, string fileName, byte[] data, string contentType, int lengthFile)
        {

            //待請求參數數組
            Dictionary<string, string> dicPara = new Dictionary<string, string>();
            dicPara = BuildRequestPara(sParaTemp);

            //構造請求地址
            string strUrl = GATEWAY_NEW + "_input_charset=" + _input_charset;

            //設置HttpWebRequest基本信息
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrl);
            //設置請求方式:get、post
            request.Method = strMethod;
            //設置boundaryValue
            string boundaryValue = DateTime.Now.Ticks.ToString("x");
            string boundary = "--" + boundaryValue;
            request.ContentType = "\r\nmultipart/form-data; boundary=" + boundaryValue;
            //設置KeepAlive
            request.KeepAlive = true;
            //設置請求數據,拼接成字符串
            StringBuilder sbHtml = new StringBuilder();
            foreach (KeyValuePair<string, string> key in dicPara)
            {
                sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"" + key.Key + "\"\r\n\r\n" + key.Value + "\r\n");
            }
            sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"withhold_file\"; filename=\"");
            sbHtml.Append(fileName);
            sbHtml.Append("\"\r\nContent-Type: " + contentType + "\r\n\r\n");
            string postHeader = sbHtml.ToString();
            //將請求數據字符串類型根據編碼格式轉換成字節流
            Encoding code = Encoding.GetEncoding(_input_charset);
            byte[] postHeaderBytes = code.GetBytes(postHeader);
            byte[] boundayBytes = Encoding.ASCII.GetBytes("\r\n" + boundary + "--\r\n");
            //設置長度
            long length = postHeaderBytes.Length + lengthFile + boundayBytes.Length;
            request.ContentLength = length;

            //請求遠程HTTP
            Stream requestStream = request.GetRequestStream();
            Stream myStream;
            try
            {
                //發送數據請求服務器
                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                requestStream.Write(data, 0, lengthFile);
                requestStream.Write(boundayBytes, 0, boundayBytes.Length);
                HttpWebResponse HttpWResp = (HttpWebResponse)request.GetResponse();
                myStream = HttpWResp.GetResponseStream();
            }
            catch (WebException e)
            {
                return e.ToString();
            }
            finally
            {
                if (requestStream != null)
                {
                    requestStream.Close();
                }
            }

            //讀取支付寶返回處理結果
            StreamReader reader = new StreamReader(myStream, code);
            StringBuilder responseData = new StringBuilder();

            String line;
            while ((line = reader.ReadLine()) != null)
            {
                responseData.Append(line);
            }
            myStream.Close();
            return responseData.ToString();
        }
        /// <summary>
        /// 用於防釣魚,調用接口query_timestamp來獲取時間戳的處理函數
        /// 注意:遠程解析XML出錯,與IIS服務器配置有關
        /// </summary>
        /// <returns>時間戳字符串</returns>
        public static string Query_timestamp()
        {
            string url = GATEWAY_NEW + "service=query_timestamp&partner=" + Config.Partner + "&_input_charset=" + Config.Input_charset;
            string encrypt_key = "";

            XmlTextReader Reader = new XmlTextReader(url);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Reader);

            encrypt_key = xmlDoc.SelectSingleNode("/alipay/response/timestamp/encrypt_key").InnerText;

            return encrypt_key;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace Com.Alipay
{
    /// <summary>
    /// 類名:MD5
    /// 功能:MD5加密
    /// </summary>
    public sealed class AlipayMD5
    {
        public AlipayMD5()
        {
            //
            // TODO: 在此處添加構造函數邏輯
            //
        }

        /// <summary>
        /// 簽名字符串
        /// </summary>
        /// <param name="prestr">須要簽名的字符串</param>
        /// <param name="key">密鑰</param>
        /// <param name="_input_charset">編碼格式</param>
        /// <returns>簽名結果</returns>
        public static string Sign(string prestr, string key, string _input_charset)
        {
            StringBuilder sb = new StringBuilder(32);

            prestr = prestr + key;

            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(prestr));
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }

            return sb.ToString();
        }
        /// <summary>
        /// 驗證簽名
        /// </summary>
        /// <param name="prestr">須要簽名的字符串</param>
        /// <param name="sign">簽名結果</param>
        /// <param name="key">密鑰</param>
        /// <param name="_input_charset">編碼格式</param>
        /// <returns>驗證結果</returns>
        public static bool Verify(string prestr, string sign, string key, string _input_charset)
        {
            string mysign = Sign(prestr, key, _input_charset);
            if (mysign == sign)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

下面這個就是webapi裏面的處理(簡單處理)css

using System.Collections.Generic;
using System.Web.Http;
using System;
using Com.Alipay;
using Npgsql;
using AlipayFrist.DBUtilty;
using System.Data;
//using System.ComponentModel.DataAnnotations;
using System.Xml;
using System.IO;
using System.Xml.Linq;
using AlipayFrist.Models;
using System.Linq;

namespace AlipayFrist.Controllers
{
    /// <summary>
    /// B2C單筆轉帳到帳戶的接口
    /// </summary>
    public class MyFristAlipayController : ApiController
    {
        //轉帳接口
        public object Post(alipay Alipay)
        {
            try
            {
                var sParaTemp = new SortedDictionary<string, string>();
                sParaTemp.Add("sign_type", Config.Sign_type);//簽名方式
                sParaTemp.Add("service", "alipay.fund.trans.toacc");//接口名稱
                sParaTemp.Add("partner", Config.Partner);//合做者身份ID 
                sParaTemp.Add("out_biz_no", DateTime.Now.Ticks.ToString());//商戶轉帳惟一訂單號 
                sParaTemp.Add("payer_type", "ALIPAY_USERID");//付款方帳戶類型
                sParaTemp.Add("payer_account", Config.Partner);//付款方帳戶
                sParaTemp.Add("payer_name", "");//付款方真實姓名
                sParaTemp.Add("payee_type", "ALIPAY_LOGONID");//收款方帳戶類型
                sParaTemp.Add("payee_account", Alipay.payee_account);//收款方帳戶 
                sParaTemp.Add("payee_ real_name", Alipay.payee_name);//收款方真實姓名
                sParaTemp.Add("_input_charset", Config.Input_charset.ToLower());//編碼
                sParaTemp.Add("amount", Alipay.amount.ToString());//轉帳金額 
                sParaTemp.Add("memo", Alipay.memo);//轉帳備註 
                //創建請求  
                var aa = Submit.BuildRequest(sParaTemp);
                try
                {
                    var xmldoc = new XmlDocument();
                    xmldoc.LoadXml(aa);
                    //xmldoc.Load(new System.IO.MemoryStream(System.Text.Encoding.GetEncoding("utf-8").GetBytes(aa)));//獲取xml文件
                    var Nodes = xmldoc.SelectSingleNode("alipay");
                    var is_successNode = Nodes.SelectSingleNode("is_success");
                    var is_success = is_successNode.InnerXml;//is_success 的值
                    var paramNodes = Nodes.SelectSingleNode("request").ChildNodes;//全部的param節點
                    var sign = "";
                    for (int i = 0; i < paramNodes.Count; i++)
                    {
                        //判斷是name是否爲sign
                        if (paramNodes[i].Attributes["name"].Value == "sign")
                        {
                            sign = paramNodes[i].InnerXml;
                        }
                    }
                    var result_code = Nodes.SelectSingleNode("response").SelectSingleNode("alipay").SelectSingleNode("result_code").InnerXml;
                    var sign_type = Nodes.SelectSingleNode("sign_type").InnerXml;
                    if (is_success == "T")
                    {
                        var dbhelper = new PostgreHelper();
                        var sql = @"INSERT INTO alipay(out_biz_no,payer_type,payer_account,payer_name,payee_type,payee_account,payee_name,amount,memo,CreateDate,TypeResult_code) VALUES(@out_biz_no,@payer_type,@payer_account,@payer_name,@payee_type,@payee_account,@payee_name,@amount,@memo,@CreateDate,@TypeResult_code)";
                        var para = new[]{
                            new NpgsqlParameter("@out_biz_no",DateTime.Now.Ticks.ToString()),
                            new NpgsqlParameter("@payer_type","ALIPAY_USERID"),
                            new NpgsqlParameter("@payer_account",Config.Partner),
                            new NpgsqlParameter("@payer_name",""),
                            new NpgsqlParameter("@payee_type","ALIPAY_LOGONID"),
                            new NpgsqlParameter("@payee_account",Alipay.payee_account),
                            new NpgsqlParameter("@payee_name",Alipay.payee_name),
                            new NpgsqlParameter("@amount",decimal.Parse(Alipay.amount.ToString())),
                            new NpgsqlParameter("@memo",Alipay.memo.ToString()),
                            new NpgsqlParameter("@CreateDate",DateTime.Now.ToString()),
                            new NpgsqlParameter("@TypeResult_code",result_code.ToString())
                         };
                        dbhelper.ExecuteNonQuery(ConnectionString.DB, CommandType.Text, sql, para);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                return new { Result = true, Message = "轉帳成功!" };
            }
            catch (Exception)
            {
                return new { Result = false, Message = "轉帳失敗!" };
            }
        }
       

}

前臺頁面調用html

@{
    ViewBag.Title = "Frist";
}

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
</head>
<body>

    <form id="form1" action="/Api/MyFristAlipay" method="post">

        <div class="form-group">
            <label for="name">付款人支付寶帳號:</label>
            <input type="text" class="form-control" disabled="disabled" value="123456789">
        </div>
        <div class="form-group">
            <label for="name">付款人姓名:</label>
            <input type="text" class="form-control" disabled="disabled" value="" name="CompanyName" id="CompanyName" />
        </div>
        <div class="form-group">
            <label for="name">收款人支付寶帳號:</label>
            <input type="text" name="payee_account" id="PayeeAlipayNumber" class="form-control" />
        </div>
        <div class="form-group">
            <label for="name">收款人姓名:</label>
            <input type="text" class="form-control" name="payee_name" id="PayeeAlipayName">
        </div>
        <div class="form-group">
            <label for="name">支付金額:</label>
            <input type="text" class="form-control" name="amount" id="AlipayNameAmount">
        </div>
        <div class="form-group">
            <label for="name">備註:</label>
            <input type="text" class="form-control" name="memo" id="Remark">
        </div>
        <div>
            @*<button type="submit" class="btn btn-primary" data-button="alipay_submit">
                    提  交
                </button>*@
            <button type="button" class="btn btn-primary" data-button="alipay_submit" onclick="test()">
                提  交
            </button>
        </div>
    </form>
    <div id="test_div">
    </div>
</body>
</html>
<script type="text/javascript">
    function test() {
        debugger;
        $.post($('#form1').attr("action"), $('#form1').serialize(), function (dt) {
           // $("#test_div").html(dt);
            if (dt.Result) {
                alert(dt.Message);
                window.location.href = "Home/Index";
            }
            else {
                alert(dt.Message);
            }
        })
    }
    //$(document).ready(function () {
    //    $(document).on("click", "[data-button=alipay_submit]", function () {
    //        debugger;
    //        var Alipay = {};
    //        Alipay.payee_account = $("#PayeeAlipayNumber").val();//收款人支付寶帳號
    //        Alipay.payee_real_name = $("#PayeeAlipayName").val();//收款人姓名
    //        Alipay.memo = $("#Remark").val();//備註
    //        Alipay.amount = $("#AlipayNameAmount").val();//支付金額
    //        $.post("Api/MyFristAlipay", Alipay, function (data) {
    //            if (data)
    //            {
    //                alert("轉帳成功");
    //            }
    //        })
    //        //$.ajax({
    //        //    type: "get",
    //        //    url: "Api/MyFristAlipay",
    //        //    data: Alipay,
    //        //    success: function (data) {
    //        //        if (data) {
    //        //            alert('轉帳成功');
    //        //        }
    //        //    },
    //        //    error: function () {
    //        //        alert('轉帳失敗');
    //        //    }
    //        //})
    //    })
    //})
</script>
相關文章
相關標籤/搜索