一键支付工具类
示例#1
0
    /// <summary>
    /// 将请求接口中的业务明文参数加密并请求一键支付接口,单不对返回的数据进行解密,用于获取清算对账单接口--商户通用接口
    /// </summary>
    /// <param name="sd"></param>
    /// <param name="apiUri"></param>
    /// <returns></returns>
    private string createMerchantDataAndRequestYb2(SortedDictionary <string, object> sd, string apiUri, bool ispost)
    {
        //随机生成商户AESkey
        string merchantAesKey = AES.GenerateAESKey();

        //生成RSA签名
        string sign = EncryptUtil.handleRSA(sd, merchantPrivatekey);

        sd.Add("sign", sign);


        //将对象转换为json字符串
        string bpinfo_json = Newtonsoft.Json.JsonConvert.SerializeObject(sd);
        string datastring  = AES.Encrypt(bpinfo_json, merchantAesKey);

        //将商户merchantAesKey用RSA算法加密
        string encryptkey = RSAFromPkcs8.encryptData(merchantAesKey, yibaoPublickey, "UTF-8");

        String ybResult = "";

        if (ispost)
        {
            ybResult = YJPayUtil.payAPIRequest(apimercahntprefix + apiUri, datastring, encryptkey, true);
        }
        else
        {
            ybResult = YJPayUtil.payAPIRequest(apimercahntprefix + apiUri, datastring, encryptkey, false);
        }

        return(YJPayUtil.checkYbClearResult(ybResult));
    }
