public static void CheckResponseSign <T>(IAopRequest <T> request, string responseBody, bool isError, IAopParser <T> parser, string alipayPublicKey, string charset, string signType, bool keyFromFile) where T : AopResponse { if (string.IsNullOrEmpty(alipayPublicKey) || string.IsNullOrEmpty(charset)) { return; } SignItem signItem = parser.GetSignItem(request, responseBody); if (signItem == null) { throw new AopException("sign check fail: Body is Empty!"); } if ((!isError || (isError && !string.IsNullOrEmpty(signItem.Sign))) && !AlipaySignature.RSACheckContent(signItem.SignSourceDate, signItem.Sign, alipayPublicKey, charset, signType, keyFromFile)) { if (string.IsNullOrEmpty(signItem.SignSourceDate) || !signItem.SignSourceDate.Contains("\\/")) { throw new AopException("sign check fail: check Sign and Data Fail!"); } string signContent = signItem.SignSourceDate.Replace("\\/", "/"); if (!AlipaySignature.RSACheckContent(signContent, signItem.Sign, alipayPublicKey, charset, signType, keyFromFile)) { throw new AopException("sign check fail: check Sign and Data Fail JSON also"); } } }
/// <summary> /// 服务器异步通知页面 /// </summary> public ActionResult ReturnUrl() { /* 实际验证过程建议商户添加以下校验。 * 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号, * 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额), * 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email) * 4、验证app_id是否为该商户本身。 */ Dictionary <string, string> sArray = GetRequestGet(); if (sArray.Count != 0) { //订单号 string orderno = sArray["out_trade_no"]; bool flag = AlipaySignature.RSACheckV1(sArray, WeixinConfig.payKey, WeixinConfig.charset, WeixinConfig.signType, false);//支付宝公钥 if (flag) { ViewBag.Result = "支付成功"; ViewBag.icon = "success"; //ViewBag.display = "none"; LogHelper.AddLog("同步验证通过! 订单号:" + orderno); } else { ViewBag.Result = "未支付"; ViewBag.icon = "warn"; //ViewBag.display = "block"; LogHelper.AddLog("同步验证失败! 订单号:" + orderno); } ViewBag.orderno = orderno; //ViewBag.id = OperatorAgentProvider.Provider.Current().Id.ToString(); } return(View()); }
private void CheckResponseSign <T>(IAlipayRequest <T> request, string responseBody, bool isError, IAlipayParser <T> parser, AlipayOptions options) where T : AlipayResponse { var signItem = parser.GetSignItem(request, responseBody); if (signItem == null) { throw new AlipayException("sign check fail: Body is Empty!"); } if (!isError || isError && !string.IsNullOrEmpty(signItem.Sign)) { var rsaCheckContent = AlipaySignature.RSACheckContent(signItem.SignSourceDate, signItem.Sign, options.AlipayPublicKey, options.SignType); if (!rsaCheckContent) { if (!string.IsNullOrEmpty(signItem.SignSourceDate) && signItem.SignSourceDate.Contains("\\/")) { var srouceData = signItem.SignSourceDate.Replace("\\/", "/"); var jsonCheck = AlipaySignature.RSACheckContent(srouceData, signItem.Sign, options.AlipayPublicKey, options.SignType); if (!jsonCheck) { throw new AlipayException("sign check fail: check Sign and Data Fail JSON also"); } } else { throw new AlipayException("sign check fail: check Sign and Data Fail!"); } } } }
public IActionResult Callback() { /* 实际验证过程建议商户添加以下校验。 * 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号, * 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额), * 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email) * 4、验证app_id是否为该商户本身。 */ Dictionary <string, string> sArray = GetRequestGet(); if (sArray.Count != 0) { bool flag = AlipaySignature.RSACheckV1(sArray, Config.AlipayPublicKey, Config.CharSet, Config.SignType, false); if (flag) { Console.WriteLine($"同步验证通过,订单号:{sArray["out_trade_no"]}"); ViewData["PayResult"] = "同步验证通过"; } else { Console.WriteLine($"同步验证失败,订单号:{sArray["out_trade_no"]}"); ViewData["PayResult"] = "同步验证失败"; } } return(View()); }
public async Task <T> ExecuteAsync <T>(IAlipayRequest <T> request, string accessToken, string appAuthToken) where T : AlipayResponse { var multiMediaDownloadRequest = ((AlipayMobilePublicMultiMediaDownloadRequest)request); // 添加协议级请求参数 var txtParams = new AlipayDictionary(request.GetParameters()) { { METHOD, request.GetApiName() }, { VERSION, Options.Version }, { APP_ID, Options.AppId }, { FORMAT, Options.Format }, { TIMESTAMP, DateTime.Now }, { ACCESS_TOKEN, accessToken }, { SIGN_TYPE, Options.SignType }, { TERMINAL_TYPE, request.GetTerminalType() }, { TERMINAL_INFO, request.GetTerminalInfo() }, { PROD_CODE, request.GetProdCode() } }; if (!string.IsNullOrEmpty(appAuthToken)) { txtParams.Add(APP_AUTH_TOKEN, appAuthToken); } // 添加签名参数 txtParams.Add(SIGN, AlipaySignature.RSASign(txtParams, RSAPrivateParameters, Options.SignType)); var outStream = multiMediaDownloadRequest.Stream; var rsp = await DoGetAsync(txtParams, outStream); return((T)rsp); }
private static void CheckSignAndDecrypt() { // 参数构建 var charset = "UTF-8"; var bizContent = "<XML><AppId><![CDATA[2013082200024893]]></AppId><FromUserId><![CDATA[2088102122485786]]></FromUserId><CreateTime>1377228401913</CreateTime><MsgType><![CDATA[click]]></MsgType><EventType><![CDATA[event]]></EventType><ActionParam><![CDATA[authentication]]></ActionParam><AgreementId><![CDATA[201308220000000994]]></AgreementId><AccountNo><![CDATA[null]]></AccountNo><UserInfo><![CDATA[{\"logon_id\":\"15858179811\",\"user_name\":\"许旦辉\"}]]></UserInfo></XML>"; var publicKeyPem = Path.Combine(GetCurrentPath(), "public-key.pem"); var privateKeyPem = Path.Combine(GetCurrentPath(), "aop-sandbox-RSA-private-c#.pem"); if (!File.Exists(publicKeyPem)) { throw new FileNotFoundException(); } if (!File.Exists(privateKeyPem)) { throw new FileNotFoundException(); } IDictionary <string, string> paramsMap = new Dictionary <string, string>(); paramsMap.Add("biz_content", AlipaySignature.RSAEncrypt(bizContent, publicKeyPem, charset)); paramsMap.Add("charset", charset); paramsMap.Add("service", "alipay.mobile.public.message.notify"); paramsMap.Add("sign_type", "RSA"); paramsMap.Add("sign", AlipaySignature.RSASign(paramsMap, privateKeyPem, null, "RSA")); // 验签&解密 var resultContent = AlipaySignature.CheckSignAndDecrypt(paramsMap, publicKeyPem, privateKeyPem, true, true); Console.Write("resultContent=" + resultContent + "\n\r"); }
protected void Page_Load(object sender, EventArgs e) { /* 实际验证过程建议商户添加以下校验。 * 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号, * 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额), * 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email) * 4、验证app_id是否为该商户本身。 */ Dictionary <string, string> sArray = GetRequestPost(); if (sArray.Count != 0) { bool flag = AlipaySignature.RSACheckV1(sArray, config.alipay_public_key, config.charset, config.sign_type, false); if (flag) { //交易状态 //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //请务必判断请求时的total_amount与通知时获取的total_fee为一致的 //如果有做过处理,不执行商户的业务程序 //注意: //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知 string trade_status = Request.Form["trade_status"]; Response.Write("success"); } else { Response.Write("fail"); } } }
public Task <T> SdkExecuteAsync <T>(IAlipayRequest <T> request, string optionsName) where T : AlipayResponse { var options = string.IsNullOrEmpty(optionsName) ? _optionsSnapshotAccessor.Value : _optionsSnapshotAccessor.Get(optionsName); // 构造请求参数 var requestParams = BuildRequestParams(request, null, null, options); // 字典排序 var sortedParams = new SortedDictionary <string, string>(requestParams); var sortedAlipayDic = new AlipayDictionary(sortedParams); // 参数签名 var signContent = AlipaySignature.GetSignContent(sortedAlipayDic); var signResult = AlipaySignature.RSASignContent(signContent, options.PrivateRSAParameters, options.SignType); // 添加签名结果参数 sortedAlipayDic.Add(SIGN, signResult); // 参数拼接 var signedResult = AlipayUtility.BuildQuery(sortedAlipayDic); // 构造结果 var rsp = Activator.CreateInstance <T>(); rsp.Body = signedResult; return(Task.FromResult(rsp)); }
public void Submit_OnClick(object sender, EventArgs e) { _configInfo.IsAlipayPc = Utils.ToBool(DdlIsEnabled.SelectedValue); if (_configInfo.IsAlipayPc && PhOpenApi.Visible) { try { AlipaySignature.RSASignCharSet("test", TbPrivateKey.Text, "utf-8", false, "RSA2"); } catch (Exception ex) { Utils.SwalError(Page, "应用私钥格式不正确!", ex.Message); return; } } _configInfo.AlipayPcIsMApi = Utils.ToBool(DdlIsMApi.SelectedValue); _configInfo.AlipayPcAppId = TbAppId.Text; _configInfo.AlipayPcPid = TbPid.Text; _configInfo.AlipayPcMd5 = TbMd5.Text; _configInfo.AlipayPcPublicKey = TbPublicKey.Text; _configInfo.AlipayPcPrivateKey = TbPrivateKey.Text; Plugin.SetConfigInfo(_siteId, _configInfo); Utils.Redirect(PageIntegrationPay.GetRedirectUrl(_siteId)); }
protected void Page_Load(object sender, EventArgs e) { Dictionary <string, string> sArray = GetRequestPost(); if (sArray.Count != 0) { bool flag = AlipaySignature.RSACheckV1(sArray, config.alipay_public_key, config.charset, config.sign_type, false); if (flag) { //交易状态 //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //请务必判断请求时的total_amount与通知时获取的total_fee为一致的 //如果有做过处理,不执行商户的业务程序 //注意: //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知 string trade_status = Request.Form["trade_status"]; Response.Write("success"); } else { Response.Write("fail"); } } }
/// <summary> /// 商城自动对账 /// </summary> public ActionResult ShopNotifyUrl() { Dictionary <string, string> sArray = GetRequestPost(); if (sArray.Count != 0) { bool flag = AlipaySignature.RSACheckV1(sArray, Help.alipay_public_key, Help.charset, Help.sign_type, false); if (flag) { string out_trade_no = Request.Form["out_trade_no"]; //支付宝交易号 string trade_no = Request.Form["trade_no"]; //获取总金额 string total_amount = Request.Form["total_amount"]; //交易状态 string trade_status = Request.Form["trade_status"]; if (trade_status == "TRADE_SUCCESS" || trade_status == "TRADE_FINISHED") { if (Helper.ShopOrder(out_trade_no, trade_no, 1, decimal.Parse(total_amount))) { return(Content("success")); } } } } return(Content("fail")); }
protected void Page_Load(object sender, EventArgs e) { System.Diagnostics.Debug.WriteLine("同步接收"); /* 实际验证过程建议商户添加以下校验。 * 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号, * 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额), * 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email) * 4、验证app_id是否为该商户本身。 */ Dictionary <string, string> sArray = GetRequestGet(); if (sArray.Count != 0) { bool flag = AlipaySignature.RSACheckV1(sArray, config.alipay_public_key, config.charset, config.sign_type, false); if (flag) { Response.Write("同步验证通过"); Response.Redirect("~/Default.aspx"); } else { Response.Write("同步验证失败"); } } }
public void SetOption(IAlipayOptions options) { if (options == null) { throw new ArgumentException(nameof(options)); } //SignType私钥检查 if (string.IsNullOrEmpty(options.SignType)) { throw new Exception("您的支付宝配置未能通过检查,详细信息:签名类型未指定!"); } //RSA私钥检查 if (string.IsNullOrEmpty(options.PrivateKey)) { throw new Exception("您的支付宝配置未能通过检查,详细信息:未能获取到商户私钥!"); } //RSA私钥格式检查 RSA rsaCsp = AlipaySignature.LoadCertificateString(options.PrivateKey, options.SignType); if (rsaCsp == null) { throw new Exception("您的支付宝配置未能通过检查,详细信息:商户私钥格式错误,未能导入!"); } this.Uid = options.Uid; this.AlipayPublicKey = options.AlipayPublicKey; this.AppId = options.AppId; this.CharSet = options.CharSet; this.Gatewayurl = options.Gatewayurl; this.PrivateKey = options.PrivateKey; this.SignType = options.SignType; }
public void Test1() { try { string prikey = "MIIEpAIBAAKCAQEAqOTxQbDUUkm/CS/eVTHgARhqCfs5mWe/FImEIDyPrsExswLUbc6pIXBulqtYOJ9Nl4fljNgXJbh4CyoUtiM5U9jf5yoPthJq667rPwtRVOIDnmNWKZNHponXjFBQs/juNkUgdX4kcWx695cWGkm+SRXCQQsKcSsqubFwLgXRP9HErfPwColtfmwVZVNXWA4ZtHTrSczbVDplMS8Fg73eprwIxYvpOFxFhAAwC4+Xw753Zd+u0P05YhXrQ/76g1YqNBkiHlOpWtwLVdL+zU9Nk5PxRGgjUqvJpDUxwjEHCEDxD4fxdgS+ml5pm0SsRKyXFm2+ZyPDlu7LQdx28kgAeQIDAQABAoIBAQCZvGQa/qIWEUjSTP9dn1uew6FqWoLwr64QPKjHSzkiwnrBzradCXuMk7ImdeuFBwTzBOGfledkD4k96F0X+fIp74TH/9JzUkp/JCbAqUWsNVtD5no8t/KFln1dHJKJb/Mt9Th5mowDrtIz4xRcc3nBPwwmdq1XnAp1Ix3Q1rzFEGX4Ndce6q2YkbpAMKgl3HeIbgKrKHOxmJJ9hJ3rUzc24D+e2dR9eYCym576RrxxuHISysa4N41MSdZq5jXaaWmwIGg68v5wEVJcEkmAc91webKAfy1SVdQiAl8I1xSI3JDUXloWrUAX3ZnRcknjEmhcs7by5QrOnbTd8ZR5Mkt9AoGBAPU4QLSj5QdNz+HjoRdfxda2lK1OPy3O/jReCE6NnqTbvVygQjFdlmYnGFhwnLa1SoWYW9M9mg9lRxsQoBt6Zdh4Pu08cG+3GY1i4tILWroLekPHImz8TcqYCeU9OlAt+Yo59NWTA0EboDfr/YPx8WYeJ5g1z+yz9qG8+iz04ZMDAoGBALBRtZ7ywEYGdHW47jhNpJwTfBygFCOZzoIIpYoEuHVrtlBiKtPgMEryReOEurpl6TKgdOVZ99F0G0lIMZtyqdRKkJh8t99S5z7Y7yWRA+1ImcmHNC/r+KZig1gcAW6z26xVNPsNtjiXwixrQ5cIsQGN53mgauGCVsrzyH3yMkfTAoGAfKiQHESFFWV1HHw/VEaXqENA6akxbPQhPjXfOy+7Skt6xC+j9ryAzIVrVupIgIlAzRFa/NQAEXuG3jdhbRaX16epNajX77LBBqMSc3zaLmHPUc1VrtnEIg2QWjz5+/CjPqWf1ULbEKoelM8fHYhNE4CY2EPi443I/we2lkwWsEkCgYEAhvck5XTARVnvj6VthF+6n1Yy7N6ES/QSJWtk+889O3Sl68YZLnIvxU7KvKv/G2ujJAO7N0y06/nKYUAH6QvOgBhLss3VGfel12/LL6BftySZw6/g/MXOYd6K18koN4spnjLjCUGnuI5CLio1ZMlcZOoww+NNrS1OLrCJSg84+c0CgYAkw6xcfaKLH39+jdc2DLVrip4JYv+p4v9GuQbn1C1aqjaxVR5ZjbYuIaJXhr8Z0qIFaYENBVAA0AM75lkZUcYwVNiIfSA2WSFlymoy90ovPIQaG5jaQXRv8hrjRJ1zQ/l5JzhngERVbi4BBcz2QfC9GxsEa4CYGciI/sMH44fUvg=="; string pubkey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqOTxQbDUUkm/CS/eVTHgARhqCfs5mWe/FImEIDyPrsExswLUbc6pIXBulqtYOJ9Nl4fljNgXJbh4CyoUtiM5U9jf5yoPthJq667rPwtRVOIDnmNWKZNHponXjFBQs/juNkUgdX4kcWx695cWGkm+SRXCQQsKcSsqubFwLgXRP9HErfPwColtfmwVZVNXWA4ZtHTrSczbVDplMS8Fg73eprwIxYvpOFxFhAAwC4+Xw753Zd+u0P05YhXrQ/76g1YqNBkiHlOpWtwLVdL+zU9Nk5PxRGgjUqvJpDUxwjEHCEDxD4fxdgS+ml5pm0SsRKyXFm2+ZyPDlu7LQdx28kgAeQIDAQAB"; string abc = "abc123"; RSACryptoServiceProvider rsaCsp = AlipaySignature.LoadCertificateString(prikey, "RSA2"); string r1 = Convert.ToBase64String(AlipaySignature.RSAEncrypt(rsaCsp, Encoding.UTF8.GetBytes(abc))); string r2 = Encoding.UTF8.GetString(AlipaySignature.RSADecrypt(rsaCsp, Convert.FromBase64String(r1))); var sPublicKeyPEM = "-----BEGIN PUBLIC KEY-----\r\n"; sPublicKeyPEM += pubkey; sPublicKeyPEM += "-----END PUBLIC KEY-----\r\n\r\n"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.PersistKeyInCsp = false; RSACryptoServiceProviderExtension.LoadPublicKeyPEM(rsa, sPublicKeyPEM); string r11 = Convert.ToBase64String(AlipaySignature.RSAEncrypt(rsa, Encoding.UTF8.GetBytes(abc))); string r22 = Encoding.UTF8.GetString(AlipaySignature.RSADecrypt(rsaCsp, Convert.FromBase64String(r1))); } catch (Exception) { } }
private static void EncryptAndSign() { // 参数构建 var bizContent = "<XML><ToUserId><![CDATA[2088102122494786]]></ToUserId><AppId><![CDATA[2013111100036093]]></AppId><AgreementId><![CDATA[20131111000001895078]]></AgreementId>" + "<CreateTime>12334349884</CreateTime>" + "<MsgType><![CDATA[image-text]]></MsgType>" + "<ArticleCount>1</ArticleCount>" + "<Articles>" + "<Item>" + "<Title><![CDATA[[回复测试加密解密]]></Title>" + "<Desc><![CDATA[测试加密解密]]></Desc>" + "<Url><![CDATA[http://m.taobao.com]]></Url>" + "<ActionName><![CDATA[立即前往]]></ActionName>" + "</Item>" + "</Articles>" + "<Push><![CDATA[false]]></Push>" + "</XML>"; var publicKeyPem = Path.Combine(GetCurrentPath(), "public-key.pem"); var privateKeyPem = Path.Combine(GetCurrentPath(), "aop-sandbox-RSA-private-c#.pem"); if (!File.Exists(publicKeyPem)) { throw new FileNotFoundException(); } if (!File.Exists(privateKeyPem)) { throw new FileNotFoundException(); } var responseContent = AlipaySignature.encryptAndSign(bizContent, publicKeyPem, privateKeyPem, "UTF-8", true, true); Console.Write("resultContent=" + responseContent + "\n\r"); }
public static string Signature(VipUserOrderInfo info) { string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string biz_content = string.Empty; StringBuilder builder = new StringBuilder(); builder.Append("app_id="); builder.Append(HttpUtility.UrlEncode(app_id)); builder.Append("&biz_content="); biz_content = "{\"timeout_express\":\"30m\",\"seller_id\":\""; biz_content += seller_id; biz_content += "\","; biz_content += "\"product_code\":\"QUICK_MSECURITY_PAY\","; biz_content += "\"total_amount\":\"" + info.mo_money.ToString("f2") + "\","; biz_content += "\"subject\":\"" + "企业查询宝会员" + "\","; biz_content += "\"body\":\"" + "企业查询宝会员" + "\","; biz_content += "\"out_trade_no\":\"" + info.mo_orderid + "\"}"; biz_content = HttpUtility.UrlEncode(biz_content); builder.Append(biz_content); builder.Append("&charset=" + HttpUtility.UrlEncode("utf-8")); builder.Append("&method=" + HttpUtility.UrlEncode("alipay.trade.app.pay")); builder.Append("¬ify_url="); builder.Append(HttpUtility.UrlEncode(alipay_notify_url)); builder.Append("&sign_type=" + HttpUtility.UrlEncode("RSA")); builder.Append("×tamp="); builder.Append(HttpUtility.UrlEncode(timestamp).Replace("+", " ")); builder.Append("&version=" + HttpUtility.UrlEncode("1.0")); string Signature = AlipaySignature.RSASign(SignatureContent(info, timestamp), APP_PRIVATE_KEY, "utf-8", "RSA"); builder.Append("&sign="); builder.Append(HttpUtility.UrlEncode(Signature)); return(builder.ToString()); }
private static void CheckSign() { IDictionary <string, string> paramsMap = new Dictionary <string, string>(); paramsMap.Add("appId", "2013092500031084"); var privateKeyPem = Path.Combine(GetCurrentPath(), "aop-sandbox-RSA-private-c#.pem"); if (!File.Exists(privateKeyPem)) { throw new FileNotFoundException(); } var sign = AlipaySignature.RSASign(paramsMap, privateKeyPem, null, "RSA"); paramsMap.Add("sign", sign); var publicKey = Path.Combine(GetCurrentPath(), "public-key.pem"); if (!File.Exists(publicKey)) { throw new FileNotFoundException(); } var checkSign = AlipaySignature.RSACheckV2(paramsMap, publicKey); Console.Write("---------公众号通知消息签名验证--------" + "\n\r"); Console.Write("checkSign:" + checkSign + "\n\r"); }
/// <summary> /// 异步回调 /// </summary> public void AsyncNotify() { Dictionary <string, string> sArray = GetRequestPost(); if (sArray.Count != 0) { bool flag = AlipaySignature.RSACheckV1(sArray, config.alipay_public_key, config.charset, config.sign_type, false); if (flag) { //交易状态 //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //请务必判断请求时的total_amount与通知时获取的total_fee为一致的 //如果有做过处理,不执行商户的业务程序 //注意: //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知 string trade_status = Request.Form["trade_status"]; log.Info("异步回调,trade_status为:" + trade_status); log.Info("异步回调,成功"); Response.Write("success"); } else { log.Info("异步回调,失败"); Response.Write("fail"); } } else { log.Info("异步回调,获取到的参数为空"); } }
/// <summary> /// 生成RSA签名后的订单字符串 /// </summary> /// <param name="price"></param> /// <param name="description"></param> /// <returns></returns> public static string createRSASignedOrderString(double price, string description) { Dictionary <string, string> orderStringDict = new Dictionary <string, string>(); orderStringDict.Add("app_id", APP_ID); orderStringDict.Add("method", "alipay.trade.app.pay"); orderStringDict.Add("format", "JSON"); orderStringDict.Add("charset", "utf-8"); orderStringDict.Add("sign_type", "RSA"); orderStringDict.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); orderStringDict.Add("version", "1.0"); orderStringDict.Add("notify_url", ""); orderStringDict.Add("biz_content", generateBizContentString(price.ToString(), description)); // 排序拼接成字符串 string orderInfo = AlipaySignature.GetSignContent(orderStringDict); string orderInfoEncoded = Core.CreateLinkStringUrlencode(orderStringDict, (new System.Text.UTF8Encoding())); // 签名 string privateKeyPem = GetCurrentPath() + "rsa_private_key.pem"; string signString = AlipaySignature.RSASign(orderInfo, privateKeyPem, null, "RSA"); signString = HttpUtility.UrlEncode(signString, new UTF8Encoding()); // 加上sign string orderString = orderInfoEncoded + "&sign=" + signString; // 拼接最终返回给客户端的字符串 return(orderString); }
public string AcquirePageCreateandpay() { Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("service", "alipay.dut.customer.agreement.page.sign"); dic.Add("partner", AlipayConfig.Pid); dic.Add("product_code", "GENERAL_WITHHOLDING_P"); //dic.Add("access_info", "{\"channel\":\"ALIPAYAPP\"}"); dic.Add("access_info", "{\"channel\":\"PC\"}"); dic.Add("_input_charset", "utf-8"); //dic.Add("scene", "INDUSTRY|CARRENTAL"); //dic.Add("agreement_sign_parameters", Newtonsoft.Json.JsonConvert.SerializeObject(dic)); //dic.Add("notify_url", AlipayConfig.NotifyUrl); //dic.Add("out_trade_no", "201601010001x"); //dic.Add("request_from_url", "test"); //dic.Add("seller_id", AlipayConfig.SellerId); //var sign = AlipaySignature.RSASign(dic,AlipayConfig.AliPayHzhbPrivateKey, AlipayConfig.Charset,false, AliPaySignType.RSA.ToString()); var @params = AlipaySignature.GetSignContent(dic); var sign = Md5Sign(@params, AlipayConfig.Md5Key, "utf-8"); dic.Add("sign", sign); dic.Add("sign_type", "MD5"); var content = AlipaySignature.GetSignContent(dic); return(content); }
/// <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 isSign = false; if (sign != null && sign != "") { switch (_sign_type) { //isSgin = AlipayMD5.Verify(preSignStr, sign, _key, charset); case "RSA": isSign = AlipaySignature.RSACheckContent(preSignStr, sign, Config.alipay_public_key, _charset); break; default: break; } } return(isSign); }
/// <summary> /// 统一下单并支付页面接口-alipay.acquire.page.createandpay(首次扣款和签约合并) /// </summary> /// <returns></returns> public string AlipayAcquirePageCreateandpay() { Dictionary <string, string> dic = new Dictionary <string, string>(); // 基本参数 dic.Add("service", "alipay.acquire.page.createandpay"); dic.Add("partner", AlipayConfig.Pid); dic.Add("product_code", "GENERAL_WITHHOLDING"); dic.Add("integration_type", "ALIAPP"); dic.Add("_input_charset", "utf-8"); // 业务参数 dic.Add("out_trade_no", "DX" + DateTime.Now.ToString("yyyyMMddHHssmmffff")); //商户网站唯一订单号 dic.Add("subject", "TestOrder"); //订单标题 dic.Add("total_fee", "0.01"); // 订单金额 dic.Add("agreement_sign_parameters", "{\"productCode\":\"GENERAL_WITHHOLDING_P\",\"scene\":\"INDUSTRY|APPSTORE\",\"notifyUrl\":\"https://www.gingergo.cn/api/alipay/signed\",\"externalAgreementNo\":\"\"}"); dic.Add("notify_url", "https://www.gingergo.cn/api/alipay/signed"); dic.Add("request_from_url", "https://www.gingergo.cn/api/alipay/signed"); dic.Add("return_url", "https://www.gingergo.cn/api/alipay/signed"); dic.Add("seller_id", AlipayConfig.Pid); var @params = AlipaySignature.GetSignContent(dic); var sign = Md5Sign(@params, AlipayConfig.Md5Key, "utf-8"); dic.Add("sign", sign); dic.Add("sign_type", "MD5"); var content = AlipaySignature.GetSignContent(dic); return(content); }
/// <summary> /// 支付异步回调通知 需配置域名 因为是支付宝主动post请求这个action 所以要通过域名访问或者公网ip /// </summary> public async void Notify() { /* 实际验证过程建议商户添加以下校验。 * 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号, * 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额), * 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email) * 4、验证app_id是否为该商户本身。 */ Dictionary <string, string> sArray = GetRequestPost(); if (sArray.Count != 0) { bool flag = AlipaySignature.RSACheckV1(sArray, Config.AlipayPublicKey, Config.CharSet, Config.SignType, false); if (flag) { //交易状态 //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //请务必判断请求时的total_amount与通知时获取的total_fee为一致的 //如果有做过处理,不执行商户的业务程序 //注意: //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知 Console.WriteLine(Request.Form["trade_status"]); await Response.WriteAsync("success"); } else { await Response.WriteAsync("fail"); } } }
/// <summary> /// 支付异步回调通知 需配置域名 因为是支付宝主动post请求这个action 所以要通过域名访问或者公网ip /// </summary> public void Notify() { /* 实际验证过程建议商户添加以下校验。 * 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号, * 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额), * 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email) * 4、验证app_id是否为该商户本身。 */ IDictionary <string, string> sArray = GetRequestPost(); if (sArray.Count != 0) { bool flag = AlipaySignature.RSACheckV1(sArray, Config.alipay_public_key, Config.charset, Config.sign_type, false); if (flag) { Console.WriteLine($"异步验证通过,订单号:{sArray["out_trade_no"]}"); ViewData["PayResult"] = "同步验证通过"; } else { Console.WriteLine($"异步验证失败,订单号:{sArray["out_trade_no"]}"); ViewData["PayResult"] = "异步验证失败"; } } }
/// <summary> /// 同步回调 /// </summary> public ActionResult Callback() { Dictionary <string, string> sArray = GetRequestGet(); if (sArray.Count != 0) { bool flag = AlipaySignature.RSACheckV1(sArray, AlipayPublicKey, CharSet, SignType, false); if (flag) { Console.WriteLine($"同步验证通过,订单号:{sArray["out_trade_no"]}"); ViewData["PayResult"] = "同步验证通过"; } else { Console.WriteLine($"同步验证失败,订单号:{sArray["out_trade_no"]}"); ViewData["PayResult"] = "同步验证失败"; } AlipayTradeQueryResponseViewModel traceState = GetTraceMsg(sArray["out_trade_no"], sArray["trade_no"]); if (traceState.alipay_trade_query_response.code != "10000") { Console.WriteLine($"获取订单失败,失败原因:{traceState.alipay_trade_query_response.msg}"); } } return(View()); }
public IActionResult SuccessPay() //最终购买成功 { if (Request.Cookies["buyerNickName"] != null) { return(View()); } else { Dictionary <string, string> sArray = GetRequestGet(); if (sArray.Count != 0) { bool flag = AlipaySignature.RSACheckV1(sArray, AlipayConfig.AlipayPublicKey, AlipayConfig.CharSet, AlipayConfig.SignType, false); if (flag) { Console.WriteLine($"同步验证通过,订单号:{sArray["out_trade_no"]}"); ViewData["PayResult"] = "同步验证通过"; } else { Console.WriteLine($"同步验证失败,订单号:{sArray["out_trade_no"]}"); ViewData["PayResult"] = "同步验证失败"; } } return(Redirect("/Entry/BuyerLogIn")); } }
public Task <T> SdkExecuteAsync <T>(IAlipayRequest <T> request) where T : AlipayResponse { // 构造请求参数 var requestParams = BuildRequestParams(request, null, null); // 字典排序 var sortedParams = new SortedDictionary <string, string>(requestParams); var sortedAlipayDic = new AlipayDictionary(sortedParams); // 参数签名 var signContent = AlipaySignature.GetSignContent(sortedAlipayDic); var signResult = AlipaySignature.RSASignContent(signContent, PrivateRSAParameters, Options.SignType); // 添加签名结果参数 sortedAlipayDic.Add(SIGN, signResult); // 参数拼接 var signedResult = HttpClientEx.BuildQuery(sortedAlipayDic); // 构造结果 var rsp = Activator.CreateInstance <T>(); rsp.Body = signedResult; return(Task.FromResult(rsp)); }
/// <summary> /// 检查阿里支付。正确返回订单号,错误返回null /// </summary> /// <param name="dict"></param> /// <param name="Total_amount"></param> /// <returns></returns> public string CheckAliPay(IDictionary <string, string> dict, string Total_amount) { bool flag = AlipaySignature.RSACheckV1(dict, alipayPublicKey, "utf-8", "RSA2", false); txyInfo info = new txyInfo(); info.content = JsonConvert.SerializeObject(dict + "==flag===" + flag); txyInfoOper.Instance.Add(info); if (flag) { var total_amount = dict["total_amount"]; var out_trade_no = dict["out_trade_no"]; string status = dict["trade_status"]; string seller_id = dict["seller_id"]; string app_id = dict["app_id"]; if (total_amount == Total_amount && seller_id == sellerId && app_id == appId) { switch (status) { case "TRADE_SUCCESS": return(out_trade_no); } } } return(null); }
//public override DApiResult<string> Pay(long orderNo, decimal price, string subject) //{ // var dict = Config.BaseParams("alipay.trade.pay"); // //业务参数 // var item = new Dictionary<string, object> // { // {"out_trade_no", orderNo}, // {"product_code", "QUICK_MSECURITY_PAY"}, // {"auth_code", "28763443825664394"}, // {"subject", subject}, // {"total_amount", price} // }; // dict.Add("biz_content", JsonHelper.ToJson(item)); // dict.Add("sign", dict.RsaSign(Config.PrivateKey, Config.Charset)); // var url = $"{Config.Gateway}?{dict.ParamsUrl()}"; // Logger.Info(JsonHelper.ToJson(dict, indented: true)); // using (var http = new HttpHelper(url, Encoding.GetEncoding(Config.Charset))) // { // var html = http.GetHtml(); // Logger.Info(html); // var dto = JsonHelper.Json<ReturnAlipayDto>(html); // if (dto?.alipay_trade_pay_response == null) // return DApiResult.Error<string>("支付接口异常"); // var result = dto.alipay_trade_pay_response; // if (result.code != "10000") // return DApiResult.Error<string>($"{result.msg}:{result.sub_msg}"); // return DApiResult.Succ(string.Empty); // } //} public override DResult <VerifyDto> Verify() { var paramDict = OnlinePayHelper.GetParams(); Logger.Info(JsonHelper.ToJson(paramDict, indented: true)); var signVerified = AlipaySignature.RsaCheck(paramDict, Config.PublicKey, Config.Charset); if (!signVerified) { return(DResult.Error <VerifyDto>("验证签名失败")); } if (paramDict.GetValue <string>("app_id") != Config.AppId) { return(DResult.Error <VerifyDto>("AppId异常")); } var dto = new VerifyDto { Id = paramDict.GetValue <string>("out_trade_no"), TradeNo = paramDict.GetValue <string>("trade_no"), TradeStatus = paramDict.GetValue <string>("trade_status"), Amount = paramDict.GetValue <decimal>("total_amount"), BuyerId = paramDict.GetValue <string>("buyer_id"), BuyerAccount = paramDict.GetValue <string>("buyer_logon_id") }; return(DResult.Succ(dto)); }
private void CheckNotifySign(IDictionary <string, string> parameters, RSAParameters publicRSAParameters, string signType) { try { logger?.LogDebug($"{DateTime.Now} 支付宝回调CheckNotifySign"); if (parameters == null || parameters.Count == 0) { throw new Exception("sign check fail: content is Empty!"); } if (!parameters.TryGetValue("sign", out var sign)) { throw new Exception("sign check fail: sign is Empty!"); } var prestr = GetSignContent(parameters); if (!AlipaySignature.RSACheckContent(prestr, sign, publicRSAParameters, signType)) { throw new Exception("sign check fail: check Sign Data Fail!"); } } catch (Exception ex) { logger?.LogError($"{DateTime.Now} 支付宝回调CheckNotifySign报错", ex.Message); } }