public AlipayOrderCreationResult GenerateAlipayPaymentUrl(AlipayOrderModel payment) { var payModel = new AlipayTradePayModel { Subject = payment.Subject, Body = payment.Body, OutTradeNo = payment.OrderNo, TotalAmount = payment.Amount.ToString("f2"), DisablePayChannels = payment.AllowCreditCard ? null : "credit_group", ProductCode = "FAST_INSTANT_TRADE_PAY" }; var wapPayRequest = new AlipayTradeWapPayRequest(); wapPayRequest.SetNotifyUrl(payment.NotifyUrl ?? _options.DefaultNotifyUrl); wapPayRequest.SetReturnUrl(payment.ReturnUrl); wapPayRequest.SetBizModel(payModel); var wapPayResponse = _alipay.SdkExecute(wapPayRequest); var pagePayRequest = new AlipayTradePagePayRequest(); pagePayRequest.SetNotifyUrl(payment.NotifyUrl ?? _options.DefaultNotifyUrl); pagePayRequest.SetReturnUrl(payment.ReturnUrl); pagePayRequest.SetBizModel(payModel); var pagePayResponse = _alipay.SdkExecute(pagePayRequest); return new AlipayOrderCreationResult { MobileWebPaymentUrl = _options.GatewayUrl + "?" + wapPayResponse.Body, DesktopPagePaymentUrl = _options.GatewayUrl + "?" + pagePayResponse.Body }; }
/// <summary> /// 生成APP支付订单信息 /// </summary> /// <returns></returns> public static string GetAlipayOrderInfo(decimal amount, string orderNumber) { IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", Config.APPID, Config.APP_PRIVATE_KEY, "json", "1.0", "RSA2", Config.ALIPAY_PUBLIC_KEY, Config.CHARSET, false); //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如:alipay.trade.app.pay AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); model.Body = "订单付款{0}".FormatWith(orderNumber); model.Subject = "五福天下商城订单付款"; model.TotalAmount = amount.ToString(); model.ProductCode = "QUICK_MSECURITY_PAY"; model.OutTradeNo = orderNumber; model.TimeoutExpress = "30m"; request.SetBizModel(model); request.SetNotifyUrl("http://m.wftx666.com"); //这里和普通的接口调用不同,使用的是sdkExecute AlipayTradeAppPayResponse response = client.SdkExecute(request); //HttpUtility.HtmlEncode是为了输出到页面时防止被浏览器将关键参数html转义,实际打印到日志以及http传输不会有这个问题 //return HttpUtility.HtmlEncode(response.Body); return(response.Body); //页面输出的response.Body就是orderString 可以直接给客户端请求,无需再做处理。 }
/// <summary> /// 生成RSA签名后的订单字符串,给客户端用的 /// </summary> /// <param name="body"></param> /// <param name="subject"></param> /// <param name="out_trade_no"></param> /// <param name="timeout_express"></param> /// <param name="total_amount"></param> /// <param name="product_code"></param> /// <param name="notify_url"></param> /// <returns></returns> public static string CreateRSASignedOrderString(string body, string subject, string out_trade_no, string timeout_express, string total_amount) { //从pem文件中读取 APP_PRIVATE_KEY = GetCurrentPathByAbs() + "rsa_private_key.pem"; ALIPAY_PUBLIC_KEY = GetCurrentPathByAbs() + "rsa_alipay_public_key.pem"; //最后一个参数为false直接将私钥内容写入代码,true从pem文件中读取 IAopClient client = new DefaultAopClient(gateway, APPID, APP_PRIVATE_KEY, format, version, sign_type, ALIPAY_PUBLIC_KEY, CHARSET, true); //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如:alipay.trade.app.pay AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); model.Body = body; model.Subject = subject; model.TotalAmount = total_amount; model.ProductCode = product_code; model.OutTradeNo = out_trade_no; model.TimeoutExpress = timeout_express; request.SetBizModel(model); request.SetNotifyUrl(notify_url); //这里和普通的接口调用不同,使用的是sdkExecute AlipayTradeAppPayResponse response = client.SdkExecute(request); string resp = response.Body; return(resp); }
public ActionResult AlipayOrder(string orderNo) { IAopClient client = new DefaultAopClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.APP_PRIVATE_KEY, "json", "1.0", "RSA", AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, true); ////实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如:alipay.trade.app.pay AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); model.Body = "我是测试数据"; model.Subject = "App支付测试DoNet"; model.TotalAmount = "0.01"; model.ProductCode = "QUICK_MSECURITY_PAY"; model.OutTradeNo = "sadfa" + DateTime.Now.ToString("yyyyMMddHHmmssfff"); // model.TimeoutExpress = "30m"; request.SetBizModel(model); request.SetNotifyUrl(AlipayConfig.NOTIFY_URL); //这里和普通的接口调用不同,使用的是sdkExecute AlipayTradeAppPayResponse response = client.SdkExecute(request); return(Json(new ResultMessage() { Code = 0, Msg = HttpUtility.HtmlEncode(response.Body) })); //HttpUtility.HtmlEncode是为了输出到页面时防止被浏览器将关键参数html转义,实际打印到日志以及http传输不会有这个问题 // Response.Write(HttpUtility.HtmlEncode(response.Body)); //log4netHelper.Info(string.Format("支付宝订单参数:{0}", HttpUtility.HtmlDecode(response.Body))); //bool flag = AlipaySignature.RSACheckV1(GetRequestPost(), AlipayConfig.APP_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA", false); //log4netHelper.Info(string.Format("验签结果:{0}", flag)); //return Json(new Result(0, HttpUtility.HtmlEncode(response.Body))); //页面输出的response.Body就是orderString 可以直接给客户端请求,无需再做处理。 }
public string appid = ConfigurationManager.AppSettings["aliAppId"];//应用2.0签约2017120190774565 #endregion /// <summary> /// .NET服务端SDK生成APP支付订单信息示例 /// </summary> /// //.NET服务端SDK生成APP支付订单信息示例(https://docs.open.alipay.com/54/106370/)根据文档上的说法,这样就行了。 /// <summary> /// 这个行了 /// </summary> /// <param name="totalAmount"></param> /// <param name="outTradeNo"></param> /// <param name="notifyUrl"></param> /// <returns></returns> public string CreateAlipayOrder(string totalAmount, string outTradeNo, string notifyUrl) { IAopClient client = new DefaultAopClient(gateway, appid, app_private_key, "json", "1.0", "RSA2", alipay_public_key, charset, false); //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如:alipay.trade.app.pay AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 request.SetApiVersion("1.0"); AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); model.Body = "body"; model.Subject = "App支付"; model.TotalAmount = totalAmount; model.ProductCode = "QUICK_MSECURITY_PAY"; //订单号 model.OutTradeNo = outTradeNo; model.TimeoutExpress = "30m"; request.SetBizModel(model); request.SetNotifyUrl(notifyUrl); //这里和普通的接口调用不同,使用的是sdkExecute AlipayTradeAppPayResponse response = client.SdkExecute(request); //HttpUtility.HtmlEncode是为了输出到页面时防止被浏览器将关键参数html转义,实际打印到日志以及http传输不会有这个问题 var a = response.Body; return(response.Body); //return HttpUtility.HtmlEncode(response.Body).Replace("&","&"); //Response.Write(HttpUtility.HtmlEncode(response.Body)); //页面输出的response.Body就是orderString 可以直接给客户端请求,无需再做处理。 }
public void PayRequest() { DefaultAopClient client = new DefaultAopClient(Gatewayurl, AppId, PrivateKey, "json", "2.0", SignType, AlipayPublicKey, CharSet, false); string tradeno = "1"; // 外部订单号,商户网站订单系统中唯一的订单号 // 组装业务参数model AlipayTradePagePayModel model = new AlipayTradePagePayModel(); model.Body = "商品描述"; // 商品描述 model.Subject = "订单名称"; // 订单名称 model.TotalAmount = "0.01"; // 付款金额 model.OutTradeNo = tradeno; // 外部订单号,商户网站订单系统中唯一的订单号 model.ProductCode = "FAST_INSTANT_TRADE_PAY"; AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 设置同步回调地址 request.SetReturnUrl("http://localhost:58616/Home/Callback"); // 设置异步通知接收地址 request.SetNotifyUrl("http://localhost:58616/Home/Notify"); // 将业务model载入到request request.SetBizModel(model); var response = client.SdkExecute(request); Console.WriteLine($"订单支付发起成功,订单号:{tradeno}"); //跳转支付宝支付 Response.Redirect(Gatewayurl + "?" + response.Body); }
/// <summary> /// 支付宝新版APP参数生成 /// </summary> /// <param name="orderNo">订单号</param> /// <param name="subject">订单标题</param> /// <param name="body">订单内容</param> /// <param name="payAmount">金额(元)</param> /// <param name="timeoutMinute">请求超时时间</param> /// <returns></returns> public string BuildAppParam(string orderNo, string subject, string body, decimal payAmount, int timeoutMinute) { var appId = System.Configuration.ConfigurationManager.AppSettings["ALIPAY_APPID"]; var privatePem = System.Configuration.ConfigurationManager.AppSettings["ALIPay_RSA2_PRIVATEKEY"]; var aliPublishPem = System.Configuration.ConfigurationManager.AppSettings["ALIPay_RSA2_ALI_PUBLICKEY"]; IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", appId, privatePem, "json", "1.0", "RSA2", aliPublishPem, "utf-8", false);//改成RSA,方便异步回调验签 AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); model.Body = body; model.Subject = subject; model.TotalAmount = payAmount.ToString("0.00"); model.ProductCode = "QUICK_MSECURITY_PAY"; model.OutTradeNo = orderNo; model.TimeoutExpress = timeoutMinute + "m"; request.SetBizModel(model); request.SetNotifyUrl(System.Configuration.ConfigurationManager.AppSettings["ALIPay_NotifyURL"]); //这里和普通的接口调用不同,使用的是sdkExecute AlipayTradeAppPayResponse response = client.SdkExecute(request); if (response != null && !response.IsError) { return(response.Body); } else { return("error"); } }
public void PayRequest(JObject json) { var commdy = new vw_MallOrderInfo(); //using (var db = new RepositoryBase(DBFactory.Bayetech)) //{ // vw_MallOrderInfo order = JsonConvert.DeserializeObject<vw_MallOrderInfo>(json.First.Path); // commdy = db.FindEntity<vw_MallOrderInfo>(a => a.OrderNo == order.OrderNo); //} AlipayTradePagePayModel model = new AlipayTradePagePayModel { Body = "eshi", Subject = commdy.GameName, TotalAmount = commdy.OrderPrice.ToString(), OutTradeNo = commdy.OrderNo, ProductCode = "FAST_INSTANT_TRADE_PAY" }; AliPayConfig alipay = new AliPayConfig(); DefaultAopClient clent = new DefaultAopClient(alipay.Gatewayurl, alipay.AppId, alipay.PrivateKey, "json", "1.0", alipay.SignType, alipay.AlipayPublicKey, alipay.CharSet, false); AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 设置同步回调地址 request.SetReturnUrl($"http://{GetCurrentFullHost()}/Home/Callback"); // 设置异步通知接收地址 request.SetNotifyUrl(""); // 将业务model载入到request request.SetBizModel(model); var response = clent.SdkExecute(request); //Console.WriteLine($"订单支付发起成功,订单号:{tradeno}"); //跳转支付宝支付 Response.Redirect(alipay.Gatewayurl + "?" + response.Body); }
public void PayRequest(string tradeno, string subject, string totalAmout, string itemBody) { DefaultAopClient client = new DefaultAopClient(Config.Gatewayurl, Config.AppId, Config.PrivateKey, "json", "2.0", Config.SignType, Config.AlipayPublicKey, Config.CharSet, false); // 组装业务参数model AlipayTradePagePayModel model = new AlipayTradePagePayModel(); model.Body = itemBody; model.Subject = subject; model.TotalAmount = totalAmout; model.OutTradeNo = tradeno; model.ProductCode = "FAST_INSTANT_TRADE_PAY"; AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 设置同步回调地址 request.SetReturnUrl("http://localhost:5003/Pay/Callback"); // 设置异步通知接收地址 request.SetNotifyUrl(""); // 将业务model载入到request request.SetBizModel(model); var response = client.SdkExecute(request); Console.WriteLine($"订单支付发起成功,订单号:{tradeno}"); //跳转支付宝支付 Response.Redirect(Config.Gatewayurl + "?" + response.Body); }
public ApiMessage <string> Alipay(PayModel pm) { var api = new ApiMessage <string>(); IAopClient client = new DefaultAopClient(URL, APPID, APP_PRIVATE_KEY, "json", "1.0", RSA2, ALIPAY_PUBLIC_KEY, CHARSET, false); AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); var res = bll.CkeckData(pm, UserInfo); if (!res.Success) { api.Success = false; api.Msg = res.Msg; return(api); } var oData = res.Data; model.Body = oData.Body; model.Subject = oData.Subject; model.TotalAmount = oData.TotalAmount.ToString(); model.ProductCode = "QUICK_MSECURITY_PAY"; model.OutTradeNo = oData.OutTradeNo; AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); request.SetBizModel(model); request.SetNotifyUrl(ConfigHelper.WebSiteUrl + "/api/payment/updateorder/alipay"); AlipayTradeAppPayResponse response = client.SdkExecute(request); api.Data = response.Body; return(api); }
public object getAliMiniAppPaySign(Dictionary <string, object> dicParas) { try { int coins = 0; string orderNo = string.Empty; string errMsg = string.Empty; string mobileToken = dicParas.ContainsKey("mobileToken") ? dicParas["mobileToken"].ToString() : string.Empty; string storeId = dicParas.ContainsKey("storeId") ? dicParas["storeId"].ToString() : string.Empty; string productName = dicParas.ContainsKey("productName") ? dicParas["productName"].ToString() : string.Empty; string payPriceStr = dicParas.ContainsKey("payPrice") ? dicParas["payPrice"].ToString() : string.Empty; string buyType = dicParas.ContainsKey("buyType") ? dicParas["buyType"].ToString() : string.Empty; string coinsStr = dicParas.ContainsKey("coins") ? dicParas["coins"].ToString() : string.Empty; decimal payPrice = 0; if (!decimal.TryParse(payPriceStr, out payPrice)) { return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付金额不正确")); } if (!int.TryParse(coinsStr, out coins)) { return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "购买币数不正确")); } MobileTokenModel mobileTokenModel = (MobileTokenModel)(dicParas[Constant.MobileTokenModel]); //生成服务器订单号 orderNo = PayOrderHelper.CreateXCGameOrderNo(storeId, payPrice, 0, (int)(OrderType.Ali), productName, mobileTokenModel.Mobile, buyType, coins); IAopClient client = new DefaultAopClient(AliPayConfig.serverUrl, AliPayConfig.miniAppId, AliPayConfig.merchant_miniapp_private_key, "json", "1.0", "RSA2", AliPayConfig.alipay_miniapp_public_key, AliPayConfig.charset, false); AlipayTradeAppPayModel builder = new AlipayTradeAppPayModel(); builder.Body = "莘拍档-" + buyType; builder.Subject = productName; builder.OutTradeNo = orderNo; builder.TotalAmount = payPrice.ToString("0.00"); builder.ProductCode = "QUICK_MSECURITY_PAY"; builder.TimeoutExpress = "10m"; AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); request.SetBizModel(builder); request.SetNotifyUrl(AliPayConfig.AliMiniAppNotify_url); AlipayTradeAppPayResponse response = client.SdkExecute(request); //string strSign = HttpUtility.HtmlEncode(response.Body); AlipayMiniAppSignModel model = new AlipayMiniAppSignModel(); model.OrderId = orderNo; model.PaySign = response.Body; return(ResponseModelFactory <AlipayMiniAppSignModel> .CreateModel(isSignKeyReturn, model)); } catch (Exception e) { throw e; } }
public void should_return_order_string_with_correct_order_of_parameters() { IAopClient client = new DefaultAopClient(TestAccount.Sandbox.Gateway, TestAccount.Sandbox.AppId, TestAccount.Sandbox.AppPrivateKey, "json", "1.0", "RSA2", TestAccount.Sandbox.AlipayPublicKey, "utf-8", false); ParameterCaseMixingRequest request = new ParameterCaseMixingRequest(); AlipayTradeAppPayResponse response = client.SdkExecute(request); String orderString = response.Body; //大写字符必须在小写字符前面 Assert.AreEqual(orderString.Contains("A=test&a=test"), true); }
public ActionResult GeneralPayParamByChongZhi(int User_ID, decimal FinishPrice) { try { if (User_ID <= 0) { return(FailNoLogin()); } string appid = CheckAPPID(); if (FinishPrice < 1) { throw new Exception("充值金额最小为1元"); } dm_basesettingEntity dm_BasesettingEntity = dM_BaseSettingIBLL.GetEntityByCache(appid); if (dm_BasesettingEntity == null) { return(Fail("基础配置获取失败!")); } //FinishPrice = 0.01M;//测试支付金额为0.01 string out_trade_no = DateTime.Now.ToString("yyyyMMddHHmmssfff") + User_ID.ToString().PadLeft(6, '0'); IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", dm_BasesettingEntity.alipay_appid, dm_BasesettingEntity.merchant_private_key, "json", "1.0", "RSA2", "utf-8", false, AliPayHelper.GetCertParams(dm_BasesettingEntity.alipay_appid, base.Server)); //IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", dm_BasesettingEntity.alipay_appid, dm_BasesettingEntity.merchant_private_key, "json", "1.0", "RSA2", dm_BasesettingEntity.alipay_public_key, "GBK", false); AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); request.SetNotifyUrl(dm_BasesettingEntity.alipay_notifyurl); request.SetReturnUrl(dm_BasesettingEntity.alipay_notifyurl); request.BizContent = GetBizContent1(User_ID, 99, "余额充值", FinishPrice, out_trade_no); AlipayTradeAppPayResponse response = client.SdkExecute(request); dm_alipay_recordEntity dm_Alipay_RecordEntity = new dm_alipay_recordEntity(); dm_Alipay_RecordEntity.user_id = User_ID; dm_Alipay_RecordEntity.total_amount = FinishPrice; dm_Alipay_RecordEntity.templateid = 99; dm_Alipay_RecordEntity.subject = "余额充值"; dm_Alipay_RecordEntity.out_trade_no = out_trade_no; dM_Alipay_RecordIBLL.SaveEntity(0, dm_Alipay_RecordEntity); return(Success("支付参数获取成功!", new { PayParam = response.Body })); } catch (Exception ex) { return(FailException(ex)); } }
/// <summary> /// 生成支付参数 /// </summary> /// <param name="user_id">用户ID</param> /// <param name="PackageType">套餐ID 1初级代理 2高级代理 3升级代理</param> /// <returns></returns> // GET: A_Pay public ActionResult GeneralPayParam(int user_id, int TemplateID) { try { string appid = CheckAPPID(); if (TemplateID <= 0) { return(Fail("套餐信息异常!")); } dm_alipay_templateEntity dm_Alipay_TemplateEntity = dM_Alipay_TemplateIBLL.GetEntityByCache(TemplateID, appid); if (dm_Alipay_TemplateEntity.IsEmpty()) { return(Fail("套餐信息异常!")); } dm_basesettingEntity dm_BasesettingEntity = dM_BaseSettingIBLL.GetEntityByCache(appid); if (dm_BasesettingEntity == null) { return(Fail("基础配置获取失败!")); } string out_trade_no = DateTime.Now.ToString("yyyyMMddHHmmssfff") + user_id.ToString().PadLeft(6, '0'); IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", dm_BasesettingEntity.alipay_appid, dm_BasesettingEntity.merchant_private_key, "json", "1.0", "RSA2", "utf-8", false, AliPayHelper.GetCertParams(dm_BasesettingEntity.alipay_appid, base.Server)); //IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", dm_BasesettingEntity.alipay_appid, dm_BasesettingEntity.merchant_private_key, "json", "1.0", "RSA2", dm_BasesettingEntity.alipay_public_key, "GBK", false); AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); request.SetNotifyUrl(dm_BasesettingEntity.alipay_notifyurl); request.SetReturnUrl(dm_BasesettingEntity.alipay_notifyurl); request.BizContent = GetBizContent1(user_id, TemplateID, dm_Alipay_TemplateEntity.name, dm_Alipay_TemplateEntity.finishprice, out_trade_no); AlipayTradeAppPayResponse response = client.SdkExecute(request); dm_alipay_recordEntity dm_Alipay_RecordEntity = new dm_alipay_recordEntity(); dm_Alipay_RecordEntity.user_id = user_id; dm_Alipay_RecordEntity.total_amount = dm_Alipay_TemplateEntity.finishprice; dm_Alipay_RecordEntity.templateid = TemplateID; dm_Alipay_RecordEntity.subject = dm_Alipay_TemplateEntity.name; dm_Alipay_RecordEntity.out_trade_no = out_trade_no; dM_Alipay_RecordIBLL.SaveEntity(0, dm_Alipay_RecordEntity); return(Success("支付参数获取成功!", new { PayParam = response.Body })); } catch (Exception ex) { return(FailException(ex)); } }
/// <summary> /// 获取APP支付宝支付订单参数 /// </summary> /// <param name="orderCode">平台订单号</param> /// <param name="money">金额</param> /// <param name="timeOut">订单支付超时时间</param> /// <returns></returns> private ApiResultModel <string> GetAppAliPayParam(string orderCode, decimal money, int?timeOut) { IAopClient client = new DefaultAopClient(AliPayConfig.gatewayUrl, AliPayConfig.AppId, AliPayConfig.privatekey, "json", "1.0", AliPayConfig.sign_type, AliPayConfig.alipublickey, AliPayConfig.charset, false); //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如:alipay.trade.app.pay AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel pmodel = new AlipayTradeAppPayModel { Subject = Subject, TotalAmount = decimal.Round(money, 2).ToString("f2"), ProductCode = "QUICK_MSECURITY_PAY", OutTradeNo = orderCode, // TimeoutExpress = "30m" TimeoutExpress = (timeOut ?? PayTimeOut).ToString() + "m", }; request.SetBizModel(pmodel); request.SetNotifyUrl(NotifyUrl); //这里和普通的接口调用不同,使用的是sdkExecute AlipayTradeAppPayResponse response = null; var reqTime = DateTime.Now; //HttpUtility.HtmlEncode是为了输出到页面时防止被浏览器将关键参数html转义,实际打印到日志以及http传输不会有这个问题 try { response = client.SdkExecute(request); //记录支付宝调用的日志 //WritePostThirdApi(ThirdPlatformBusinessType.Payment, orderCode, ThirdPlatformType.Alipay, AliPayConfig.gatewayUrl, request.ToJsonString(), reqTime, response.Body, DateTime.Now, true); } catch (Exception ex) { //LogHelper.LogError("提交支付宝预付款订单 SubmitPay", ex.ToString()); ////记录支付宝调用的日志 //WritePostThirdApi(ThirdPlatformBusinessType.Payment, orderCode, ThirdPlatformType.Alipay, AliPayConfig.gatewayUrl, request.ToJsonString(), reqTime, // response.IsNull() ? ex.ToString() : response.Body, DateTime.Now, true); } var res = new ApiResultModel <string>() { Code = ApiResultCode.Success, Message = response.Body }; return(res); }
public IHttpActionResult kkk(dynamic data) { IAopClient client = new DefaultAopClient(URL, APPID, APP_PRIVATE_KEY, FORMAT, "2.0", "RSA2", ALIPAY_PUBLIC_KEY, CHARSET, false); // 商户订单号,和交易号不能同时为空 string out_trade_no = "20200709104925"; // 支付宝交易号,和商户订单号不能同时为空 string trade_no = "2020070922001450210500981173"; // 退款金额,不能大于订单总金额 string refund_amount = "110.00"; // 退款原因 string refund_reason = "我就是想退款"; // 退款单号,同一笔多次退款需要保证唯一,部分退款该参数必填。 string out_request_no = "16541"; AlipayTradeRefundModel model = new AlipayTradeRefundModel(); model.OutTradeNo = data.data.OutTradeNo; model.TradeNo = data.data.TradeNo; model.RefundAmount = data.data.RefundAmount; model.RefundReason = data.data.RefundReason; model.OutRequestNo = DateTime.Now.ToString("yyyyMMddHHmmss"); AlipayTradeRefundRequest request = new AlipayTradeRefundRequest(); request.SetBizModel(model); AlipayTradeRefundResponse response = null; response = client.SdkExecute(request); using (SmartRentalSystemEntities db = new SmartRentalSystemEntities()) { var ode = db.Order.Where(t => t.OrderNumber == model.OutTradeNo).ToList().FirstOrDefault(); ode.OrderState = "退款"; db.SaveChanges(); } //Execute(request); return(Ok(response.Body)); }
public ActionResult Show(Order order) { IAopClient client = new DefaultAopClient(URL, APPID, APP_PRIVATE_KEY, FORMAT, "2.0", "RSA2", ALIPAY_PUBLIC_KEY, CHARSET, false); //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如: AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest(); //创建API对应的request类,请求返回二维码 AlipayTradePagePayRequest requestPagePay = new AlipayTradePagePayRequest(); //请求返回支付宝支付网页 AlipayTradePagePayModel model = new AlipayTradePagePayModel(); //主要注意的是这个地方的值 model.Body = order.GoodsMs; model.Subject = order.OrderName; model.TotalAmount = order.Count; model.OutTradeNo = DateTime.Now.ToString("yyyyMMddHHmmss");;//订单号我们是直接用日期产生的 model.StoreId = "William001"; model.ProductCode = "FAST_INSTANT_TRADE_PAY"; requestPagePay.SetBizModel(model); //这是要注意的,支付后就要通过他完成回调,这里填写你要跳转页面的地址 requestPagePay.SetReturnUrl("http://47.106.255.80:8080/Snail/#/OrderDetailss"); var response = client.SdkExecute(requestPagePay);//Execute(request); if (!response.IsError) { var res = new { success = true, out_trade_no = response.OutTradeNo, // qr_code = response.QrCode, //二维码字符串 pay_url = URL + "?" + response.Body }; return(Json(res)); } else { var res = new { success = false, }; return(Json(res)); } }
public JObject PayOrder(JObject json) { JObject ret = new JObject(); var commdy = new vw_MallOrderInfo(); using (var db = new RepositoryBase(DBFactory.Bayetech)) { vw_MallOrderInfo order = JsonConvert.DeserializeObject <vw_MallOrderInfo>(json.First.Path); commdy = db.FindEntity <vw_MallOrderInfo>(a => a.OrderNo == order.OrderNo); } AlipayTradePagePayModel model = new AlipayTradePagePayModel { Body = commdy.GoodTitle, Subject = commdy.GameName, TotalAmount = commdy.OrderPrice.ToString(), OutTradeNo = commdy.OrderNo, ProductCode = "FAST_INSTANT_TRADE_PAY" }; AliPayConfig alipay = new AliPayConfig(); DefaultAopClient clent = new DefaultAopClient(alipay.Gatewayurl, alipay.AppId, alipay.PrivateKey, "json", "1.0", alipay.SignType, alipay.AlipayPublicKey, alipay.CharSet, false); AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 设置同步回调地址 request.SetReturnUrl($"http://{Common.GetCurrentFullHost()}/Home/Callback"); // 设置异步通知接收地址 request.SetNotifyUrl(""); // 将业务model载入到request request.SetBizModel(model); var response = clent.SdkExecute(request); //Console.WriteLine($"订单支付发起成功,订单号:{tradeno}"); //跳转支付宝支付 //HttpContext.Current.Response.Redirect(alipay.Gatewayurl + "?" + response.Body); //HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.Moved); //resp.Headers.Location = new Uri(alipay.Gatewayurl + "?" + response.Body); string resp = alipay.Gatewayurl + "?" + response.Body; ret.Add(ResultInfo.Result, true); ret.Add(ResultInfo.Content, JToken.FromObject(resp)); return(ret); }
/// <summary> /// 创建Sdk支付链接串(蚂蚁金服) /// </summary> /// <param name="directInfo">支付信息</param> /// <param name="config">config</param> /// <returns>请求连接</returns> public static string CreateDirectSdkPayByUser(DirectInfo directInfo, SdkPay.Config config) { const string url = SdkPay.Config.ServerUrl; string appId = config.GetAppId(); string privateKeyPem = config.GetPrivateKeyPem(); const string format = SdkPay.Config.Format; const string version = SdkPay.Config.Version; const string signType = SdkPay.Config.SignType; string publicKeyPem = config.GetPublicKeyPem(); const string charset = SdkPay.Config.Charset; const string productCode = SdkPay.Config.ProductCode; string pid = config.GetPid(); IAopClient client = new DefaultAopClient(url, appId, privateKeyPem, format, version, signType, publicKeyPem, charset, false); AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); if (!string.IsNullOrWhiteSpace(directInfo.Notify)) { request.SetNotifyUrl(directInfo.Notify); } if (!string.IsNullOrWhiteSpace(directInfo.Return)) { request.SetReturnUrl(directInfo.Return); } AlipayTradeAppPayModel model = new AlipayTradeAppPayModel { Body = directInfo.ExtraCommonParam, Subject = directInfo.Subject, TotalAmount = directInfo.TotalFee.ToString("0.00"), ProductCode = productCode, OutTradeNo = directInfo.OutTradeNo, TimeoutExpress = "30m", SellerId = pid }; request.SetBizModel(model); AlipayTradeAppPayResponse response = client.SdkExecute(request); var body = response.Body; return(body); }
public string GeneratePayInfo(string subject, string totalAmount) { var config = ConfigUtil.GetConfig <DataApiAppSettings>("AppSettings"); IAopClient client = new DefaultAopClient(config.AlipayServer, config.AlipayAppId, config.AlipayPrivateKey, "json", "1.0", "RSA2", config.AlipayPublicKey, "UTF-8", false); //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如:alipay.trade.app.pay AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); model.Body = "惠及万家支付"; model.Subject = subject; model.TotalAmount = totalAmount; model.ProductCode = "QUICK_MSECURITY_PAY"; model.OutTradeNo = PrimaryKey.Current.ID.ToString(); model.TimeoutExpress = "30m"; request.SetBizModel(model); request.SetNotifyUrl(config.AlipayNotifyUrl); //这里和普通的接口调用不同,使用的是sdkExecute AlipayTradeAppPayResponse response = client.SdkExecute(request); return(response.Body); }
public ApiResult GetZfbInfo(int money) { var zFBResDto = new ZFBResDto(); zFBResDto.OrderId = GetRandom(); if (_service.AddComeOutRecord(zFBResDto.OrderId, money, 2, (int)this.UserInfo.UserId)) { notifyUrl = ApiHost + "/api/Recharge/AsyncPay"; LogHelper.Info("notifyUrl=" + notifyUrl); IAopClient client = new DefaultAopClient(apiUrl, app_id, merchant_private_key, format, version, sign_type, alipay_public_key, charset, false); //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如:alipay.trade.app.pay AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); model.Body = "金币充值"; model.Subject = "金币充值"; model.TotalAmount = money.ToString(); model.ProductCode = "QUICK_MSECURITY_PAY"; model.OutTradeNo = zFBResDto.OrderId; model.TimeoutExpress = "5m"; request.SetBizModel(model); request.SetNotifyUrl(notifyUrl); //这里和普通的接口调用不同,使用的是sdkExecute AlipayTradeAppPayResponse response = client.SdkExecute(request); //页面输出的response.Body就是orderString 可以直接给客户端请求,无需再做处理。 zFBResDto.ResponseBody = response.Body; //HttpUtility.HtmlEncode是为了输出到页面时防止被浏览器将关键参数html转义,实际打印到日志以及http传输不会有这个问题 var result = new ApiResult <ZFBResDto>(); result.Data = zFBResDto; return(result); } else { return(new ApiResult(10000, "生成订单失败")); } }
public void should_return_correct_signed_order_string() { IAopClient client = new DefaultAopClient(TestAccount.Sandbox.Gateway, TestAccount.Sandbox.AppId, TestAccount.Sandbox.AppPrivateKey, "json", "1.0", "RSA2", TestAccount.Sandbox.AlipayPublicKey, "utf-8", false); AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); model.Body = "我是测试数据"; model.Subject = "App支付测试DoNet"; model.TotalAmount = "0.01"; model.ProductCode = "QUICK_MSECURITY_PAY"; model.OutTradeNo = "20170216test01"; model.TimeoutExpress = "30m"; request.SetBizModel(model); request.SetNotifyUrl("http://www.test.notify"); AlipayTradeAppPayResponse response = client.SdkExecute(request); String orderString = response.Body; // 必须拥有正确的签名串 Assert.AreEqual(orderString.Contains("&sign="), true); }
public void ProcessRequest(HttpContext context) { HttpRequest req = context.Request; Stream stream = req.InputStream; if (stream.Length != 0) { var OutTradeNo = req["out_trade_no"]; var TotalAmount = req["total_fee"]; string APPID = AlipayConstants.app_id; string APP_PRIVATE_KEY = AlipayConstants.private_key; string ALIPAY_PUBLIC_KEY = AlipayConstants.alipay_public_key; string CHARSET = "utf-8"; IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", APPID, APP_PRIVATE_KEY, "json", "1.0", "RSA", ALIPAY_PUBLIC_KEY, CHARSET, false); AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); model.Body = "微特众包-商家充值"; model.Subject = "微特众包-商家充值"; model.TotalAmount = TotalAmount; model.ProductCode = "1"; model.OutTradeNo = OutTradeNo; model.TimeoutExpress = "30m"; request.SetNotifyUrl(AlipayConstants.notify_url); request.SetBizModel(model); //这里和普通的接口调用不同,使用的是sdkExecute AlipayTradeAppPayResponse response = client.SdkExecute(request); //HttpUtility.HtmlEncode是为了输出到页面时防止被浏览器将关键参数html转义,实际打印到日志以及http传输不会有这个问题 context.Response.Write(HttpUtility.HtmlEncode(response.Body)); //context.Response.Write(response.Body); //页面输出的response.Body就是orderString 可以直接给客户端请求,无需再做处理。 } else { context.Response.Write(""); } }
private static readonly string AlipayPublicKey = AliPayConfig.AlipayPublicKey; //支付宝公钥 /// <summary> /// 签名订单 /// </summary> /// <param name="body">订单描述</param> /// <param name="subject">商品标题</param> /// <param name="totalAmount">订单总金额</param> /// <param name="outTradeNo">订单号</param> /// <param name="passbackParams">公共回传参数</param> /// <returns>签名</returns> public static string Signature(string body, string subject, string totalAmount, string outTradeNo, string passbackParams) { IAopClient client = new DefaultAopClient(ServerUrl, AppId, AppPrivateKey, "json", "1.0", SignType, AlipayPublicKey, Charset, false); //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如:alipay.trade.app.pay AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel almodel = new AlipayTradeAppPayModel(); almodel.Body = body; almodel.Subject = subject; almodel.TotalAmount = String.Format("{0:0.00}", totalAmount); almodel.ProductCode = "QUICK_MSECURITY_PAY"; almodel.OutTradeNo = outTradeNo; almodel.TimeoutExpress = "30m"; almodel.PassbackParams = System.Web.HttpUtility.UrlEncode(passbackParams); request.SetBizModel(almodel); request.SetNotifyUrl(NotifyUrl); //这里和普通的接口调用不同,使用的是sdkExecute AlipayTradeAppPayResponse response = client.SdkExecute(request); //HttpUtility.HtmlEncode是为了输出到页面时防止被浏览器将关键参数html转义,实际打印到日志以及http传输不会有这个问题 return(response.Body); //页面输出的response.Body就是orderString 可以直接给客户端请求,无需再做处理。 }
/// <summary> /// app支付 /// </summary> /// <param name="orderName">订单名称</param> /// <param name="orderAmount">订单金额</param> /// <param name="outTradeNo">订单号</param> /// <returns></returns> public ActionResult ScanCodeGen(string orderName, string orderAmount, string outTradeNo) { IAopClient client = new DefaultAopClient(Config.gatewayUrl, Config.app_id, Config.private_key, "json", "1.0", "RSA2", Config.alipay_public_key, "utf-8", false); //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如:alipay.trade.app.pay AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); model.Body = "我是测试数据"; model.Subject = orderName; model.TotalAmount = orderAmount; model.ProductCode = "QUICK_MSECURITY_PAY"; model.OutTradeNo = "20170216test01"; model.TimeoutExpress = "30m"; request.SetBizModel(model); request.SetNotifyUrl("http://19171zn332.imwork.net:22070/AppPay/Notify"); //这里和普通的接口调用不同,使用的是sdkExecute AlipayTradeAppPayResponse response = client.SdkExecute(request); //HttpUtility.HtmlEncode是为了输出到页面时防止被浏览器将关键参数html转义,实际打印到日志以及http传输不会有这个问题 // Response.Write(HttpUtility.HtmlEncode(response.Body)); //页面输出的response.Body就是orderString 可以直接给客户端请求,无需再做处理。 return(Json(response.Body)); }
public ActionResult PayRequest(string tradeno, string subject, string totalAmout, string itemBody) { DefaultAopClient client = new DefaultAopClient(Config.Gatewayurl, Config.AppId, Config.PrivateKey, "json", "2.0", Config.SignType, Config.AlipayPublicKey, Config.CharSet, false); // 组装业务参数model AlipayTradePagePayModel model = new AlipayTradePagePayModel(); model.Body = itemBody; model.Subject = subject; model.TotalAmount = totalAmout; model.OutTradeNo = tradeno; model.ProductCode = "FAST_INSTANT_TRADE_PAY"; AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 设置同步回调地址 request.SetReturnUrl("http://localhost:8013/Pay/Callback"); // 设置异步通知接收地址 request.SetNotifyUrl(""); // 将业务model载入到request request.SetBizModel(model); AlipayTradePagePayResponse response = null; try { response = client.SdkExecute(request); Response.Redirect(Config.Gatewayurl + "?" + response.Body); return(JavaScript(string.Format($"订单支付发起成功,订单号:{0}", tradeno))); } catch (Exception exp) { throw exp; } }
public Return AliPay(AliPayPicture payModel) { var resultReturn = new Return(); var orderId = Guid.NewGuid().ToString(); var countAmout = payModel.Description * Convert.ToDecimal( System.Configuration.ConfigurationManager.AppSettings["PicturePrice"]); //连接数据库 var conn = new SqlConnection(@"server=47.106.183.2,1433;database=Picture;user id=sa;password=BigMaster@2018"); conn.Open(); SqlCommand sqlcmd = new SqlCommand(); sqlcmd.CommandText = "select * from WhiteList where androidId = '" + payModel.Phone + "' and isUseful=1"; sqlcmd.Connection = conn; SqlDataAdapter adp = new SqlDataAdapter(sqlcmd); DataTable dt = new DataTable(); adp.Fill(dt); if (dt.Rows.Count == 0) {//白名单用户可跳过价格监测 if (countAmout < 298 && payModel.Amout != countAmout) { resultReturn.Content = "订单支付失败,因为价格输入错误!"; return(resultReturn); } } else //白名单用户价格特殊 { payModel.Amout = Convert.ToDecimal(dt.Rows[0]["price"].ToString()); } try { var aopClient = new DefaultAopClient(AliPayConfig.GatewayUrl, AliPayConfig.AppId, AliPayConfig.PrivateKey, "json", "1.0", AliPayConfig.SignType, AliPayConfig.AlipayPublicKey, AliPayConfig.Charset, false); //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如:alipay.trade.app.pay var request = new AlipayTradeAppPayRequest(); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 var model = new AlipayTradeAppPayModel { Body = payModel.Body, //描述 Subject = payModel.Subject, //标题 TotalAmount = payModel.Amout.ToString(CultureInfo.InvariantCulture), //订单金额 ProductCode = "QUICK_MSECURITY_PAY", OutTradeNo = orderId //商户网站唯一订单号 }; request.SetBizModel(model); request.SetNotifyUrl(AliPayConfig.PictureNotifyUrl); var response = aopClient.SdkExecute(request); var resultDic = new Dictionary <string, object> { { "OrderId", orderId }, { "content", response.Body } }; resultReturn.Content = resultDic; //查询 //AlipayTradeQueryRequest request2 = new AlipayTradeQueryRequest();//创建API对应的request类 //var model2 = new AlipayTradeAppPayModel //{ // OutTradeNo = orderId, //标题 //}; //request2.SetBizModel(model2); //AlipayTradeQueryResponse response2 = aopClient.Execute(request2);//通过alipayClient调用API,获得对应的response类 var sqlCmd = conn.CreateCommand(); sqlCmd.CommandText = "INSERT INTO A (Id,Price,Number,FilePath,Phone,Response) VALUES ('" + orderId + "','" + payModel.Amout + "','" + payModel.Description + "','" + payModel.FilePath + "','" + payModel.Phone + "','" + response.Body + "');"; sqlCmd.ExecuteNonQuery(); conn.Close(); sqlCmd.Dispose(); } catch (AopException aopEx) { LogService.InsertLog(aopEx); resultReturn.SetWrong(); } return(resultReturn); }
/// <summary> /// 生成支付参数 /// </summary> /// <param name="user_id">用户ID</param> /// <param name="PackageType">套餐ID 1初级代理 2高级代理 3升级代理</param> /// <returns></returns> // GET: A_Pay public ActionResult GeneralPayParam(int user_id, int TemplateID) { try { string appid = CheckAPPID(); if (TemplateID <= 0) { return(Fail("套餐信息异常!")); } dm_alipay_templateEntity dm_Alipay_TemplateEntity = dM_Alipay_TemplateIBLL.GetEntityByCache(TemplateID, appid); if (dm_Alipay_TemplateEntity.IsEmpty()) { return(Fail("套餐信息异常!")); } dm_basesettingEntity dm_BasesettingEntity = dM_BaseSettingIBLL.GetEntityByCache(appid); if (dm_BasesettingEntity == null) { return(Fail("基础配置获取失败!")); } string out_trade_no = DateTime.Now.ToString("yyyyMMddHHmmssfff") + user_id.ToString().PadLeft(6, '0'); IAopClient client = new DefaultAopClient("https://openapi.alipaydev.com/gateway.do", dm_BasesettingEntity.alipay_appid, dm_BasesettingEntity.merchant_private_key, "json", "1.0", "RSA2", dm_BasesettingEntity.alipay_public_key, "GBK", false); AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); request.SetNotifyUrl(dm_BasesettingEntity.alipay_notifyurl); request.SetReturnUrl(dm_BasesettingEntity.alipay_notifyurl); request.BizContent = "{" + "\"timeout_express\":\"90m\"," + "\"total_amount\":\"" + dm_Alipay_TemplateEntity.finishprice + "\"," + "\"product_code\":\"QUICK_MSECURITY_PAY\"," + "\"body\":\"" + dm_Alipay_TemplateEntity.name + "\"," + "\"subject\":\"" + dm_Alipay_TemplateEntity.name + "\"," + "\"out_trade_no\":\"" + out_trade_no + "\"," + "\"time_expire\":\"" + DateTime.Now.AddMinutes(30).ToString("yyyy-MM-dd HH:mm:ss") + "\"," + "\"goods_type\":\"1\"," + //"\"promo_params\":\"{\\\"storeIdType\\\":\\\"1\\\"}\"," + "\"passback_params\":\"" + HttpUtility.UrlEncode(dm_Alipay_TemplateEntity.name) + "\"," + "\"extend_params\":{" + "\"sys_service_provider_id\":\"" + user_id + "\"," + "\"hb_fq_num\":\"3\"," + "\"hb_fq_seller_percent\":\"100\"," + "\"industry_reflux_info\":\"{\\\\\\\"scene_code\\\\\\\":\\\\\\\"metro_tradeorder\\\\\\\",\\\\\\\"channel\\\\\\\":\\\\\\\"xxxx\\\\\\\",\\\\\\\"scene_data\\\\\\\":{\\\\\\\"asset_name\\\\\\\":\\\\\\\"ALIPAY\\\\\\\"}}\"," + "\"card_type\":\"S0JP0000\"" + " }," + "\"merchant_order_no\":\"20201008001\"," + "\"enable_pay_channels\":\"pcredit,moneyFund,debitCardExpress\"," + "\"store_id\":\"NJ_001\"," + "\"specified_channel\":\"pcredit\"," + "\"disable_pay_channels\":\"pcredit,moneyFund,debitCardExpress\"," + " \"goods_detail\":[{" + " \"goods_id\":\"" + TemplateID + "\"," + "\"alipay_goods_id\":\"20010001\"," + "\"goods_name\":\"" + dm_Alipay_TemplateEntity.name + "\"," + "\"quantity\":1," + "\"price\":2000," + "\"goods_category\":\"34543238\"," + "\"categories_tree\":\"124868003|126232002|126252004\"," + "\"body\":\"" + dm_Alipay_TemplateEntity.name + "\"," + "\"show_url\":\"http://www.alipay.com/xxx.jpg\"" + " }]," + "\"ext_user_info\":{" + "\"name\":\"" + dm_Alipay_TemplateEntity.name + "\"," + "\"mobile\":\"16587658765\"," + "\"cert_type\":\"IDENTITY_CARD\"," + "\"cert_no\":\"362334768769238881\"," + "\"min_age\":\"18\"," + "\"fix_buyer\":\"F\"," + "\"need_check_info\":\"F\"" + " }," + "\"business_params\":\"{\\\"data\\\":\\\"123\\\"}\"," + "\"agreement_sign_params\":{" + "\"personal_product_code\":\"CYCLE_PAY_AUTH_P\"," + "\"sign_scene\":\"INDUSTRY|DIGITAL_MEDIA\"," + "\"external_agreement_no\":\"test20190701\"," + "\"external_logon_id\":\"13852852877\"," + "\"access_params\":{" + "\"channel\":\"ALIPAYAPP\"" + " }," + "\"sub_merchant\":{" + "\"sub_merchant_id\":\"2088123412341234\"," + "\"sub_merchant_name\":\"哆来米\"," + "\"sub_merchant_service_name\":\"能省钱更能赚钱\"," + "\"sub_merchant_service_description\":\"副业才有未来\"" + " }," + "\"period_rule_params\":{" + "\"period_type\":\"DAY\"," + "\"period\":3," + "\"execute_time\":\"2019-01-23\"," + "\"single_amount\":10.99," + "\"total_amount\":600," + "\"total_payments\":12" + " }" + " }" + " }"; AlipayTradeAppPayResponse response = client.SdkExecute(request); dm_alipay_recordEntity dm_Alipay_RecordEntity = new dm_alipay_recordEntity(); dm_Alipay_RecordEntity.user_id = user_id; dm_Alipay_RecordEntity.total_amount = dm_Alipay_TemplateEntity.finishprice; dm_Alipay_RecordEntity.templateid = TemplateID; dm_Alipay_RecordEntity.subject = dm_Alipay_TemplateEntity.name; dm_Alipay_RecordEntity.out_trade_no = out_trade_no; dM_Alipay_RecordIBLL.SaveEntity(0, dm_Alipay_RecordEntity); return(Success("支付参数获取成功!", new { PayParam = response.Body })); } catch (Exception ex) { return(FailException(ex)); } }
/// <summary> /// 创建订单 /// </summary> /// <param name="setid"></param> /// <param name="paytype"></param> /// <returns></returns> public string createOrder(int setid, int paytype) { if (paytype > 2) { return(JsonConvert.SerializeObject(new repmsg { state = 0, msg = "支付方式不正确" })); } int userid = User.userid; //创建订单 using (shhouseEntities ent = new shhouseEntities()) { ObjectParameter ordernum = new ObjectParameter("ordernum", typeof(string)); ObjectParameter setname = new ObjectParameter("setname", typeof(string)); ObjectParameter state = new ObjectParameter("state", typeof(int)); ObjectParameter totals = new ObjectParameter("totals", typeof(int)); ObjectParameter msg = new ObjectParameter("msg", typeof(string)); ent.order_create_jjr2018(userid, DateTime.Now, DateTime.Now.AddHours(2), setid, 1, paytype, ordernum, setname, totals, state, msg); int _state = (int)state.Value; if (_state == 1) { if (paytype == 1) { IAopClient client = new DefaultAopClient( "https://openapi.alipay.com/gateway.do", "APPID", "APP_PRIVATE_KEY", "json", "1.0", "RSA2", "ALIPAY_PUBLIC_KEY", "UTF-8", false ); //支付宝支付 AlipayTradePagePayModel model = new AlipayTradePagePayModel { Body = (string)setname.Value, Subject = (string)setname.Value, TotalAmount = Math.Round((decimal)totals.Value / 100m, 2).ToString(), OutTradeNo = (string)ordernum.Value, ProductCode = "FAST_INSTANT_TRADE_PAY" }; AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 设置同步回调地址 request.SetReturnUrl(""); // 设置异步通知接收地址 request.SetNotifyUrl(""); // 将业务model载入到request request.SetBizModel(model); try { AlipayTradePagePayResponse response = client.SdkExecute(request); //支付宝支付地址 string url = "https://openapi.alipay.com/gateway.do?" + response.Body; //Response.Write(response.Body); return(JsonConvert.SerializeObject(new repmsg { state = 1, msg = "", data = new { tradeno = (string)ordernum.Value, total = (int)totals.Value, paytype = paytype, url = url } })); } catch (Exception exp) { return(JsonConvert.SerializeObject(new repmsg { state = 0, msg = exp.Message })); } } else if (paytype == 2) { try { //微信支付 NativePay nativePay = new NativePay(); string url = nativePay.GetPayUrl(setid.ToString(), (string)setname.Value, (string)ordernum.Value, (int)totals.Value); if (string.IsNullOrEmpty(url)) { return(JsonConvert.SerializeObject(new repmsg { state = 0, msg = "订单创建失败" })); } QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; qrCodeEncoder.QRCodeVersion = 0; qrCodeEncoder.QRCodeScale = 8; //将字符串生成二维码图片 Bitmap image = qrCodeEncoder.Encode(url, Encoding.Default); string _root = Server.MapPath($"~/wxpaycode/{userid}/"); if (!System.IO.Directory.Exists(_root)) { System.IO.Directory.CreateDirectory(_root); } string _filename = Guid.NewGuid().ToString().Replace("-", "") + ".jpg"; image.Save(_root + _filename, System.Drawing.Imaging.ImageFormat.Jpeg); return(JsonConvert.SerializeObject(new repmsg { state = 1, msg = "", data = new { tradeno = (string)ordernum.Value, setname = (string)setname.Value, total = (int)totals.Value, paytype = paytype, qrimg = $"/wxpaycode/{userid}/{_filename}" } })); } catch (Exception e) { return(JsonConvert.SerializeObject(new repmsg { state = 0, msg = e.Message })); } } else { return(""); } } else { return(JsonConvert.SerializeObject(new repmsg { state = 0, msg = "提交失败,请稍后再试" })); } } }
private string OnPay(DataRow row) { #region 获取基本参数 string CommunityId = string.Empty; if (row.Table.Columns.Contains("CommunityId")) { CommunityId = row["CommunityId"].ToString(); } string RoomID = string.Empty; if (row.Table.Columns.Contains("RoomID")) { RoomID = row["RoomID"].ToString(); } string CustID = string.Empty; if (row.Table.Columns.Contains("CustID")) { CustID = row["CustID"].ToString(); } string OpenID = string.Empty; if (row.Table.Columns.Contains("OpenID")) { OpenID = row["OpenID"].ToString(); } if (!row.Table.Columns.Contains("PayChannel") || string.IsNullOrEmpty(row["PayChannel"].ToString())) { return(new ApiResult(false, "参数PayChannel有误").toJson()); } var community = GetCommunity(CommunityId); if (community == null) { return(JSONHelper.FromString(false, "未查询到小区信息")); } int CommID = AppGlobal.StrToInt(community.CommID); PubConstant.hmWyglConnectionString = GetConnectionStr(community); var payChannel = row["PayChannel"].ToString(); var payType = 0; switch (payChannel.ToLower()) { case PayChannelString.Alipay: payType = 1; break; case PayChannelString.WechatPay: payType = 2; break; case PayChannelString.AllInPay_Alipay: payType = 1; break; case PayChannelString.AllInPay_WechatPay: payType = 2; break; default: return(new ApiResult(false, "参数payChannel有误").toJson()); } if (payType == 2) { if (payChannel.ToLower().Equals(PayChannelString.AllInPay_WechatPay) && string.IsNullOrEmpty(OpenID)) { return(new ApiResult(false, "参数OpenID不能为空").toJson()); } } #endregion using (IDbConnection erpConn = new SqlConnection(PubConstant.hmWyglConnectionString)) { dynamic tb_Payment_Config = erpConn.QueryFirstOrDefault <dynamic>("SELECT * FROM Tb_Payment_Config WITH(NOLOCK) WHERE CommID = @CommID", new { CommID }); if (null == tb_Payment_Config) { return(new ApiResult(false, "该项目未开通对应支付方式").toJson()); } // 旧方式获取对应支付配置 AllinConfig allinConfig = null; // 新方式获取支付配置 PaymentConfig paymentConfig = null; if (payChannel == PayChannelString.AllInPay_Alipay || payChannel == PayChannelString.AllInPay_WechatPay) { try { allinConfig = JsonConvert.DeserializeObject <AllinConfig>(tb_Payment_Config.Config); if (null == allinConfig) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } } catch (Exception) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } } else { // 新的方式,Config存储多个配置 try { // ERP的配置表,要求存储一个Json数组,用于配置支持不同支付方式 // 配置项要求存储一个 List <PaymentConfig> configs = JsonConvert.DeserializeObject <List <PaymentConfig> >(tb_Payment_Config.Config); if (null == configs || configs.Count <= 0) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } if (payChannel == PayChannelString.Alipay) { paymentConfig = configs.Find(item => item.type == "AliPay"); } if (payChannel == PayChannelString.WechatPay) { paymentConfig = configs.Find(item => item.type == "WChatPay"); } if (null == paymentConfig) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } } catch (Exception) { } } #region 计算金额 if (!row.Table.Columns.Contains("PayData") || string.IsNullOrEmpty(row["PayData"].ToString())) { return(new ApiResult(false, "缺少参数PayData").toJson()); } string PayData = row["PayData"].ToString(); if (!CheckPayData(Global_Fun.BurstConnectionString(CommID, Global_Fun.BURST_TYPE_CHARGE), Convert.ToInt64(CustID), Convert.ToInt64(RoomID), PayData, out decimal Amt, out string errMsg, true, false, !"1940".Equals(Global_Var.LoginCorpID))) { return(new ApiResult(false, errMsg).toJson()); } if (Amt <= 0.00M) { return(new ApiResult(false, "金额必须大于0").toJson()); } #endregion JObject PayDataObj = JObject.Parse(PayData); int Type = (int)PayDataObj["Type"]; #region 查询项目名称和房屋编号,拼接费用备注 string FeesMemo = string.Empty; string RoomSign = string.Empty; if (Type == 1) { FeesMemo = "物业综合费用缴纳"; string CommName = erpConn.QueryFirstOrDefault <string>("SELECT CommName FROM Tb_HSPR_Community WHERE CommID = @CommID", new { CommID }); if (string.IsNullOrEmpty(CommName)) { CommName = Convert.ToString(CommID); } RoomSign = erpConn.QueryFirstOrDefault <string>("SELECT ISNULL(RoomSign,RoomName) AS RoomSign FROM Tb_HSPR_Room WHERE RoomID = @RoomID", new { RoomID }); if (string.IsNullOrEmpty(RoomSign)) { RoomSign = Convert.ToString(RoomID); } FeesMemo += string.Format("-{0}-{1}", CommName, RoomSign); } else { FeesMemo = "物业综合费用预存"; string CommName = erpConn.QueryFirstOrDefault <string>("SELECT CommName FROM Tb_HSPR_Community WHERE CommID = @CommID", new { CommID }); if (string.IsNullOrEmpty(CommName)) { CommName = Convert.ToString(CommID); } RoomSign = erpConn.QueryFirstOrDefault <string>("SELECT ISNULL(RoomSign,RoomName) AS RoomSign FROM Tb_HSPR_Room WHERE RoomID = @RoomID", new { RoomID }); if (string.IsNullOrEmpty(RoomSign)) { RoomSign = Convert.ToString(RoomID); } FeesMemo += string.Format("-{0}-{1}", CommName, RoomSign); } #endregion string NoticeId = Guid.NewGuid().ToString(); // 生成订单 if (erpConn.Execute("INSERT INTO Tb_Notice(Id, CommID, RoomID, CustID, PayData, CreateTime) VALUES(@Id, @CommID, @RoomID, @CustID, @PayData, @CreateTime)", new { Id = NoticeId, CommID, RoomID, CustID, PayData, CreateTime = DateTime.Now.ToString() }) <= 0) { return(new ApiResult(false, "创建收款订单失败,请重试").toJson()); } string ChargeMode = "业主APP缴费"; if (payChannel == PayChannelString.AllInPay_Alipay) { ChargeMode = "通联_业主APP(支付宝)"; } else if (payChannel == PayChannelString.AllInPay_WechatPay) { ChargeMode = "通联_业主APP(微信)"; } else { ChargeMode = "通联_业主APP"; } #region 修改收款方式 if (erpConn.QueryFirstOrDefault <int>("SELECT COUNT(1) FROM syscolumns WHERE id=object_id('Tb_Notice') AND name = 'ChargeMode'") > 0) { erpConn.Execute("UPDATE Tb_Notice SET ChargeMode = @ChargeMode WHERE Id = @Id", new { ChargeMode, Id = NoticeId }); } #endregion DateTime dateNow = DateTime.Now; string OrderSN = dateNow.ToString("yyyyMMddHHmmssfff") + Utils.BuildRandomStr(3); string PaymentNotifyUrl = string.Empty; Dictionary <string, string> param = null; if (payChannel == PayChannelString.AllInPay_Alipay || payChannel == PayChannelString.AllInPay_WechatPay) { #region 请求通联支付 #region 获取对应类型的下账地址 if (Type == 1) { PaymentNotifyUrl = AppGlobal.GetAppSetting("AllinPay_Notify_Url") + "?CommID=" + CommID; } else { PaymentNotifyUrl = AppGlobal.GetAppSetting("AllinPay_Prec_Notify_Url") + "?CommID=" + CommID; } #endregion try { param = SybWxPayService.Pay(Convert.ToInt64(Amt * 100), OrderSN, payChannel == PayChannelString.AllInPay_Alipay ? "A01" : "W06", FeesMemo, RoomSign, OpenID, "", PaymentNotifyUrl, "", "", "", "", allinConfig.orgid, allinConfig.appid, allinConfig.custid, allinConfig.appkey, allinConfig.subbranch); if (param == null || !param.ContainsKey("payinfo")) { GetLog().Error("OnPay:" + JsonConvert.SerializeObject(param)); return(new ApiResult(false, "生成支付订单失败,请重试").toJson()); } } catch (Exception ex) { GetLog().Error("OnPay", ex); return(new ApiResult(false, "生成支付订单失败,请重试").toJson()); } if (erpConn.Execute(@"INSERT INTO Tb_Payment_Order(PayType, OrderSN, NoticeId, Amt, CreateTime) VALUES(@PayType, @OrderSN, @NoticeId, @Amt, @CreateTime)", new { PayType = payType, OrderSN = OrderSN, NoticeId = NoticeId, Amt = Amt, CreateTime = dateNow }) <= 0) { return(new ApiResult(false, "生成支付订单失败,请重试(1003)").toJson()); } return(new ApiResult(true, new { OrderSN = OrderSN, QrCode = param["payinfo"].ToString() }).toJson()); #endregion } if (payChannel == PayChannelString.Alipay) { AliConfig aliConfig = null; try { aliConfig = Config.GetConfig <AliConfig>(paymentConfig.config); if (null == aliConfig) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } } catch (Exception) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } #region 请求支付宝官方支付 #region 获取对应类型的下账地址 PaymentNotifyUrl = AppGlobal.GetAppSetting("AliPay_Notify_Url"); #endregion AlipayTradeAppPayResponse response = null; try { JObject BizContent = new JObject(); //要求15分钟内支付 BizContent.Add("timeout_express", "15m"); BizContent.Add("total_amount", Amt); BizContent.Add("body", FeesMemo); BizContent.Add("subject", FeesMemo); BizContent.Add("out_trade_no", OrderSN); IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", aliConfig.appid, aliConfig.app_private_key, "json", "1.0", "RSA2", aliConfig.alipay_public_key, "UTF-8", false); AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest { BizContent = JsonConvert.SerializeObject(BizContent), }; request.SetNotifyUrl(PaymentNotifyUrl); response = client.SdkExecute(request); } catch (Exception ex) { Log(ex.Message, "AliPayLogs\\"); GetLog().Error(ex.Message + Environment.CommandLine + ex.StackTrace); return(new ApiResult(false, "请求订单失败,请重试").toJson()); } if (erpConn.Execute("INSERT INTO Tb_Payment_Order(PayType, OrderSN, NoticeId, Amt, CreateTime) VALUES(@PayType, @OrderSN, @NoticeId, @Amt, @CreateTime)", new { PayType = 1, OrderSN, NoticeId = NoticeId, Amt = Amt, CreateTime = dateNow }) <= 0) { return(new ApiResult(false, "生成订单失败").toJson()); } return(new ApiResult(true, new { OrderSN = OrderSN, QrCode = response.Body }).toJson()); #endregion } if (payChannel == PayChannelString.WechatPay) { WxConfig wxConfig = null; try { wxConfig = Config.GetConfig <WxConfig>(paymentConfig.config); if (null == wxConfig) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } } catch (Exception) { return(new ApiResult(false, "该项目支付类型对应配置有误").toJson()); } #region 请求微信官方支付 #region 获取对应类型的下账地址 PaymentNotifyUrl = AppGlobal.GetAppSetting("WxPay_Notify_Url"); #endregion WxPayData wxPayData = new WxPayData(); wxPayData.SetValue("appid", wxConfig.appid); wxPayData.SetValue("body", FeesMemo); wxPayData.SetValue("mch_id", wxConfig.mch_id); wxPayData.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); wxPayData.SetValue("notify_url", PaymentNotifyUrl); wxPayData.SetValue("out_trade_no", OrderSN); wxPayData.SetValue("spbill_create_ip", "8.8.8.8"); wxPayData.SetValue("total_fee", Convert.ToInt32(Amt * 100)); wxPayData.SetValue("trade_type", "APP"); wxPayData.SetValue("sign_type", wxpay.utils.WxPayData.SIGN_TYPE_HMAC_SHA256); wxPayData.SetValue("sign", wxPayData.MakeSign(wxConfig.appkey)); try { wxPayData = WxPayApi.UnifiedOrder(wxPayData); } catch (Exception) { return(new ApiResult(false, "请求超时,请重试").toJson()); } if (!wxPayData.IsSet("return_code") || !"SUCCESS".Equals(wxPayData.GetValue("return_code").ToString())) { return(new ApiResult(false, "请求支付订单失败").toJson()); } if (!wxPayData.IsSet("result_code") || !"SUCCESS".Equals(wxPayData.GetValue("result_code").ToString())) { return(new ApiResult(false, "请求支付订单失败").toJson()); } if (!wxPayData.IsSet("prepay_id")) { return(new ApiResult(false, "请求支付订单失败").toJson()); } string prepay_id = wxPayData.GetValue("prepay_id").ToString(); if (erpConn.Execute("INSERT INTO Tb_Payment_Order(PayType, OrderSN, NoticeId, Amt, CreateTime) VALUES(@PayType, @OrderSN, @NoticeId, @Amt, @CreateTime)", new { PayType = 2, OrderSN, NoticeId = NoticeId, Amt = Amt, CreateTime = dateNow }) <= 0) { return(new ApiResult(false, "生成订单失败").toJson()); } WxPayData result = new WxPayData(); result.SetValue("appid", wxPayData.GetValue("appid").ToString()); result.SetValue("partnerid", wxPayData.GetValue("mch_id").ToString()); result.SetValue("prepayid", prepay_id); result.SetValue("package", "Sign=WXPay"); result.SetValue("noncestr", wxPayData.GetValue("nonce_str").ToString()); result.SetValue("timestamp", WxPayApi.GenerateTimeStamp()); result.SetValue("sign", result.MakeSign(wxpay.utils.WxPayData.SIGN_TYPE_HMAC_SHA256, wxConfig.appkey)); JObject jObj = JObject.Parse(result.ToJson()); return(new ApiResult(true, new { OrderSN = OrderSN, QrCode = jObj }).toJson()); #endregion } return(new ApiResult(false, "不支持的支付方式").toJson()); } }