示例#2
0
        /// <summary>
        /// 易宝异步返回
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public YBResponsePara YBCallBack(HttpContext context)
        {
            YBResponsePara result = new YBResponsePara()
            {
                isPaySuccess = false,
                orderNumber  = "",
                paymentMoney = 0,
                resultMsg    = ""
            };

            try
            {
                if (context.Request["data"].IsNull() ||
                    context.Request["encryptkey"].IsNull())
                {
                    result.resultMsg = "回调参数不正确";
                    return(result);
                }
                //回调中的参数data
                string data = context.Request["data"].ToString();
                //回调中的参数encryptkey
                string encryptkey = context.Request["encryptkey"].ToString();
                //解密易宝支付回调结果
                string callback_result = YJPayUtil.checkYbCallbackResult(data, encryptkey);
                if (callback_result != "验签未通过")
                {
                    //string descstring = AES.Decrypt(data, APIURLConfig.merchantAesKey);
                    Dictionary <string, object> responsePara = callback_result.JsonToDocument <Dictionary <string, object> >();

                    if (!responsePara.IsNull())
                    {
                        result.isPaySuccess = true;
                        result.paymentMoney = AlipayConfig.MoneyFormatDco(responsePara["amount"].ToString());
                        result.orderNumber  = responsePara["orderid"].ToString();
                        result.resultMsg    = "返回成功";
                    }
                }
            }
            catch (Exception err)
            {
                result.resultMsg = err.Message;
            }

            return(result);
        }
        public ActionResult YeePay(Dictionary <string, string> queryvalues)
        {
            string _data       = queryvalues.ContainsKey("data") ? queryvalues["data"] : string.Empty;
            string _encryptkey = queryvalues.ContainsKey("encryptkey") ? queryvalues["encryptkey"] : string.Empty;

            if (_data == string.Empty || _encryptkey == string.Empty)
            {
                Response.Redirect("mobilecall://fail");
                return(Content("参数不正确!"));
            }

            try
            {
                //商户注意:接收到易宝的回调信息后一定要回写success用以保证握手成功!
                //Response.Write("success");

                YeepayCallback model = new YeepayCallback();
                model.Data           = _data;
                model.EncryptKey     = _encryptkey;
                model.CallBackResult = YJPayUtil.checkYbCallbackResult(_data, _encryptkey);//解密易宝支付回调结果



                JsonToInstance       util = new JsonToInstance();
                YeepayCallbackReslut m    = util.ToInstance <YeepayCallbackReslut>(model.CallBackResult);
                RechargeCheck        rc   = RechargeCheckBLL.GetModelBySerialNo(new RechargeCheck {
                    SerialNo = m.orderid
                });
#if Debug
                Role user = RoleBLL.GetModelByID(new Role {
                    ID = rc.UserID
                });
#endif

#if P17
                Role user = RoleBLL.GetModelByID(new Role {
                    ID = rc.UserID
                });
#endif
#if Release
                Role user = RoleBLL.GetModelByID(new Role {
                    ID = rc.UserID
                });
#endif
                IAPProduct iap = IAPProductBLL.GetModelByID(rc.ProductID);
                isFirst    iF  = iap.product_id.Split('_')[0].Equals("firstCharge")?isFirst.是:isFirst.否;
                chipType   ct  = iF == isFirst.是 ? chipType.首冲礼包 : (chipType)iap.goodsType;



                bool firstGif = iF == isFirst.是;

                uint gold = iap.goodsType == 1 ? (uint)iap.goods : 0;
                uint dia  = iap.goodsType == 2 ? (uint)iap.goods : 0;

                if (firstGif)
                {
                    gold = (uint)(iap.goods + iap.attach_chip);
                    dia  = (uint)iap.attach_5b;
                }

                uint rmb = (uint)(rc.Money / 100);

                normal ServiceNormalS = normal.CreateBuilder()
                                        .SetUserID((uint)rc.UserID)
                                        .SetGold(gold)
                                        .SetDia(dia)
                                        .SetRmb(rmb)
                                        .SetFirstGif(firstGif)
                                        .Build();


                Bind tbind = Cmd.runClient(new Bind(BR_Cmd.BR_NORMAL, ServiceNormalS.ToByteArray()));
                switch ((CenterCmd)tbind.header.CommandID)
                {
                case CenterCmd.CS_NORMAL:
                    normalRep ServiceNormalC = normalRep.ParseFrom(tbind.body.ToBytes());


                    if (ServiceNormalC.Suc)
                    {
                        RechargeBLL.Add(new Recharge {
                            BillNo = m.yborderid, OpenID = rc.SerialNo, UserID = rc.UserID, Money = rc.Money, CreateTime = DateTime.Now, Chip = gold, ChipType = ct, IsFirst = iF, NickName = iap.productname, PayItem = iap.product_id, PF = raType.易宝, UserAccount = user.NickName
                        });

                        RechargeCheckBLL.Delete(new RechargeCheck {
                            SerialNo = m.orderid
                        });



                        //Response.Redirect("mobilecall://success");
                        return(RedirectToAction("success", "Home"));
                    }
                    //Response.Redirect("mobilecall://fail?suc=" + ServiceNormalC.Suc);
                    break;

                case CenterCmd.CS_CONNECT_ERROR:
                    break;
                }



                //Response.Redirect("mobilecall://fail");
                return(RedirectToAction("fail", "Home"));
            }
            catch (Exception err)
            {
                //Response.Redirect("mobilecall://fail?err=" + err);
                return(RedirectToAction("fail", "Home"));
                //return Content("支付失败!" + err);
            }
        }
