C#调用支付宝接口案例

C#调用支付宝接口案例

        /// <summary>
        /// 页面跳转同步通知页面
        /// </summary>
        /// <returns></returns>
        public ActionResult PayResult()
        {
            SortedDictionary<string, string> sPara = GetRequestGet();
            T_Trade objTrade = null;
            if (sPara.Count > 0)//判断是否有带返回参数
            {
                Notify aliNotify = new Notify();
                bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]);
                if (verifyResult)//验证成功
                {
                    //商户订单号
                    string out_trade_no = Request.QueryString["out_trade_no"];

                    //支付宝交易号
                    string trade_no = Request.QueryString["trade_no"];

                    //交易状态
                    string trade_status = Request.QueryString["trade_status"];

                    //验证订单状态并处理业务逻辑
                    VerifyPay(out_trade_no, trade_no, trade_status);
                    var db = DBHelper.QueryDB();
                    string strSql = string.Format(@"select * from T_Trade where ID='{0}'", out_trade_no);
                    objTrade = db.Sql(strSql).QuerySingle<T_Trade>();
                    strSql = string.Format(@"select UserName from T_User where ID={0}", objTrade.UserID);
                    ViewBag.UserName = db.Sql(strSql).QuerySingle<string>();
                }
            }
            return View(objTrade);
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
 ///    <summary>
        /// 服务器异步通知页面
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult PayNotify()
        {
            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"];

                    //验证订单状态并处理业务逻辑
                    VerifyPay(out_trade_no, trade_no, trade_status);

                    Response.Write("success");  //请不要修改或删除
                }
                else//验证失败
                {
                    Response.Write("fail");
                }
            }
            else
            {
                Response.Write("无通知参数");
            }
            return View();
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
        public bool VerifyPay(string strOutTradeNo, string strTradeNo, string strTradeStatus)
        {
            bool bRes = false;
            string strSql = string.Format(@"select * from T_Trade where ID='{0}'", strOutTradeNo);
            T_Trade objTrade = DBHelper.QueryDB().Sql(strSql).QuerySingle<T_Trade>();
            if (strTradeStatus == "TRADE_FINISHED" || strTradeStatus == "TRADE_SUCCESS")
            {
                if (objTrade.State != 2)
                {
                    objTrade.TradeNo = strTradeNo;
                    objTrade.FinishTime = DateTime.Now;
                    objTrade.State = 2;
                    doPay(objTrade);
                }
                bRes = true;
            }
            else if (strTradeStatus == "TRADE_CLOSED")
            {
                if (objTrade.State != 1)
                {
                    objTrade.TradeNo = strTradeNo;
                    objTrade.FinishTime = DateTime.Now;
                    objTrade.State = 1;
                    doPay(objTrade);
                }
                bRes = false;
            }
            return bRes;
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
        /// <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;
        }

        /// <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;
        }       
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
        /// <summary>
        /// 提交支付请求到支付宝
        /// </summary>
        public ActionResult PostToAlipay(int id)
        {
            int uid = id;

            var db = DBHelper.QueryDB();
            string strSql = string.Format(@"select count(ID) from T_Trade where UserID={0} and State=2", uid);
            //如果已经支付过则跳转到首页
            if (db.Sql(strSql).QuerySingle<int>() > 0)
            {
                return Redirect("/home");
            }
            //查找没有支付的订单
            strSql = string.Format(@"select * from T_Trade where UserID={0} and State=0", uid);
            var objTrade = db.Sql(strSql).QuerySingle<T_Trade>();

            //支付类型,1为商品购买
            string payment_type = "1";

            //服务器异步通知页面路径,需http://格式的完整路径,不能加?id=123这类自定义参数
            string notify_url = "http://zc.jcxt99.com/pay/paynotify";
            //string notify_url = "http://192.168.1.33:39371/pay/paynotify";

            //页面跳转同步通知页面路径,需http://格式的完整路径,不能加?id=123这类自定义参数,不能写成http://localhost/
            string return_url = "http://zc.jcxt99.com/pay/payresult";
            //string return_url = "http://192.168.1.33:39371/pay/payresult";

            //商户订单号,商户网站订单系统中唯一订单号,必填
            string out_trade_no = objTrade == null ? Guid.NewGuid().ToString("N").Trim() : objTrade.ID;

            //订单名称,必填
            string subject = "会员资格";

            //付款金额,必填
            string total_fee = "200.00";
            //string total_fee = "0.01";

            string it_b_pay = "30m";

            //防钓鱼时间戳,若要使用请调用类文件submit中的query_timestamp函数
            //string anti_phishing_key = Com.Alipay.Submit.Query_timestamp();

            //客户端的IP地址,非局域网的外网IP地址,如:221.0.0.1
            //string exter_invoke_ip = "";

            //把请求参数打包成数组
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("partner", Config.Partner);
            sParaTemp.Add("seller_email", Config.Seller_email);
            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("out_trade_no", out_trade_no);
            sParaTemp.Add("subject", subject);
            sParaTemp.Add("total_fee", total_fee);
            sParaTemp.Add("it_b_pay", it_b_pay);
            //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", "确认");
            if (objTrade == null)
            {
                objTrade = new T_Trade();
                objTrade.ID = out_trade_no;
                objTrade.UserID = uid;
                objTrade.TradeTime = DateTime.Now;
                objTrade.Value = total_fee;
                objTrade.TradeNo = "";
                objTrade.FinishTime = DateTime.Now;
                objTrade.State = 0;
                if (db.Insert<T_Trade>("T_Trade", objTrade).AutoMap().Execute() > 0)
                {
                    Response.Write(sHtmlText);
                }
                else
                {
                    return Content("生成订单失败,请刷新页面重试!");
                }
            }
            else
            {
                Response.Write(sHtmlText);
            }
            return null;
        }
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
trade_create_by_buyer-CSHARP-UTF-8 │ ├app_code ┈┈┈┈┈┈┈┈┈┈类文件夹 │ │ │ ├AlipayConfig.cs┈┈┈┈┈基础配置类文件 │ │ │ ├AlipayCore.cs┈┈┈┈┈┈支付宝接口公用函数类文件 │ │ │ ├AlipayNotify.cs┈┈┈┈┈支付宝通知处理类文件 │ │ │ ├AlipaySubmit.cs┈┈┈┈┈支付宝接口请求提交类文件 │ │ │ └MD5.cs ┈┈┈┈┈┈┈┈┈MD5类库 │ ├log┈┈┈┈┈┈┈┈┈┈┈┈┈日志文件夹 │ ├default.aspx ┈┈┈┈┈┈┈┈支付宝接口入口文件 ├default.aspx.cs┈┈┈┈┈┈┈支付宝接口入口文件 │ ├notify_url.aspx┈┈┈┈┈┈┈服务器异步通知页面文件 ├notify_url.aspx.cs ┈┈┈┈┈服务器异步通知页面文件 │ ├return_url.aspx┈┈┈┈┈┈┈页面跳转同步通知文件 ├return_url.aspx.cs ┈┈┈┈┈页面跳转同步通知文件 │ ├Web.Config ┈┈┈┈┈┈┈┈┈配置文件(集成时删除) │ └readme.txt ┈┈┈┈┈┈┈┈┈使用说明文本 ※注意※ 需要配置的文件是: alipay_config.cs default.aspx default.aspx.csreturn_url.aspx return_url.aspx.cs notify_url.aspx notify_url.aspx.cs统一命名空间为:namespace Com.Alipiay ───────── 类文件函数结构 ───────── AlipayCore.cs public static Dictionary<string, string> ParaFilter(SortedDictionary<string, string> dicArrayPre) 功能:除去数组中的空值和签名参数并以字母a到z的顺序排序 输入:SortedDictionary<string, string> dicArrayPre 过滤前的参数组 输出:Dictionary<string, string> 去掉空值与签名参数后的新签名参数组 public static string CreateLinkString(Dictionary<string, string> dicArray) 功能:把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 输入:Dictionary<string, string> dicArray 需要拼接的数组 输出:string 拼接完成以后的字符串 public static string CreateLinkStringUrlencode(Dictionary<string, string> dicArray, Encoding code) 功能:把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,并对参数值做urlencode 输入:Dictionary<string, string> dicArray 需要拼接的数组 Encoding code 字符编码 输出:string 拼接完成以后的字符串 public static void log_result(string sPath, string sWord) 功能:写日志,方便测试(看网站需求,也可以改成存入数据库) 输入:string sPath 日志的本地绝对路径 string sWord 要写入日志里的文本内容 public static string GetAbstractToMD5(Stream sFile) 功能:获取文件的md5摘要 输入:Stream sFile 文件流 输出:string MD5摘要结果 public static string GetAbstractToMD5(byte[] dataFile) 功能:获取文件的md5摘要 输入:byte[] dataFile 文件流 输出:string MD5摘要结果 ┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉ MD5.cs public static string Sign(string prestr, string key, string _input_charset) 功能:签名字符串 输入:string prestr 需要签名的字符串 string key 密钥 string _input_charset 编码格式 输出:string 签名结果 public static bool Verify(string prestr, string sign, string key, string _input_charset) 功能:验证签名 输入:string prestr 需要签名的字符串 string sign 签名结果 string key 密钥 string _input_charset 编码格式 输出:string 验证结果 ┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉ AlipayNotify.cs public Notify() 功能:构造函数 从配置文件中初始化变量 public bool Verify(SortedDictionary<string, string> inputPara, string notify_id, string sign) 功能:验证消息是否是支付宝发出的合法消息 输入:SortedDictionary<string, string> inputPara 通知返回参数数组 string notify_id 通知验证ID string sign 支付宝生成的签名结果 输出:bool 验证结果 private string GetPreSignStr(SortedDictionary<string, string> inputPara) 功能:获取待签名字符串(调试用) 输入:SortedDictionary<string, string> inputPara 通知返回参数数组 输出:string 待签名字符串 private bool GetSignVeryfy(SortedDictionary<string, string> inputPara, string sign) 功能:获取返回回来的待签名数组签名后结果 输入:SortedDictionary<string, string> inputPara 通知返回参数数组 string sign 支付宝生成的签名结果 输出:bool 签名验证结果 private string GetResponseTxt(string notify_id) 功能:获取是否是支付宝服务器发来的请求的验证结果 输入:string notify_id 通知验证ID 输出:string 验证结果 private string Get_Http(string strUrl, int timeout) 功能:获取远程服务器ATN结果 输入:string strUrl 指定URL路径地址 int timeout 超时时间设置 输出:string 服务器ATN结果字符串 ┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉ AlipaySubmit.cs private static string BuildRequestMysign(Dictionary<string, string> sPara) 功能:生成签名结果 输入:Dictionary<string, string> sPara 要签名的数组 输出:string 签名结果字符串 private static Dictionary<string, string> BuildRequestPara(SortedDictionary<string, string> sParaTemp) 功能:生成要请求给支付宝的参数数组 输入:SortedDictionary<string, string> sParaTemp 请求前的参数数组 输出:Dictionary<string, string> 要请求的参数数组 private static string BuildRequestParaToString(SortedDictionary<string, string> sParaTemp, Encoding code) 功能:生成要请求给支付宝的参数数组 输入:SortedDictionary<string, string> sParaTemp 请求前的参数数组 Encoding code 字符编码 输出:string 要请求的参数数组字符串 public static string BuildRequest(SortedDictionary<string, string> sParaTemp, string strMethod, string strButtonValue) 功能:建立请求,以表单HTML形式构造(默认) 输入:SortedDictionary<string, string> sParaTemp 请求参数数组 string strMethod 提交方式。两个值可选:post、get string strButtonValue 确认按钮显示文字 输出:string 提交表单HTML文本 public static string BuildRequest(SortedDictionary<string, string> sParaTemp) 功能:建立请求,以模拟远程HTTP的POST请求方式构造并获取支付宝的处理结果 输入:SortedDictionary<string, string> sParaTemp 请求参数数组 输出:string 支付宝处理结果 public static string BuildRequest(SortedDictionary<string, string> sParaTemp, string strMethod, string fileName, byte[] data, string contentType, int lengthFile) 功能:建立请求,以模拟远程HTTP的POST请求方式构造并获取支付宝的处理结果 输入:SortedDictionary<string, string> sParaTemp 请求参数数组 string strMethod 提交方式。两个值可选:post、get string fileName 文件绝对路径 byte[] data 文件数据 string contentType 文件内容类型 int lengthFile 文件长度 输出:string 支付宝处理结果 public static string Query_timestamp() 功能:用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数 输出:string 时间戳字符串 ────────── 出现问题,求助方法 ────────── 如果在集成支付宝接口时,有疑问或出现问题,可使用下面的链接,提交申请。 https://b.alipay.com/support/helperApply.htm?action=supportHome 我们会有专门的技术支持人员为您处理
接口特点: 1.同时提供银行卡在线支付、声讯电话支付、互联星空支付、手机短信注册、腾讯财付通、 腾讯Q币、神州行充值卡、盛大游戏点卡、支付宝、手机银行、北京宽带支付、联通充值卡 等支付途径。 2.银行卡在线支付支持国内60 余种银行卡(信用卡、储蓄卡、借记卡等)在线支付。 3.全国声讯电话支付支持全国所有省份固定电话、小灵通、中国移动、中国联通手机, 开通移动、联通、电信、网通多个声讯热线号码。 4.中国电信互联星空支付支持直接用163或ADSL上网帐号、各省互联星空网站注册用户支付。 5.支持中国移动、中国联通、中国电信小灵通手机用户发送短信点播赠送服务。 6.开放腾讯公司Q币和财付通支付接口。 7.支持50元、100元、300元、500元等多种面值的移动神州行和联通充值卡支付。 8.各支付途径可任意选择开启或关闭。 9.真正傻瓜式支付接口,提供示例程序,只需简单设置即可使用。 10.设置商户密钥,支付信息加密传递,加强支付安全性,加密系统与其他支付平台兼容。 11.贺喜支付平台(http://www.168reg.cn)提供完善的后台管理系统,提供定单管理、定单 统计、财务管理、用户资料修改、商户密钥设置、推荐用户及技术支持等功能。 12.提交支付信息时可设置服务名称、商户订单号和两个自定义字段,支付成功后实时将支 付结果返回商户网站。 13.提供接口的测试模式,方便商户快捷地开发支付接口程序。 14.您可以登录后台管理系统查看定单以下信息:定单号、用户支付金额、商户所得金额、 自定义订单号、支付日期、结帐信息等。 15.提供定单后台通知系统,彻底解决用户端返回造成的挂单、掉单现象。 16.提供宣传推广代码,推荐其他商户加盟可获得其收入的一定比例分成。 17.开放收费制商户,为商户降低支付成本。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值