码迷,mamicode.com
首页 > 其他好文 > 详细

调用支付宝转账接口(单笔)

时间:2016-09-04 19:17:15      阅读:1429      评论:0      收藏:0      [点我收藏+]

标签:

下面这几个类都是支付宝demo里面的,直接拿过来用就可以

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里面的处理(简单处理)

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 = "转账失败!" };
            }
        }
       

}

前台页面调用

@{
    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>

 

调用支付宝转账接口(单笔)

标签:

原文地址:http://www.cnblogs.com/hbh123/p/5839828.html

(1)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!