示例#4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            TuanDai.Payment.Log.Info(this.GetType().ToString(), "开始易宝回调");
            string callback_result = "";

            try
            {
                if (Request["data"] == null || Request["encryptkey"] == null)
                {
                    TuanDai.Payment.Log.Info(this.GetType().ToString(), "参数不正确");
                    Response.Write("参数不正确!");
                    Response.End();
                }

                TuanDai.Payment.Log.Info(this.GetType().ToString(), "易宝回调加密参数:" + Request["data"] + ",密钥:" + Request["encryptkey"]);
                //商户注意:接收到易宝的回调信息后一定要回写success用以保证握手成功!

                string data       = Request["data"];       //回调中的参数data
                string encryptkey = Request["encryptkey"]; //回调中的参数encryptkey
                callback_result = YJPayUtil.checkYbCallbackResult(data, encryptkey);
                var resultData = JsonConvert.DeserializeObject <SortedDictionary <string, string> >(callback_result);
                TuanDai.Payment.Log.Info(this.GetType().ToString(), "The Pay result is Values  : " + callback_result);

                if (resultData == null || resultData.ContainsKey("error_msg"))
                {
                    Response.Write("参数不正确!");
                    Response.End();
                }

                var status         = resultData["status"].ToString();
                var rechargeMoney  = resultData["amount"].ToString();
                var out_trade_no   = resultData["orderid"].ToString();
                var transaction_id = resultData["yborderid"].ToString();

                string            strSQL   = "p_OnLineRechargeHandler";
                DynamicParameters dyParams = new DynamicParameters();
                dyParams.Add("@orderno", out_trade_no);
                dyParams.Add("@MediumMoney", decimal.Parse(rechargeMoney) / 100);
                dyParams.Add("@MediumOrderNo", transaction_id);
                dyParams.Add("@outStatus", 0, DbType.Int32, ParameterDirection.Output, 20);
                if (status == "1")
                {
                    dyParams.Add("@handlerStatus", 2);
                }
                else
                {
                    dyParams.Add("@handlerStatus", 1);
                }
                PublicConn.ExecuteTD(PublicConn.DBWriteType.FundWrite, strSQL, ref dyParams, CommandType.StoredProcedure);

                int result = dyParams.Get <int>("@outStatus");
                if (result == 1)
                {
                    AccountRechareInfo accountRechare = getAccountRechare(out_trade_no);
                    if (accountRechare != null)
                    {
                        //List<int> typeList = new List<int>() { 2, 3, 4, 6, 8,9,11, 12 };
                        //if (db.AccountRechare.Count(p => p.UserId == accountRechare.UserId && p.Status == 2 && typeList.Contains(p.type)) == 1)
                        //{
                        //    TuanDai.PortalSystem.BLL.VipGetWorthBLL.AddGetWorth(accountRechare.UserId, (int)ConstString.UserGrowthType.FirstReCharge, null, 0);
                        //}

                        TuanDai.PortalSystem.BLL.UserBLL bll = new TuanDai.PortalSystem.BLL.UserBLL();
                        UserBasicInfoInfo userBasicInfo      = bll.GetUserBasicInfoModelById(accountRechare.UserId);
                        if (userBasicInfo != null)
                        {
                            var isNewSmsRequest = ConfigHelper.getConfigString("IsNewSmsRequest", "0");
                            if (isNewSmsRequest == "0")
                            {
                                var parameters = new Dictionary <string, object>();
                                parameters.Add("User", userBasicInfo);
                                parameters.Add("CurrentDate", DateTime.Now);
                                parameters.Add("RechargeMoney", rechargeMoney);
                                parameters.Add("Host", GlobalUtils.WebURL);

                                var messageSender = new BusinessDll.MessageSend();
                                messageSender.SendMessage2(eventCode: MessageTemplates.RechargeSuccess, parameters: parameters,
                                                           mobile: userBasicInfo.TelNo, email: userBasicInfo.Email, userId: userBasicInfo.Id);
                            }
                            else
                            {
                                SmsRequest rechargeSuccessSmsRequest = new SmsRequest();
                                rechargeSuccessSmsRequest.EventCode      = MsgTemplatesType.RechargeSuccess;
                                rechargeSuccessSmsRequest.PlatformSource = PlatformSource.Pc;
                                rechargeSuccessSmsRequest.UserId         = userBasicInfo.Id;
                                rechargeSuccessSmsRequest.EmailAddress   = userBasicInfo.Email;
                                rechargeSuccessSmsRequest.Mobile         = userBasicInfo.TelNo;
                                rechargeSuccessSmsRequest.Parameters     = new Dictionary <string, object>();
                                rechargeSuccessSmsRequest.Parameters.Add("RechargeMoney", rechargeMoney);

                                string errorMessage = string.Empty;
                                SmsClient.SendMessage(rechargeSuccessSmsRequest, ref errorMessage);
                            }
                        }
                    }
                }

                //NetLog.WriteBatchwithdrawHandler("交易成功", string.Concat("签名:", sPara["sign"].ToString(), "签名方式:", sPara["sign_type"].ToString(), "我方处理状态:", result.ToString().Trim(), "连连处理状态:", sPara["result_pay"].ToString()));
                Response.Write(@"SUCCESS");
                Response.End();

                //SoftLog.LogStr("支付成功回调信息:" + callback_result, "yeepay/CallbackLog");
            }
            catch (Exception err)
            {
                TuanDai.Payment.Log.Info(this.GetType().ToString(), "支付失败:" + err.ToString() + "," + Request["data"] + Environment.NewLine + Request["encryptkey"] + "处理结果:" + callback_result);
                //SoftLog.LogStr("支付失败:" + err.ToString() + "," + Request["data"] + Environment.NewLine + Request["encryptkey"] + "处理结果:" + callback_result, "yeepay/CallbackLog");
                Response.Write("支付失败!");
                Response.End();
            }
            finally
            {
                //SoftLog.LogStr("支付回调信息" + Request["data"] + Environment.NewLine + Request["encryptkey"] + "处理结果:" + callback_result, "yeepay/CallbackLog");
            }
        }
