代码:
using CMS.Utility.ReturnResult; using OAuthWebAPI.Package; using Common; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Ninject; using System.Data; using Aop.Api; using Aop.Api.Request; using Aop.Api.Response; using System.Text; using System.Web; using System.Web.Script.Serialization; using Aop.Api.Util; namespace ADT.TuDou.OAuthWebAPI.Controllers { public class TestAliPayController : ApiController { private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// 支付宝同步通知 /// AliPay/AliPayCallBack /// </summary> /// <param name="data"></param> /// <returns></returns> [AcceptVerbs("POST")] [Authorize] public HttpResponseMessage AliPayCallBack([FromBody]PostModel.AliPayCallBackModel data) { //参考:https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.o060pE&treeId=193&articleId=105302&docType=1 MessagesDataCodeModel json = new MessagesDataCodeModel(false, "无效参数", 401); { try { if (data.resultStatus == "9000") { json.Success = true; json.Msg = "操作成功"; json.Code = 200; } else if (data.resultStatus == "8000") { json.Success = false; json.Msg = "正在处理中"; json.Code = 203; } else if (data.resultStatus == "4000") { json.Success = false; json.Msg = "订单支付失败"; json.Code = 204; } else if (data.resultStatus == "5000") { json.Success = false; json.Msg = "重复请求"; json.Code = 205; } else if (data.resultStatus == "6001") { json.Success = false; json.Msg = "用户中途取消"; json.Code = 206; } else if (data.resultStatus == "6002") { json.Success = false; json.Msg = "网络连接出错"; json.Code = 207; } else if (data.resultStatus == "6004") { json.Success = false; json.Msg = "支付结果未知"; json.Code = 208; } else { json.Success = false; json.Msg = "其他未知错误"; json.Code = 209; } } catch (Exception ex) { json.Success = false; json.Msg = "服务器无响应"; json.Code = 500; json.Data = ex.Message; logger.Error("AliPayController.AliPayCallBack", ex); } return ToJsonTran.ToJson(json); } } /// <summary> /// 阿里异步通知 /// AliPay/Notify /// </summary> /// <returns></returns> [AcceptVerbs("POST")] public void Notify() { //验签(解决问题成功率90 %) issig为false,一般有几种可能: //1、支付宝公鈅(特别是PHP编程语言,一定要用demo中的支付宝公钥文件)或者key有问题; //2、参与验签的待签名字符串存在中文乱码,或者多了商户的自定义参数(异步通知地址带自定义参数;),或者少了一些异步通知参数; //3、需要RSA验签,但是商户用MD5验签; //4、验签的编码格式有问题(主要是java和c#); //5、验签的代码逻辑有问题,强烈建议参考demo的 //[FromBody]PostModel.AliNotify data //参考地址:https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.XZMUaR&treeId=204&articleId=105301&docType=1 //编码(101-登录无效,102-账号无效,200-成功,201-失败,202~299-其他原因1-99,300-无效提交方式,400-无效参数) MessagesDataCodeModel json = new MessagesDataCodeModel(false, "无效参数", 401); string result = "failed"; try { #region 验签 //获取所有通知参数,其中sign不要解码 IDictionary<string, string> dic = GetParas(); //string signContent = AlipaySignature.GetSignContent(dic);//验签字符串 //支付宝公钥 string publicKeyPem_Alipay = HttpContext.Current.Server.MapPath("~/alipay/rsa_public_key_alipay.pem"); //验签,公共类库下载地址: bool ValidateSign = AlipaySignature.RSACheckV1(dic, publicKeyPem_Alipay, ConfigApi.AliPay_App_charset); #endregion #region 处理订单 if (ValidateSign) { //处理订单的业务逻辑... result = "success"; } else { result = "RSACheckV1Error"; logger.Error("AliPayController.Notify【验签失败】"); } #endregion } catch (Exception ex) { logger.Error("AliPay/Notify", ex); result = "exception"; } HttpContext.Current.Response.Write(result); HttpContext.Current.Response.End(); } /// <summary> /// RSA签名 /// AliPay/Sign /// 系统平台 ios 、android /// pro_type 商品类型 购买官方录音专辑=1,购买Vip会员=2,购买绘本=3,快乐英语=4,打赏优秀专家=5,打赏优秀机构=6,打赏优秀电台=7, /// </summary> /// <param name="data"></param> /// <returns></returns> [AcceptVerbs("POST")] [Authorize] public HttpResponseMessage Sign([FromBody]PostModel.biz_content data) { //编码(101-登录无效,102-账号无效,200-成功,201-失败,202~299-其他原因1-99,300-无效提交方式,400-无效参数) MessagesDataCodeModel json = new MessagesDataCodeModel(false, "无效参数", 401); try { if (data != null) { //生成签名之前,编写自己的验证逻辑... //订单编号 string out_trade_no = Guid.NewGuid().ToString().Replace("-", ""); double total_fee = 0.01;//费用 1分钱(测试) #region 生成签名 string publicKeyPem = HttpContext.Current.Server.MapPath("~/alipay/rsa_public_key.pem");//公钥 string privateKeyPem = HttpContext.Current.Server.MapPath("~/alipay/rsa_private_key.pem");//私钥 string app_id = ConfigApi.AliPay_App_app_id;//app支付,支付宝中该应用的ID string seller_id = ConfigApi.AliPay_App_seller_id;//商户账户 string method = ConfigApi.AliPay_App_method;//alipay.trade.app.pay string charset = ConfigApi.AliPay_App_charset;//utf-8 string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string version = @"1.0"; string sign_type = @"RSA"; string timeout_express = "30m"; string notify_url = ConfigApi.AliPay_App_notify_url; string body = data.body; string subject = data.subject; //拼接签名使用的字符串【编码】 string app_id_encode = HttpUtility.UrlEncode(app_id, Encoding.GetEncoding(charset));// string charset_encode = HttpUtility.UrlEncode(charset, Encoding.GetEncoding(charset));// string method_encode = HttpUtility.UrlEncode(method, Encoding.GetEncoding(charset));// string sign_type_encode = HttpUtility.UrlEncode(sign_type, Encoding.GetEncoding(charset));// string timestamp_encode = HttpUtility.UrlEncode(timestamp, Encoding.GetEncoding(charset));// string version_encode = HttpUtility.UrlEncode(version, Encoding.GetEncoding(charset));// string notify_url_encode = HttpUtility.UrlEncode(ConfigApi.AliPay_App_notify_url, Encoding.GetEncoding(charset));// string body_encode = HttpUtility.UrlEncode(data.body, Encoding.GetEncoding(charset));// string subject_encode = HttpUtility.UrlEncode(data.subject, Encoding.GetEncoding(charset));// //订单内容 string biz_content = "{\"body\":\"" + body + "\",\"subject\":\"" + subject + "\",\"out_trade_no\":\"" + out_trade_no + "\",\"timeout_express\":\"" + timeout_express + "\",\"total_amount\":\"" + total_fee + "\",\"seller_id\":\"" + seller_id + "\",\"product_code\":\"QUICK_MSECURITY_PAY\"}"; //将订单内容编码,必须和支付宝指定的编码一致 utf-8 string biz_content_encode = HttpUtility.UrlEncode(biz_content, Encoding.GetEncoding(charset)); //构建签名参数集合 IDictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("app_id", app_id); dic.Add("biz_content", biz_content); dic.Add("charset", charset); dic.Add("method", method); dic.Add("notify_url", notify_url); dic.Add("sign_type", sign_type); dic.Add("timestamp", timestamp); dic.Add("version", version); //得到签名字符串 string result1 = Aop.Api.Util.AlipaySignature.RSASign(dic, privateKeyPem, charset, true, sign_type); //把得到的签名字符串使用指定的格式编码(utf-8),返回给客户端再用utf-8解码就行了 string result = HttpUtility.UrlEncode(result1, Encoding.GetEncoding(charset)); string jsonStr = Aop.Api.Util.AlipaySignature.GetSignContent(dic);//得到签名原字符串,客户端要用(支付宝提供的方法) //下面是我手动拼接的,其实阿里提供的有... //@"app_id=" + app_id_encode + "&biz_content=" + biz_content_encode + "&charset=" + charset_encode + "&method=" + method_encode + "¬ify_url=" + notify_url_encode + "&sign_type=" + sign_type_encode + "×tamp=" + timestamp_encode + "&version=" + version_encode; #endregion #region 生成订单,返回 out_trade_no //生成订单的逻辑... #endregion json.Success = true; json.Msg = "操作成功"; json.Code = 200; json.Data = new { TradeNo = out_trade_no, Sign = result, SignContent = jsonStr }; } } catch (Exception ex) { json.Success = false; json.Msg = "服务器无响应"; json.Code = 500; json.Data = ex.Message; logger.Error("AliPay/Sign", ex); } return ToJsonTran.ToJson(json); } public string GetPara(string ParaName) { string result = HttpContext.Current.Request[ParaName]; if (!string.IsNullOrEmpty(result)) { return result; } return ""; } public string GetPara_Decode(string ParaName) { string result = HttpContext.Current.Request[ParaName]; if (!string.IsNullOrEmpty(result)) { return HttpUtility.UrlDecode(result, System.Text.Encoding.GetEncoding(ConfigApi.AliPay_App_charset)); } return ""; } public IDictionary<string, string> GetParas() { IDictionary<string, string> dic = new Dictionary<string, string>(); for (int i = 0; i < HttpContext.Current.Request.Form.Keys.Count; i++) { string key = HttpContext.Current.Request.Form.Keys[i].ToString(); string value = ""; if (key != "sign") { value = GetPara_Decode(key); } else { value = GetPara(key); } if (!string.IsNullOrEmpty(value)) { dic.Add(key, value); } } return dic; } } }
签名类:
#region 支付签名 实体类 public class biz_content { /// <summary> /// 订单描述 [传入] /// </summary> public string body { get; set; } /// <summary> /// 订单标题 [传入] /// </summary> public string subject { get; set; } /// <summary> /// 付款总金额 [传入] /// </summary> public string total_amount { get; set; } /// <summary> /// 订单编号GUID /// </summary> public string out_trade_no { get; set; } /// <summary> /// 订单有效时限 /// </summary> public string timeout_express { get; set; } } #endregion
文档:https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.9CZS6Q&treeId=193&articleId=105465&docType=1
主要看的有四篇:申请支付请求参数说明、客户端同步返回、支付结构异步通知、交易操作接口
服务端SDK下载:https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.huKVyy&treeId=54&articleId=103419&docType=1
来源:https://www.cnblogs.com/xsj1989/p/6206441.html