1.需要提供签约账号、商户密钥2.代码实现:
⽀付接⼝(即时到账交易):1>调⽤⽀付宝⽀付⽹关
///
/// private void AlipayTradePCPayment(订单实体 order) {
if (order == null) {
return; }
Log.Info(this.GetType().ToString(), \"AlipayTradePCPayment Start......\"); string responseText = string.Empty; try {
#region 调⽤⽀付宝⽀付接⼝
string partner = \"签约账号\";
string sign_type = \"MD5\";//签名⽅式:MD5、RSA、DSA string key = \"MD5密钥\";//商户密钥
string input_charset = \"utf-8\";//字符编码格式 ⽬前⽀持 gbk 或 utf-8
//把请求参数打包成数组
SortedDictionary sParaTemp.Add(\"service\", \"create_direct_pay_by_user\");//调⽤的接⼝名,⽆需修改 sParaTemp.Add(\"partner\", partner);//签约账号 sParaTemp.Add(\"seller_id\", \"\");//收款⽀付宝账号 sParaTemp.Add(\"_input_charset\", input_charset.ToLower());//字符编码格式 ⽬前⽀持 gbk 或 utf-8 sParaTemp.Add(\"payment_type\", \"1\");//⽀付类型,⽆需修改 sParaTemp.Add(\"notify_url\", \"http://XXXXXXXX/AliPayment/PaymentNotify\");//服务器异步通知页⾯路径 sParaTemp.Add(\"return_url\", \"http://XXXXXXXX/AliPayment/PaymentReturn\");//页⾯跳转同步通知页⾯路径 sParaTemp.Add(\"anti_phishing_key\", \"\");//防钓鱼时间戳 sParaTemp.Add(\"exter_invoke_ip\", \"\");//客户端的IP地址 sParaTemp.Add(\"out_trade_no\", \"\");//商户订单号,商户⽹站订单系统中唯⼀订单号,必填 sParaTemp.Add(\"subject\", \"\");//订单名称,必填 sParaTemp.Add(\"total_fee\", \"\");//付款⾦额,必填 单位为RMB-Yuan。取值范围为[0.01,100000000.00],精确到⼩数点后两位。 sParaTemp.Add(\"body\", \"\");//商品描述,可空 //建⽴请求 Submit submit = new Submit(partner, key, input_charset, sign_type); responseText = submit.BuildRequest(sParaTemp, \"get\", \"确认\"); #endregion _httpContext.Response.Clear(); _httpContext.Response.Write(responseText.ToString()); _httpContext.Response.End(); } catch (Exception ex) { Log.Error(this.GetType().ToString(), \"Exception: \" + ex.Message); } Log.Info(this.GetType().ToString(), \"AlipayTradePCPayment End......\"); _logger.Track(string.Format(\"⽀付宝PC⽹站⽀付跟踪信息。GetForm:{0}\", responseText), FoxconnConsts.APPSETTING_KEY_TRACK_INTERFACE); } View Code验签、建⽴请求类 /// /// 功能:⽀付宝各接⼝请求提交类 /// 详细:构造⽀付宝各接⼝表单HTML⽂本,获取远程HTTP数据 /// 版本:3.3 /// 修改⽇期:2011-07-05 /// 说明: /// 以下代码只是为了⽅便商户测试⽽提供的样例代码,商户可以根据⾃⼰⽹站的需要,按照技术⽂档编写,并⾮⼀定要使⽤该代码。 /// 该代码仅供学习和研究⽀付宝接⼝使⽤,只是提供⼀个参考 /// #region 字段 //⽀付宝⽹关地址(新) private static string GATEWAY_NEW = \"https://mapi.alipay.com/gateway.do?\"; //合作⾝份者ID,签约账号,以2088开头由16位纯数字组成的字符串,查看地址:https://b.alipay.com/order/pidAndKey.htm private static string _partner = \"\"; //商户的私钥 private static string _key = \"\"; //编码格式 private static string _input_charset = \"\"; //签名⽅式 private static string _sign_type = \"\"; #endregion public Submit(string partner, string key, string input_charset, string sign_type) { _partner = partner; _key = key; _input_charset = input_charset.ToLower(); _sign_type = sign_type.ToUpper(); } /// /// ⽣成请求时的签名 /// /// 请求给⽀付宝的参数数组 /// private string BuildRequestMysign(Dictionary //把数组所有元素,按照“参数=参数值”的模式⽤“&”字符拼接成字符串 string prestr = Core.CreateLinkString(sPara); //把最终的字符串签名,获得签名结果 string mysign = \"\"; switch (_sign_type) { case \"MD5\": mysign = AlipayMD5.Sign(prestr, _key, _input_charset); break; case \"RSA\": mysign = RSAFromPkcs8.sign(prestr, _key, _input_charset); break; default: mysign = \"\"; break; } return mysign; } /// /// ⽣成要请求给⽀付宝的参数数组 /// /// 请求前的参数数组 /// private Dictionary //待签名请求参数数组 Dictionary string mysign = \"\"; //过滤签名参数数组 sPara = Core.FilterPara(sParaTemp); //获得签名结果 mysign = BuildRequestMysign(sPara); //签名结果与签名⽅式加⼊请求提交参数组中 sPara.Add(\"sign\", mysign); sPara.Add(\"sign_type\", _sign_type); return sPara; } /// /// ⽣成要请求给⽀付宝的参数数组 /// /// 请求前的参数数组 /// 字符编码 /// private string BuildRequestParaToString(SortedDictionary //待签名请求参数数组 Dictionary //把参数组中所有元素,按照“参数=参数值”的模式⽤“&”字符拼接成字符串,并对参数值做urlencode string strRequestData = Core.CreateLinkStringUrlencode(sPara, code); return strRequestData; } /// /// 建⽴请求,以表单HTML形式构造(默认) /// /// 请求参数数组 /// 提交⽅式。两个值可选:post、get /// 确认按钮显⽰⽂字 /// public string BuildRequest(SortedDictionary //待请求参数数组 Dictionary sbHtml.Append(\" /// /// 建⽴请求,以模拟远程HTTP的POST请求⽅式构造并获取⽀付宝的处理结果 /// /// 请求参数数组 /// public string BuildRequest(SortedDictionary 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; } /// /// ⽤于防钓鱼,调⽤接⼝query_timestamp来获取时间戳的处理函数 /// 注意:远程解析XML出错,与IIS服务器配置有关 /// /// string url = GATEWAY_NEW + \"service=query_timestamp&partner=\" + _partner + \"&_input_charset=\" + _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; } } View Code 2>接收⽀付宝同步通知(get) /// /// ⽀付宝⽀付同步通知 /// /// public ActionResult PaymentReturn() { string result = string.Empty; Log.Info(this.GetType().ToString(), \"PaymentReturn End......\"); try { SortedDictionary bool verifyResult = 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\"]; if (Request.QueryString[\"trade_status\"] == \"TRADE_FINISHED\" || Request.QueryString[\"trade_status\"] == \"TRADE_SUCCESS\") { //判断该笔订单是否在商户⽹站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户⽹站的订单系统中查到该笔订单的详细,并执⾏商户的业务程序 //如果有做过处理,不执⾏商户的业务程序 } else { result = \"trade_status=\" + Request.QueryString[\"trade_status\"]; } //打印页⾯ result = \"验证成功\"; } else//验证失败 { result = \"验证失败\"; } } else { result = \"⽆返回参数\"; } Log.Info(this.GetType().ToString(), \"result:\" + result); } catch (Exception ex) { Log.Info(this.GetType().ToString(), \"Exception:\" + ex.Message); _logger.Track(string.Format(\"⽀付宝⽀付同步通知跟踪信息。结果:{0}\", ex.Message), FoxconnConsts.APPSETTING_KEY_TRACK_INTERFACE); } Log.Info(this.GetType().ToString(), \"PaymentReturn End......\"); return Redirect(Url.RouteUrl(\"CustomerOrders\")); } View Code /// /// 获取⽀付宝GET过来通知消息,并以“参数名=参数值”的形式组成数组 /// /// int i = 0; SortedDictionary //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; } View Code ⽀付宝通知处理类 /// /// 功能:⽀付宝通知处理类 /// 详细:处理⽀付宝各接⼝通知返回 /// 版本:3.3 /// 修改⽇期:2011-07-05 /// '说明: /// 以下代码只是为了⽅便商户测试⽽提供的样例代码,商户可以根据⾃⼰⽹站的需要,按照技术⽂档编写,并⾮⼀定要使⽤该代码。 /// 该代码仅供学习和研究⽀付宝接⼝使⽤,只是提供⼀个参考。 /// /// //////////////////////注意///////////////////////////// /// 调试通知返回时,可查看或改写log⽇志的写⼊TXT⾥的数据,来检查通知返回是否正常 /// #region 字段 private string _partner = \"\"; //合作⾝份者ID private string _key = \"\"; //MD5:商户的私钥 RSA:⽀付宝的公钥 private string _input_charset = \"\"; //编码格式 private string _sign_type = \"\"; //签名⽅式 //⽀付宝消息验证地址 private string Https_veryfy_url = \"https://mapi.alipay.com/gateway.do?service=notify_verify&\"; #endregion /// /// 从配置⽂件中初始化变量 /// /// 通知返回参数数组 /// 通知验证ID public Notify(string partner, string key, string input_charset, string sign_type) { //初始化基础配置信息 _partner = partner.Trim(); _key = key.Trim(); _input_charset = input_charset.Trim().ToLower(); _sign_type = sign_type.Trim().ToUpper(); } /// /// 从⽂件读取公钥转公钥字符串 /// /// 公钥⽂件路径 public static string getPublicKeyStr(string Path) { StreamReader sr = new StreamReader(Path); string pubkey = sr.ReadToEnd(); sr.Close(); if (pubkey != null) { pubkey = pubkey.Replace(\"-----BEGIN PUBLIC KEY-----\", \"\"); pubkey = pubkey.Replace(\"-----END PUBLIC KEY-----\", \"\"); pubkey = pubkey.Replace(\"\\r\", \"\"); pubkey = pubkey.Replace(\"\\n\", \"\"); } return pubkey; } /// /// 验证消息是否是⽀付宝发出的合法消息 /// /// 通知返回参数数组 /// 通知验证ID /// ⽀付宝⽣成的签名结果 /// public bool Verify(SortedDictionary //获取返回时的签名验证结果 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; } } /// /// 获取待签名字符串(调试⽤) /// /// 通知返回参数数组 /// private string GetPreSignStr(SortedDictionary Dictionary //获取待签名字符串 string preSignStr = Core.CreateLinkString(sPara); return preSignStr; } /// /// 获取返回时的签名验证结果 /// /// 通知返回参数数组 /// 对⽐的签名结果 /// private bool GetSignVeryfy(SortedDictionary Dictionary //获取待签名字符串 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; case \"RSA\": isSgin = RSAFromPkcs8.verify(preSignStr, sign, _key, _input_charset); break; default: break; } } return isSgin; } /// /// 获取是否是⽀付宝服务器发来的请求的验证结果 /// /// 通知验证ID /// private string GetResponseTxt(string notify_id) { string veryfy_url = Https_veryfy_url + \"partner=\" + _partner + \"¬ify_id=\" + notify_id; //获取远程服务器ATN结果,验证是否是⽀付宝服务器发来的请求 string responseTxt = Get_Http(veryfy_url, 120000); return responseTxt; } /// /// 获取远程服务器ATN结果 /// /// 指定URL路径地址 /// 超时时间设置 /// 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; } } View Code 3>接收⽀付宝异步通知(post) /// /// ⽀付宝⽀付异步通知 /// /// public ActionResult PaymentNotify() { string result = string.Empty; try { Log.Info(this.GetType().ToString(), \"PaymentNotify Start......\"); SortedDictionary bool verifyResult = Verify(sPara, Request.Form[\"notify_id\"], Request.Form[\"sign\"]); Log.Debug(this.GetType().ToString(), \"verifyResult:\" + verifyResult); 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 (string.IsNullOrEmpty(out_trade_no)) { throw new Exception(\"商户订单号不能为空\"); } Log.Debug(this.GetType().ToString(), string.Format(\"out_trade_no:【{0}】-trade_no:【{1}】-trade_status:【{2}】\", out_trade_no, trade_no, trade_status)); if (trade_status == \"TRADE_FINISHED\") { //判断该笔订单是否在商户⽹站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户⽹站的订单系统中查到该笔订单的详细,并执⾏商户的业务程序 //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为⼀致的 //如果有做过处理,不执⾏商户的业务程序 //处理业务逻辑 //_orderProcessingService.BathMarkOrderAsPaid(out_trade_no); //注意: //退款⽇期超过可退款期限后(如三个⽉可退款),⽀付宝系统发送该交易状态通知 } else if (trade_status == \"TRADE_SUCCESS\") { //判断该笔订单是否在商户⽹站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户⽹站的订单系统中查到该笔订单的详细,并执⾏商户的业务程序 //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为⼀致的 //如果有做过处理,不执⾏商户的业务程序 //处理业务逻辑 Log.Info(this.GetType().ToString(), \"订单状态更新成功\"); //注意: //付款完成后,⽀付宝系统发送该交易状态通知 } else { } //——请根据您的业务逻辑来编写程序(以上代码仅作参考)—— Response.Write(\"success\"); //请不要修改或删除 ///////////////////////////////////////////////////////////////////////////////////////////////////////////// } else//验证失败 { Response.Write(\"fail\"); } } else { Response.Write(\"⽆通知参数\"); Log.Info(this.GetType().ToString(), \"result:⽆通知参数\"); } } catch (Exception ex) { Response.Write(\"fail\"); Log.Info(this.GetType().ToString(), \"Exception:\" + ex.Message); _logger.Track(string.Format(\"⽀付宝⽀付异步通知跟踪信息。结果:{0}\", ex.Message), FoxconnConsts.APPSETTING_KEY_TRACK_INTERFACE); } Response.End(); Log.Info(this.GetType().ToString(), \"PaymentNotify End......\"); return Content(\"fail\"); } View Code /// /// 获取⽀付宝POST过来通知消息,并以“参数名=参数值”的形式组成数组 /// /// int i = 0; SortedDictionary //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; } View Code 退款接⼝(即时到账有密退款接⼝):1>调⽤⽀付宝⽀付⽹关 /// /// /// /// private bool AlipayTradePCRefund(退款实体 refundModel) { var result = false; if (refundModel == null) { Log.Error(this.GetType().ToString(), \"退款数据不能为空\"); return result; } string responseText = string.Empty; try { #region 调⽤⽀付宝退款接⼝ string partner = \"签约账号\"; string sign_type = \"MD5\";//签名⽅式:MD5、RSA、DSA string key = \"MD5密钥\";//商户密钥 string input_charset = \"utf-8\";//字符编码格式 ⽬前⽀持 gbk 或 utf-8 //服务器异步通知页⾯路径 string notify_url = \"http://XXXXXXXX/AliPayment/RefundNotify\"; Log.Debug(this.GetType().ToString(), \"notify_url:\" + notify_url); //退款当天⽇期 string refund_date = DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss\"); //必填,格式:年[4位]-⽉[2位]-⽇[2位] ⼩时[2位 24⼩时制]:分[2位]:秒[2位],如:2007-10-01 13:13:13 //批次号 string batch_no = DateTime.UtcNow.ToString(\"yyyyMMdd\") + refundModel.RefundNumber;//? //必填,格式:当天⽇期[8位]+序列号[3⾄24位],如:201008010000001 Log.Debug(this.GetType().ToString(), \"batch_no:\" + batch_no); //退款笔数 string batch_num = \"1\"; //必填,参数detail_data的值中,“#”字符出现的数量加1,最⼤⽀持1000笔(即“#”字符出现的数量999个) //退款详细数据 string detail_data = \"\"; //必填,具体格式请参见接⼝技术⽂档 StringBuilder sb = new StringBuilder(); Log.Debug(this.GetType().ToString(), \"batch_num:\" + batch_num); foreach (var item in 集合) { sb.AppendFormat(\"{0}^{1}^{2}#\", \"交易号\", \"退款⾦额\", \"退款原因\"); } if (sb.Length > 0) { detail_data = sb.ToString().Substring(0, sb.ToString().Length - 1); } Log.Debug(this.GetType().ToString(), \"detail_data:\" + detail_data); //把请求参数打包成数组 SortedDictionary sParaTemp.Add(\"_input_charset\", _alipayPaymentSettings.InputCharset.ToLower());//字符编码格式 ⽬前⽀持 gbk 或 utf-8 sParaTemp.Add(\"notify_url\", notify_url);//服务器异步通知页⾯路径 sParaTemp.Add(\"seller_user_id\", _alipayPaymentSettings.SellerId);//收款⽀付宝账号 sParaTemp.Add(\"refund_date\", refund_date);//退款⽇期 sParaTemp.Add(\"batch_no\", batch_no);//批次号 sParaTemp.Add(\"batch_num\", batch_num);//退款笔数 sParaTemp.Add(\"detail_data\", detail_data);//退款详细数据 //建⽴请求 Submit submit = new Submit(partner, key, input_charset, sign_type); responseText = submit.BuildRequest(sParaTemp, \"get\", \"确认\"); #endregion _httpContext.Response.Clear(); _httpContext.Response.Write(responseText); _httpContext.Response.End(); result = true; } catch (Exception ex) { responseText = ex.Message; Log.Error(this.GetType().ToString(), \"Exception: \" + ex.Message); } Log.Debug(this.GetType().ToString(), string.Format(\"⽀付宝退款跟踪信息。GetForm:{0}\", responseText)); Log.Info(this.GetType().ToString(), \"Refund End......\"); return result; } View Code 2>接收⽀付宝异步通知(post) /// /// ⽀付宝退款异步通知 /// /// public ActionResult RefundNotify() { string result = string.Empty; try { Log.Info(this.GetType().ToString(), \"RefundNotify Start......\"); SortedDictionary bool verifyResult = Verify(sPara, Request.Form[\"notify_id\"], Request.Form[\"sign\"]); if (verifyResult)//验证成功 { //退款批次号 string batch_no = Request.Form[\"batch_no\"]; Log.Debug(this.GetType().ToString(), \"batch_no:\" + batch_no); //退款成功总数 string success_num = Request.Form[\"success_num\"]; Log.Debug(this.GetType().ToString(), \"success_num:\" + success_num); //退款结果明细 string result_details = Request.Form[\"result_details\"]; Log.Debug(this.GetType().ToString(), \"result_details:\" + result_details); //交易状态 //string trade_status = Request.Form[\"trade_status\"]; //Log.Info(this.GetType().ToString(), \"trade_status:\" + trade_status); //全额退款情况:trade_status= TRADE_CLOSED,⽽refund_status=REFUND_SUCCESS //⾮全额退款情况:trade_status= TRADE_SUCCESS,⽽refund_status=REFUND_SUCCESS Response.Write(\"success\"); //请不要修改或删除 } else//验证失败 { Response.Write(\"fail\"); } } else { Response.Write(\"⽆通知参数\"); } } catch(Exception ex) { Log.Info(this.GetType().ToString(), \"Exception:\" + ex.Message); _logger.Track(string.Format(\"⽀付宝退款跟踪信息。结果:{0}\", ex.Message), FoxconnConsts.APPSETTING_KEY_TRACK_INTERFACE); } Log.Info(this.GetType().ToString(), \"RefundNotify End......\"); return Content(\"fail\"); } View Code查询接⼝: /// /// 查询订单在⽀付宝的状态 /// /// /// private void AlipayTradePCQuery(订单查询实体 orderQuery) { var result = new 订单查询实体(); if (orderQuery == null) { //\"查询数据不能为空\" return; } #region 调⽤⽀付宝订单查询接⼝ string partner = \"签约账号\"; string sign_type = \"MD5\";//签名⽅式:MD5、RSA、DSA string key = \"MD5密钥\";//商户密钥 string input_charset = \"utf-8\";//字符编码格式 ⽬前⽀持 gbk 或 utf-8 //⽀付宝交易号 string trade_no = \"\"; //⽀付宝交易号与商户⽹站订单号不能同时为空 //商户订单号 string out_trade_no = \"\"; //////////////////////////////////////////////////////////////////////////////////////////////// //把请求参数打包成数组 SortedDictionary sParaTemp.Add(\"_input_charset\", input_charset.ToLower());//字符编码格式 ⽬前⽀持 gbk 或 utf-8 sParaTemp.Add(\"trade_no\", trade_no); sParaTemp.Add(\"out_trade_no\", out_trade_no);//商户订单号,商户⽹站订单系统中唯⼀订单号,必填 //建⽴请求 Submit submit = new Submit(partner, key, input_charset, sign_type); string sHtmlText = submit.BuildRequest(sParaTemp); XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.LoadXml(sHtmlText); string isSuccess = xmlDoc.SelectSingleNode(\"/alipay/is_success\").InnerText; if (isSuccess == \"T\")//请求成功 { #region 根据订单状态处理业务数据 string tradeState = xmlDoc.SelectSingleNode(\"/alipay/response/trade/trade_status\").InnerText; if (tradeState == \"TRADE_FINISHED\" || tradeState == \"TRADE_CLOSED\" || tradeState == \"TRADE_SUCCESS\")//⽀付成功 { string transaction_id = xmlDoc.SelectSingleNode(\"/alipay/response/trade/trade_no\").InnerText; //string buyer_id = xmlDoc.SelectSingleNode(\"/alipay/response/trade/buyer_id\").InnerText; string buyer_emial = xmlDoc.SelectSingleNode(\"/alipay/response/trade/buyer_email\").InnerText; //处理订单业务 } #endregion } else { string error = xmlDoc.SelectSingleNode(\"/alipay/error\").InnerText; result.AddError(string.Format(\"⽀付宝PC⽹站接⼝查询订单失败![接⼝返回码:{0}]\", error)); } } catch (Exception ex) { Log.Error(this.GetType().ToString(), \"Exception:\" + ex.Message); } #endregion } View Code3.记录⽇记类 public class Log { //在⽹站根⽬录下创建⽇志⽬录 public static string path = HttpRuntime.AppDomainAppPath + \"logs\\\\Alipay\"; /** * 向⽇志⽂件写⼊调试信息 * @param className 类名 * @param content 写⼊内容 */ public static void Debug(string className, string content) { WriteLog(\"DEBUG\", className, content); } /** * 向⽇志⽂件写⼊运⾏时信息 * @param className 类名 * @param content 写⼊内容 */ public static void Info(string className, string content) { WriteLog(\"INFO\", className, content); } /** * 向⽇志⽂件写⼊出错信息 * @param className 类名 * @param content 写⼊内容 */ public static void Error(string className, string content) { WriteLog(\"ERROR\", className, content); } /** * 实际的写⽇志操作 * @param type ⽇志记录类型 * @param className 类名 * @param content 写⼊内容 */ protected static void WriteLog(string type, string className, string content) { if (!Directory.Exists(path))//如果⽇志⽬录不存在就创建 { Directory.CreateDirectory(path); } string time = DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss.fff\");//获取当前系统时间 string filename = path + \"/\" + DateTime.Now.ToString(\"yyyy-MM-dd\") + \".log\";//⽤⽇期对⽇志⽂件命名 //创建或打开⽇志⽂件,向⽇志⽂件末尾追加记录 StreamWriter mySw = File.AppendText(filename); //向⽇志⽂件写⼊内容 string write_content = time + \" \" + type + \" \" + className + \": \" + content; mySw.WriteLine(write_content); //关闭⽇志⽂件 mySw.Close(); mySw.Dispose(); } } View Code
因篇幅问题不能全部显示,请点此查看更多更全内容