示例#5
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            StringBuilder log = new StringBuilder();

            log.Append(DateTime.Now.ToString() + "\n");
            log.Append("测试功能:" + theme.InnerText + "\n");


            //***********************修改内容****************************

            string requestUrl = APIURLConfig.QueryableOrder;

            string[] list          = { "p0_Cmd", "p1_MerId", "pb_TrxId", "pv_Ver" };
            string[] list_response = { "r0_Cmd",
                                       "r1_Code" };

            //***********************************************************


            log.Append("请求地址:" + requestUrl + "\n");
            log.Append("商户编号:" + p1_MerId.Value + "\n");
            log.Append("商户密钥:" + CustomerConfig.merchantKey + "\n");

            //存储前台数据
            string data_hmac = "";

            //循环生成
            foreach (string listname in list)
            {
                if (Request[listname] != "")
                {
                    data_hmac = data_hmac + Request[listname];
                }
            }

            //生成hmac签名
            string hmac = Digest.CreateHmac(data_hmac);

            log.Append("请求加密的字符串:" + data_hmac + "\n");
            log.Append("请求hmac:" + hmac + "\n");

            //循环生成要请求链接的数据
            string data_request = "";

            foreach (string listname in list)
            {
                data_request = data_request + listname + "=" + Request[listname] + "&";
            }
            //最终字符串
            data_request = data_request + "hmac=" + hmac;

            log.Append("请求链接:" + requestUrl + "?" + data_request + "\n");

            //发出请求
            string reqResult = YJPayUtil.payAPIRequestOnlince(requestUrl, data_request, true);

            log.Append("返回的原始信息:" + reqResult + "\n");

            //存储响应信息
            SortedDictionary <string, string> sd = new SortedDictionary <string, string>();

            //循环存储response
            foreach (string listname in list_response)
            {
                sd.Add(listname, FormatQueryString.GetQueryString(listname, reqResult, '\n'));
            }
            sd.Add("hmac", FormatQueryString.GetQueryString("hmac", reqResult, '\n'));


            string response_json = Newtonsoft.Json.JsonConvert.SerializeObject(sd);

            string type = "";

            if (sd["r1_Code"] == "1")
            {
                //回调验证签名
                string response_data = "";

                //循环生成
                foreach (string listname in list_response)
                {
                    response_data = response_data + sd[listname];
                }

                //回调信息生成HMAC
                string hmac_location = Digest.CreateHmac(response_data);


                //验证签名
                StringComparer comparer = StringComparer.OrdinalIgnoreCase;
                if (0 == comparer.Compare(hmac_location, sd["hmac"]))
                {
                    type = "验证签名成功";
                }
                else
                {
                    type = "验证签名失败";
                }
            }
            else
            {
                type = "请检查数据";
            }

            //返回数据data
            string data = response_json.ToString();



            SoftLog.LogStr(log.ToString(), theme.InnerText);

            //跳转页面
            Response.Redirect("http://localhost:58903/CallBack.aspx?data=" + data + "&type=" + type);
        }
