using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using PaySharp.Alipay.Response; using PaySharp.Core; using PaySharp.Core.Exceptions; using PaySharp.Core.Request; using PaySharp.Core.Response; using PaySharp.Core.Utils; namespace PaySharp.Alipay { internal static class SubmitProcess { private static string _gatewayUrl; internal static TResponse Execute(Merchant merchant, Request request, string gatewayUrl = null) where TResponse : IResponse { AddMerchant(merchant, request, gatewayUrl); var result = HttpUtil.Post(request.RequestUrl, request.GatewayData.ToUrl()); var jObject = JObject.Parse(result); var jToken = jObject.First.First; var sign = jObject.Value("sign"); if (!string.IsNullOrEmpty(sign) && !CheckSign( jToken.ToString(Formatting.None), sign, merchant.CertEnvironment == null ? merchant.AlipayPublicKey : merchant.CertEnvironment.GetAlipayPublicKey(jObject.Value("alipay_cert_sn")), merchant.SignType ) ) { throw new GatewayException("签名验证失败"); } var baseResponse = (BaseResponse)jToken.ToObject(typeof(TResponse)); baseResponse.Raw = result; baseResponse.Sign = sign; baseResponse.Execute(merchant, request); return (TResponse)(object)baseResponse; } internal static TResponse SdkExecute(Merchant merchant, Request request, string gatewayUrl) where TResponse : IResponse { AddMerchant(merchant, request, gatewayUrl); return (TResponse)Activator.CreateInstance(typeof(TResponse), request); } private static void AddMerchant(Merchant merchant, Request request, string gatewayUrl) where TResponse : IResponse { if (!string.IsNullOrEmpty(gatewayUrl)) { _gatewayUrl = gatewayUrl; } if (!request.RequestUrl.StartsWith("http")) { request.RequestUrl = _gatewayUrl + request.RequestUrl; } request.GatewayData.Add(merchant, StringCase.Snake); if (merchant.CertEnvironment != null) { request.GatewayData.Add("app_cert_sn", merchant.CertEnvironment.MerchantCertSN); request.GatewayData.Add("alipay_root_cert_sn", merchant.CertEnvironment.RootCertSN); } if (!string.IsNullOrEmpty(request.NotifyUrl)) { request.GatewayData.Add("notify_url", request.NotifyUrl); } if (!string.IsNullOrEmpty(request.ReturnUrl)) { request.GatewayData.Add("return_url", request.ReturnUrl); } request.GatewayData.Add("sign", BuildSign(request.GatewayData, merchant.Privatekey)); } internal static string BuildSign(GatewayData gatewayData, string privatekey) { gatewayData.Remove("sign"); return EncryptUtil.Sign(gatewayData.ToUrl(false), privatekey); } internal static bool CheckSign(string data, string sign, string alipayPublicKey, string signType) { return EncryptUtil.Verify(data, sign, alipayPublicKey); } } }