示例#6
0
        public ActionResult YeePay(string orderNo)
        {
            //var order = OrderContract.OrderInfos.Where(p => p.OrderNo == orderNo).SingleOrDefault();
            //if (order == null) return Content("订单不存在");

            string serverHost = ConfigurationManager.AppSettings["ServerHost"];

            //一键支付URL前缀
            string apiprefix = APIURLConfig.mobilePrefix;

            //网页支付地址
            string mobilepayURI = APIURLConfig.webpayURI;

            //商户账户编号
            string customernumber = YeePayConfig.merchantAccount;
            string hmacKey        = YeePayConfig.merchantKey;
            string AesKey         = YeePayConfig.AescKey;

            //日志字符串
            StringBuilder logsb = new StringBuilder();

            logsb.Append(DateTime.Now.ToString() + "\n");

            Random ra             = new Random();
            string payproducttype = "ONEKEY";                   // "支付方式";
            string amount         = /*order.TotalPrice + */ ""; //支付金额为单位元
            string requestid      = orderNo;                    //订单号
            string productcat     = "";                         //商品类别码,商户支持的商品类别码由易宝支付运营人员根据商务协议配置
            string productdesc    = "订单商品";                     //商品描述
            string productname    = "订单商品";                     //商品名称
            string assure         = "0";                        //是否需要担保,1是,0否
            string divideinfo     = "";                         //分账信息,格式”ledgerNo:分账比
            string bankid         = "";                         //银行编码
            string period         = "";                         //担保有效期,单位 :天;当assure=1 时必填,最大值:30
            string memo           = "";                         //商户备注
            string userno         = /*order.UserInfo.Id +*/ ""; //用户标识
            string ip             = "";                         //IP
            string cardname       = "";                         //持卡人姓名
            string idcard         = "";                         //身份证
            string bankcardnum    = "";                         //银行卡号

            //商户提供的商户后台系统异步支付回调地址
            string callbackurl = string.Format("{0}Admin/Pay/YeePayNotifyUrl", serverHost);
            //商户提供的商户前台系统异步支付回调地址
            string webcallbackurl = "";
            string hmac           = "";


            hmac = Digest.GetHMAC(customernumber, requestid, amount, assure, productname, productcat, productdesc, divideinfo, callbackurl, webcallbackurl, bankid, period, memo, hmacKey);

            SortedDictionary <string, object> sd = new SortedDictionary <string, object>();

            sd.Add("customernumber", customernumber);
            sd.Add("amount", amount);
            sd.Add("requestid", requestid);
            sd.Add("assure", assure);
            sd.Add("productname", productname);
            sd.Add("productcat", productcat);
            sd.Add("productdesc", productdesc);
            sd.Add("divideinfo", divideinfo);
            sd.Add("callbackurl", callbackurl);
            sd.Add("webcallbackurl", webcallbackurl);
            sd.Add("bankid", bankid);
            sd.Add("period", period);
            sd.Add("memo", memo);
            sd.Add("payproducttype", payproducttype);
            sd.Add("userno", userno);
            sd.Add("ip", ip);
            sd.Add("cardname", cardname);
            sd.Add("idcard", idcard);
            sd.Add("bankcardnum", bankcardnum);
            sd.Add("hmac", hmac);

            //将网页支付对象转换为json字符串
            string wpinfo_json = Newtonsoft.Json.JsonConvert.SerializeObject(sd);

            logsb.Append("手机支付明文数据json格式为:" + wpinfo_json + "\n");

            string datastring = AESUtil.Encrypt(wpinfo_json, AesKey);

            logsb.Append("手机支付业务数据经过AES加密后的值为:" + datastring + "\n");



            //打开浏览器访问一键支付网页支付链接地址,请求方式为get
            string postParams = "data=" + HttpUtility.UrlEncode(datastring) + "&customernumber=" + customernumber;
            string url        = apiprefix + mobilepayURI + "?" + postParams;

            logsb.Append("手机支付链接地址为:" + url + "\n");

            string ybResult = YJPayUtil.payAPIRequest(apiprefix + mobilepayURI, datastring, false);

            logsb.Append("请求支付结果:" + ybResult + "\n");

            //将支付结果json字符串反序列化为对象
            RespondJson respJson = Newtonsoft.Json.JsonConvert.DeserializeObject <RespondJson>(ybResult);
            string      yb_data  = respJson.data;

            yb_data = AESUtil.Decrypt(yb_data, YeePayConfig.merchantKey);
            PayRequestJson result = Newtonsoft.Json.JsonConvert.DeserializeObject <PayRequestJson>(yb_data);

            if (result.code == 1)
            {
                bool r = Digest.PayRequestVerifyHMAC(result.customernumber, result.requestid, result.code, result.externalid, result.amount, result.payurl, hmacKey, result.hmac);
                if (r)
                {
                    //重定向跳转到易宝支付收银台
                    return(Redirect(result.payurl));
                }
                else
                {
                    return(Content("回调验签失败"));
                }
            }
            else
            {
                return(Content(result.msg));
            }
        }