Ejemplo n.º 1
0
        public string GetPrepayId(string operater, string trade_type, string openid, string orderSn, decimal orderAmount, string goods_tag, string ip, string body, DateTime?time_expire = null)
        {
            CustomJsonResult result = new CustomJsonResult();


            TenpayUtil tenpayUtil = new TenpayUtil(wxConfig);

            UnifiedOrder unifiedOrder = new UnifiedOrder();

            unifiedOrder.openid           = openid;
            unifiedOrder.out_trade_no     = orderSn;                            //商户订单号
            unifiedOrder.spbill_create_ip = ip;                                 //终端IP
            unifiedOrder.total_fee        = Convert.ToInt32(orderAmount * 100); //标价金额
            unifiedOrder.body             = body;                               //商品描述
            unifiedOrder.trade_type       = trade_type;
            if (time_expire != null)
            {
                unifiedOrder.time_expire = time_expire.Value.ToString("yyyyMMddHHmmss");
            }

            if (!string.IsNullOrEmpty(goods_tag))
            {
                unifiedOrder.goods_tag = goods_tag;
            }

            string prepayId = tenpayUtil.GetPrepayId(unifiedOrder);

            //using (TransactionScope ts = new TransactionScope())
            //{

            //    result = new CustomJsonResult(ResultType.Success, ResultCode.Success, "操作成功");
            //}

            return(prepayId);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 创建chooseWxPay配置
        /// </summary>
        /// <param name="unifiedOrder"></param>
        /// <param name="signType"></param>
        /// <returns></returns>
        public ChooseWxPayConfig GenerateChooseWxPayConfig(UnifiedOrder unifiedOrder, WxPaySignType signType = WxPaySignType.MD5)
        {
            //转换字典
            var dic = UtilityHelper.Obj2Dictionary(unifiedOrder);

            //生成签名
            unifiedOrder.sign = SignatureGenerater.GenerateWxPaySignature(dic, _baseSettings.ApiKey, signType);
            //统一下单
            var unifiedOrderResult = _wxPayInterfaceCaller.UnifiedOrder(unifiedOrder);

            var nonceStr          = UtilityHelper.GenerateNonce();
            var timeStamp         = UtilityHelper.GetTimeStamp();
            var chooseWxPayConfig = new ChooseWxPayConfig()
            {
                nonceStr  = nonceStr,
                timestamp = timeStamp,
                package   = unifiedOrderResult.prepay_id,
                signType  = signType.GetDescription()
            };
            var paySign = SignatureGenerater.GenerateWxPaySignature(new Dictionary <string, string>()
            {
                { "appId", _baseSettings.AppId },
                { "timeStamp", chooseWxPayConfig.timestamp.ToString() },
                { "nonceStr", chooseWxPayConfig.nonceStr },
                { "package", chooseWxPayConfig.package },
                { "signType", chooseWxPayConfig.signType }
            }, _baseSettings.ApiKey, signType);

            chooseWxPayConfig.paySign = paySign;

            return(chooseWxPayConfig);
        }
Ejemplo n.º 3
0
        public UnifiedOrderResult UnifiedOrderByJsApi(WxAppInfoConfig config, string openId, string orderSn, decimal orderAmount, string goods_tag, string ip, string body, DateTime?time_expire = null)
        {
            var ret = new UnifiedOrderResult();

            TenpayUtil tenpayUtil = new TenpayUtil(config);

            UnifiedOrder unifiedOrder = new UnifiedOrder();

            unifiedOrder.openid           = openId;
            unifiedOrder.out_trade_no     = orderSn;                            //商户订单号
            unifiedOrder.spbill_create_ip = "192.168.1.1";                      //终端IP
            unifiedOrder.total_fee        = Convert.ToInt32(orderAmount * 100); //标价金额
            unifiedOrder.body             = body;                               //商品描述
            unifiedOrder.trade_type       = "JSAPI";
            if (time_expire != null)
            {
                unifiedOrder.time_expire = time_expire.Value.ToString("yyyyMMddHHmmss");
            }

            if (!string.IsNullOrEmpty(goods_tag))
            {
                unifiedOrder.goods_tag = goods_tag;
            }

            ret = tenpayUtil.UnifiedOrder(unifiedOrder);

            return(ret);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 扫码统一下单
        /// </summary>
        static string UnifiedOrder()
        {
            var apps         = File.ReadAllLines(@"D:\cert.txt");
            var payHandle    = new PayHandle();
            var unifiedOrder = new UnifiedOrder()
            {
                AppID          = apps[0],
                MchID          = apps[1],
                Key            = apps[3],
                Body           = "test",
                OutTradeNo     = DateTime.Now.ToString("yyMMddhhmmss"),
                ToalFee        = 1,
                SpbillCreateIP = "8.8.8.8",
                NotifyURL      = "http://www.abcd.com",
                TradeType      = "NATIVE",
                ProductID      = "123456"
            };
            var unifiedOrderBack = payHandle.Send(unifiedOrder) as UnifiedOrderBack;

            if (unifiedOrderBack.ResultCode == "SUCCESS")
            {
                SavaQR(unifiedOrderBack.CodeURL);
            }
            return(unifiedOrderBack.CodeURL);
        }
Ejemplo n.º 5
0
    /// <summary>
    /// 微信统一下单接口xml参数整理
    /// </summary>
    /// <param name="order">微信支付参数实例</param>
    /// <param name="key">密钥</param>
    /// <returns></returns>
    protected string getUnifiedOrderXml(UnifiedOrder order, string key)
    {
        string return_string = string.Empty;
        SortedDictionary <string, string> sParams = new SortedDictionary <string, string>();

        sParams.Add("appid", order.appid);
        sParams.Add("body", order.body);
        sParams.Add("mch_id", order.mch_id);
        sParams.Add("nonce_str", order.nonce_str);
        sParams.Add("notify_url", order.notify_url);
        if (order.openid != "")
        {
            sParams.Add("openid", order.openid);
        }
        sParams.Add("out_trade_no", order.out_trade_no);
        sParams.Add("spbill_create_ip", order.spbill_create_ip);
        sParams.Add("total_fee", order.total_fee.ToString());
        sParams.Add("trade_type", order.trade_type);
        order.sign = getsign(sParams, key);
        sParams.Add("sign", order.sign);

        //拼接成XML请求数据
        StringBuilder sbPay = new StringBuilder();

        foreach (KeyValuePair <string, string> k in sParams)
        {
            sbPay.Append("<" + k.Key + ">" + k.Value + "</" + k.Key + ">");
        }
        return_string = string.Format("<xml>{0}</xml>", sbPay.ToString());
        return(return_string);
    }
Ejemplo n.º 6
0
        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="OrderNo"></param>
        /// <returns></returns>
        public override object GetPaySign(string OrderNo, string SellerID, decimal TotalPrice, EnumPaySignType SignType, string ReturnUrl = "", string OpenId = "")
        {
            BLL.OrderService      orderService = new BLL.OrderService(CurrentOperatorUserID);
            DTO.Platform.OrderDTO order        = orderService.GetOrder(OrderNo);

            if (order != null)
            {
                #region 获取订单说明和描述

                string Subject = "-";
                string Body    = order.OrderType.GetEnumDescript();
                if (order.Details != null && order.Details.Count == 1)
                {
                    Subject = order.Details[0].Subject;
                }
                else if (order.Details != null)
                {
                    Subject = string.Format("共{0}件商品", order.Details.Count);
                }
                else
                {
                    Subject = string.Format("共{0}件商品", 0);
                }

                #endregion

                UnifiedOrder pay = new UnifiedOrder();

                if (SignType == EnumPaySignType.Web)
                {
                    return(pay.GetQRCodeUrlWhenWeb(OrderNo, Subject, Body, TotalPrice.ToString(), SellerID));
                }
                //H5支付方式
                else if (SignType == EnumPaySignType.Wap)
                {
                    return(pay.GetJumpUrlWhenMWeb(OrderNo, Subject, Body, TotalPrice.ToString(), SellerID));
                }
                //JS支付(公众号)
                else if (SignType == EnumPaySignType.Js)
                {
                    var pre_payId = pay.GetPrepayIdWhenJsSdk(OrderNo, Subject, Body, TotalPrice.ToString(), SellerID, OpenId, order.OrderOutID);
                    return(GetJsApiParameters(pre_payId, SellerID));
                }
                else if (SignType == EnumPaySignType.App)
                {
                    var pre_payId = pay.GetPrepayIdWhenApp(OrderNo, Subject, Body, TotalPrice.ToString(), SellerID);
                    return(GetAppApiParamters(pre_payId, SellerID));
                }
                else
                {
                    return(pay.GetQRCodeUrlWhenWeb(OrderNo, Subject, Body, TotalPrice.ToString(), SellerID));
                }
            }
            else
            {
                throw new System.ArgumentException("订单不存在");
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 微信统一下单接口xml参数整理
        /// </summary>
        /// <param name="order">微信支付参数实例</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string getUnifiedOrderXml(UnifiedOrder order, string key)
        {
            string return_string = string.Empty;
            SortedDictionary <string, string> sParams = new SortedDictionary <string, string>();

            sParams.Add("appid", order.appid);
            sParams.Add("attach", order.attach);
            sParams.Add("body", order.body);
            if (order.device_info != "")
            {
                sParams.Add("device_info", order.device_info);
            }
            sParams.Add("mch_id", order.mch_id);
            sParams.Add("nonce_str", order.nonce_str);
            sParams.Add("notify_url", order.notify_url);
            if (order.openid != "")
            {
                sParams.Add("openid", order.openid);
            }
            sParams.Add("out_trade_no", order.out_trade_no);
            sParams.Add("spbill_create_ip", order.spbill_create_ip);
            sParams.Add("total_fee", order.total_fee.ToString());
            sParams.Add("trade_type", order.trade_type);

            order.sign = GetSign(sParams, key);
            sParams.Add("sign", order.sign);

            //拼接成XML请求数据
            StringBuilder sbPay = new StringBuilder();

            foreach (KeyValuePair <string, string> k in sParams)
            {
                if (k.Key == "sign")
                {
                    continue;
                }
                //if (k.Key == "attach" || k.Key == "body" || k.Key == "sign")
                //{
                //    sbPay.Append("<" + k.Key + "><![CDATA[" + k.Value + "]]></" + k.Key + ">");
                //}
                //else
                //{
                sbPay.Append("<" + k.Key + ">" + k.Value + "</" + k.Key + ">");
                //}
                sbPay.Append("\n");
            }
            //sbPay.Append("<sign><![CDATA[" + sParams["sign"] + "]]></sign>");
            sbPay.Append("<sign>" + sParams["sign"] + "</sign>");

            return_string = string.Format("<xml>{0}</xml>", sbPay.ToString());
            //byte[] byteArray = Encoding.UTF8.GetBytes(return_string);
            //return_string = Encoding.GetEncoding("GBK").GetString(Encoding.UTF8.GetBytes(return_string));
            return(return_string);
        }
Ejemplo n.º 8
0
        public string GetPrepayId(UnifiedOrder order)
        {
            TenpayUnifiedOrderApi api = new TenpayUnifiedOrderApi(_config, order);

            var result = _request.DoPost(_config, api);

            string prepayId = null;

            result.TryGetValue("prepay_id", out prepayId);

            return(prepayId);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Js-API支付
        /// </summary>
        /// <param name="info"></param>
        /// <param name="signType"></param>
        /// <returns></returns>
        public ChooseWxPayConfig JsApiPay(UnifiedOrderInfo info)
        {
            var unifiedOrder = new UnifiedOrder()
            {
                nonce_str        = info.NonceStr,
                appid            = _baseSettings.AppId,
                mch_id           = _baseSettings.MchId,
                out_trade_no     = info.TradeNo,
                sign_type        = info.SignType.GetDescription(),
                total_fee        = (int)(info.TotalFee * 100),
                openid           = info.OpenId,
                notify_url       = info.NotifyUrl,
                fee_type         = info.FeeType,
                spbill_create_ip = info.DeviceIp,
                time_start       = info.StartTime.ToString("yyyyMMddHHmmss"),
                time_expire      = info.EndTime.ToString("yyyyMMddHHmmss"),
                attach           = info.Attach,
                body             = info.Body,
                detail           = info.Detail,
                goods_tag        = info.GoodTags,
                limit_pay        = info.UseLimitPay ? "no_credit" : null,
                trade_type       = info.TradeType,
                scene_info       = info.SceneInfo
            };
            //转换字典
            var dic = UtilityHelper.Obj2Dictionary(unifiedOrder);

            //生成签名
            unifiedOrder.sign = SignatureGenerater.GenerateWxPaySignature(dic, _baseSettings.ApiKey, info.SignType);
            //统一下单
            var unifiedOrderResult = _wxPayInterfaceCaller.UnifiedOrder(unifiedOrder);

            var chooseWxPayConfig = new ChooseWxPayConfig()
            {
                nonceStr  = info.NonceStr,
                timestamp = info.TimeStamp,
                package   = unifiedOrderResult.prepay_id,
                signType  = info.SignType.GetDescription()
            };
            var paySign = SignatureGenerater.GenerateWxPaySignature(new Dictionary <string, string>()
            {
                { "appId", _baseSettings.AppId },
                { "timeStamp", chooseWxPayConfig.timestamp.ToString() },
                { "nonceStr", chooseWxPayConfig.nonceStr },
                { "package", chooseWxPayConfig.package },
                { "signType", chooseWxPayConfig.signType }
            }, _baseSettings.ApiKey, info.SignType);

            chooseWxPayConfig.paySign = paySign;

            return(chooseWxPayConfig);
        }
Ejemplo n.º 10
0
        public TenpayUnifiedOrderApi(WxAppInfoConfig config, UnifiedOrder order)
        {
            SortedDictionary <string, object> sParams = new SortedDictionary <string, object>();

            sParams.Add("appid", config.AppId);                      //公众账号ID
            sParams.Add("mch_id", config.PayMchId);                  //商户号
            sParams.Add("nonce_str", CommonUtil.GetNonceStr());      //随机字符串
            sParams.Add("notify_url", config.PayResultNotifyUrl);    //通知地址
            sParams.Add("trade_type", order.trade_type);             //交易类型
            sParams.Add("spbill_create_ip", order.spbill_create_ip); //终端IP
            sParams.Add("out_trade_no", order.out_trade_no);         //商户订单号
            sParams.Add("total_fee", order.total_fee);               //标价金额
            sParams.Add("body", order.body);                         //商品描述
            sParams.Add("time_expire", order.time_expire);           //订单过期时间
            sParams.Add("attach", order.attach);                     //附加数据
            if (order.trade_type == "JSAPI")
            {
                sParams.Add("openid", order.openid);//用户标识
            }

            if (!string.IsNullOrEmpty(order.goods_tag))
            {
                sParams.Add("goods_tag", order.goods_tag);//商品优惠标识
            }

            if (order.trade_type == "MWEB")
            {
                sParams.Add("scene_info", "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://mobile.17fanju.com\",\"wap_name\": \"贩聚社团\"}}");//场景信息
            }
            //sParams.Add("device_info", "WEB");//设备号
            //sParams.Add("sign_type", "");//签名类型
            //sParams.Add("detail", "");商品详情
            //sParams.Add("attach", "");附加数据
            //sParams.Add("fee_type", "");//标价币种
            //sParams.Add("time_start", "");//交易起始时间
            //sParams.Add("time_expire", "");//交易结束时间
            //sParams.Add("goods_tag", "");//订单优惠标记
            //sParams.Add("product_id", "");//商品ID
            //sParams.Add("limit_pay", "");//指定支付方式
            //sParams.Add("openid", "openid");//用户标识
            //sParams.Add("scene_info", "");//场景信息
            string sign = MakeSign(sParams, config.PayKey);

            sParams.Add("sign", sign);//签名


            _postData = GetXml(sParams);
        }
Ejemplo n.º 11
0
 public JsonResult PreparePay([FromBody] UnifiedOrder unifiedOrder)
 {
     try
     {
         _log.Info("扫码预支付接口");
         UnifiedOrderBack unifiedOrderBack;
         string           message;
         var result = (wxHandle.SMUnifiedOrder(unifiedOrder, out unifiedOrderBack, out message));
         return(BuildJsonResult(unifiedOrderBack, result, message));
     }
     catch (Exception exc)
     {
         _log.Fatal(exc, $"扫码预支付接口:{exc.Message}");
         return(BuildJsonResult <UnifiedOrderBack>(null, false, exc.Message));
     }
 }
Ejemplo n.º 12
0
        //public UnifiedOrderResult UnifiedOrder(UnifiedOrder order)
        //{
        //    var rt = new UnifiedOrderResult();
        //    TenpayUnifiedOrderApi api = new TenpayUnifiedOrderApi(_config, order);

        //    var result = _request.DoPost(_config, api);

        //    string prepayId = null;

        //    result.TryGetValue("prepay_id", out prepayId);

        //    rt.PrepayId = prepayId;
        //    return rt;
        //}

        public UnifiedOrderResult UnifiedOrder(UnifiedOrder order)
        {
            var rt = new UnifiedOrderResult();

            TenpayUnifiedOrderApi api = new TenpayUnifiedOrderApi(_config, order);

            var    result   = _request.DoPost(_config, api);
            string prepayId = null;
            string code_url = null;

            result.TryGetValue("prepay_id", out prepayId);
            result.TryGetValue("code_url", out code_url);
            rt.PrepayId = prepayId;
            rt.CodeUrl  = code_url;
            return(rt);
        }
Ejemplo n.º 13
0
        static void Test()
        {
            var uni = new UnifiedOrder
            {
                Body           = "test",
                OutTradeNo     = DateTime.Now.ToString("yyMMddhhmmss"),
                ToalFee        = 1,
                SpbillCreateIP = "8.8.8.8",
                NotifyURL      = "http://www.abcd.com",
                TradeType      = "NATIVE",
                ProductID      = "123456"
            };
            WXPayMethods method = new WXPayMethods();

            method.UnifiedOrder(uni);
        }
Ejemplo n.º 14
0
    /// <summary>
    /// 获取prepay_id
    /// </summary>
    public string getPrepay_id(UnifiedOrder order, string key)
    {
        string prepay_id    = "";
        string post_data    = getUnifiedOrderXml(order, key);
        string request_data = PostXmlToUrl(UnifiedPayUrl, post_data);
        SortedDictionary <string, string> requestXML = GetInfoFromXml(request_data);

        foreach (KeyValuePair <string, string> k in requestXML)
        {
            if (k.Key == "prepay_id")
            {
                prepay_id = k.Value;
                break;
            }
        }
        return(prepay_id);
    }
Ejemplo n.º 15
0
        /// <summary>
        /// H5支付
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public string H5Pay(UnifiedOrderInfo info)
        {
            var unifiedOrder = new UnifiedOrder()
            {
                nonce_str        = info.NonceStr,
                appid            = _baseSettings.AppId,
                mch_id           = _baseSettings.MchId,
                out_trade_no     = info.TradeNo,
                sign_type        = info.SignType.GetDescription(),
                total_fee        = (int)(info.TotalFee * 100),
                openid           = info.OpenId,
                notify_url       = info.NotifyUrl,
                fee_type         = info.FeeType,
                spbill_create_ip = info.DeviceIp,
                time_start       = info.StartTime.ToString("yyyyMMddHHmmss"),
                time_expire      = info.EndTime.ToString("yyyyMMddHHmmss"),
                attach           = info.Attach,
                body             = info.Body,
                detail           = info.Detail,
                goods_tag        = info.GoodTags,
                limit_pay        = info.UseLimitPay ? "no_credit" : null,
                trade_type       = info.TradeType,
                scene_info       = info.SceneInfo
            };
            //转换字典
            var dic = UtilityHelper.Obj2Dictionary(unifiedOrder);

            //生成签名
            unifiedOrder.sign = SignatureGenerater.GenerateWxPaySignature(dic, _baseSettings.ApiKey, info.SignType);
            //统一下单
            var unifiedOrderResult = _wxPayInterfaceCaller.UnifiedOrder(unifiedOrder);

            var mWebUrl = unifiedOrderResult.mweb_url;

            if (!string.IsNullOrEmpty(info.RedirectUrl))
            {
                mWebUrl += $"&redirect_url={HttpUtility.UrlEncode(info.RedirectUrl)}";
            }

            return(mWebUrl);
        }
Ejemplo n.º 16
0
        public UnifiedOrderResult UnifiedOrderByNative(WxAppInfoConfig config, string merchantId, string orderSn, decimal orderAmount, string goods_tag, string ip, string body, DateTime time_expire)
        {
            var ret = new UnifiedOrderResult();

            TenpayUtil tenpayUtil = new TenpayUtil(config);

            UnifiedOrder unifiedOrder = new UnifiedOrder();

            unifiedOrder.openid           = "";
            unifiedOrder.out_trade_no     = orderSn;                            //商户订单号
            unifiedOrder.spbill_create_ip = ip;                                 //终端IP
            unifiedOrder.total_fee        = Convert.ToInt32(orderAmount * 100); //标价金额
            unifiedOrder.body             = body;                               //商品描述
            unifiedOrder.trade_type       = "NATIVE";
            unifiedOrder.time_expire      = time_expire.ToString("yyyyMMddHHmmss");
            unifiedOrder.goods_tag        = goods_tag;
            unifiedOrder.attach           = "{\"merchantId\":\"" + merchantId + "\"}";
            ret = tenpayUtil.UnifiedOrder(unifiedOrder);

            return(ret);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// NATIVE第二种扫码支付
        /// </summary>
        /// <returns></returns>
        public string Code()
        {
            //根据什么生成订单号   价格  商品名称  附加信息

            UnifiedOrder order = new UnifiedOrder();

            order.appid       = tenpay.WeChartConfigItem.appid;
            order.attach      = "vinson1";
            order.body        = "极客美家NATIVE支付正式测试";//订单描述
            order.device_info = "";
            order.mch_id      = tenpay.WeChartConfigItem.mch_id;
            order.nonce_str   = TenpayUtil.getNoncestr();                                                                   //随机字符串
            order.notify_url  = "http://mobile.mj100.com/test/h?id=100";                                                    //回调网址

            order.out_trade_no     = "20156666978542323" + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString(); //订单号
            order.trade_type       = "NATIVE";
            order.spbill_create_ip = Request.UserHostAddress;
            order.total_fee        = 1;
            //order.total_fee = 1;
            string Code_url = tenpay.TenpayUtil.getCode_url(order, tenpay.WeChartConfigItem.key);//商户key

            return(Code_url);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// native扫码支付
        /// </summary>
        /// <returns></returns>
        public string Code3()
        {
            string postStr = @"<xml><appid><![CDATA[wx2c2f2e7b5b62daa1]]></appid>
<openid><![CDATA[o8r91jjmQWUqO8zrq4rxL0QVTEYs]]></openid>
<mch_id><![CDATA[1246407101]]></mch_id>
<is_subscribe><![CDATA[Y]]></is_subscribe>
<nonce_str><![CDATA[x20MklmXIxrD7cGE]]></nonce_str>
<product_id><![CDATA[888654444]]></product_id>
<sign><![CDATA[77B6BAE35570D78DE1BA99B99CD7803B]]></sign>
</xml>
";

            System.IO.File.AppendAllText(HttpContext.Server.MapPath("") + "native.txt", postStr + ":" + DateTime.Now.ToSafeString() + "\r\n\r\n");

            SortedDictionary <string, string> dic = TenpayUtil.GetInfoFromXml(postStr);

            string osign = dic["sign"];//微信sign


            string sign = TenpayUtil.getsign(dic, "43804496F28A4F0FBF1195AA0F1Abcde");//自己加密后的sign


            #region 取到的各种值
            string appid        = dic["appid"];
            string openid       = dic["openid"];
            string mach_id      = dic["mch_id"];
            string is_subscribe = dic["is_subscribe"];
            string nonce_str    = dic["nonce_str"];
            string product_id   = dic["product_id"];
            #endregion

            System.IO.File.AppendAllText(HttpContext.Server.MapPath("") + "native.txt", product_id + ":" + DateTime.Now.ToSafeString() + "\r\n\r\n");

            #region 统一下单
            UnifiedOrder order = new UnifiedOrder();
            order.appid            = "wx2c2f2e7b5b62daa1";
            order.attach           = "vinson1";
            order.body             = "微信扫码回调测试product_id:" + product_id;//订单描述
            order.device_info      = "";
            order.mch_id           = "1246407101";
            order.nonce_str        = TenpayUtil.getNoncestr();                                                              //随机字符串
            order.notify_url       = "http://mobile.mj100.com/test/h?id=100";                                               //回调网址
            order.openid           = openid;
            order.out_trade_no     = "20156666978542323" + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString(); //订单号
            order.trade_type       = "NATIVE";
            order.spbill_create_ip = Request.UserHostAddress;
            order.total_fee        = 1;
            //order.total_fee = 1;
            string prepay_id = tenpay.TenpayUtil.getPrepay_id(order, "43804496F28A4F0FBF1195AA0F1Abcde");//商户key
            #endregion

            System.IO.File.AppendAllText(HttpContext.Server.MapPath("") + "native.txt", prepay_id + ":" + DateTime.Now.ToSafeString() + "\r\n\r\n");
            #region 响应请求
            SortedDictionary <string, string> pdic = new SortedDictionary <string, string>();

            pdic.Add("return_code", "SUCCESS");
            pdic.Add("return_msg", "");
            pdic.Add("appid", appid);
            pdic.Add("mch_id", mach_id);
            pdic.Add("nonce_str", nonce_str);
            pdic.Add("prepay_id", prepay_id);
            pdic.Add("result_code", "SUCCESS");
            pdic.Add("err_code_des", "");
            string nesign = TenpayUtil.getsign(pdic, "43804496F28A4F0FBF1195AA0F1Abcde");
            pdic.Add("sign", nesign);



            StringBuilder sbPay = new StringBuilder();
            foreach (KeyValuePair <string, string> k in pdic)
            {
                if (k.Key == "attach" || k.Key == "body" || k.Key == "sign")
                {
                    sbPay.Append("<" + k.Key + "><![CDATA[" + k.Value + "]]></" + k.Key + ">");
                }
                else
                {
                    sbPay.Append("<" + k.Key + ">" + k.Value + "</" + k.Key + ">");
                }
            }
            string return_string = string.Format("<xml>{0}</xml>", sbPay.ToString().TrimEnd(','));
            #endregion


            System.IO.File.AppendAllText(HttpContext.Server.MapPath("") + "native.txt", return_string + ":" + DateTime.Now.ToSafeString() + "\r\n\r\n");

            return(return_string);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 授权回调
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginOk(string code, string state)
        {
            string post_data          = "appid=" + "wx2c2f2e7b5b62daa1" + "&secret=" + "ed815afc669a9201a6070677d1771166" + "&code=" + code + "&grant_type=authorization_code";
            string requestData        = tenpay.TenpayUtil.PostXmlToUrl(tenpay.TenpayUtil.getAccess_tokenUrl(), post_data);
            JavaScriptSerializer js   = new JavaScriptSerializer();                  //实例化一个能够序列化数据的类
            authorization        auth = js.Deserialize <authorization>(requestData); //将json数据转化为对象类型并赋值给auth

            Session["auth"] = auth;                                                  //标识用户登录



            UnifiedOrder order = new UnifiedOrder();

            order.appid            = "wx2c2f2e7b5b62daa1";
            order.attach           = "vinson";
            order.body             = "100拍币";
            order.device_info      = "";
            order.mch_id           = "1246407101";
            order.nonce_str        = TenpayUtil.getNoncestr();
            order.notify_url       = "http://mobile.mj100.com"; //回调网址
            order.openid           = auth.openid;
            order.out_trade_no     = "2015666697854232";        //订单号
            order.trade_type       = "JSAPI";
            order.spbill_create_ip = Request.UserHostAddress;
            order.total_fee        = 100;
            //order.total_fee = 1;

            string prepay_id = tenpay.TenpayUtil.getPrepay_id(order, "43804496F28A4F0FBF1195AA0F1Abcde");

            string timeStamp = TenpayUtil.getTimestamp();


            string nonceStr = TenpayUtil.getNoncestr();

            SortedDictionary <string, string> sParams = new SortedDictionary <string, string>();

            sParams.Add("appId", "wx2c2f2e7b5b62daa1");
            sParams.Add("timeStamp", timeStamp);
            sParams.Add("nonceStr", nonceStr);
            sParams.Add("package", "prepay_id=" + prepay_id);
            sParams.Add("signType", "MD5");


            string paySign = TenpayUtil.getsign(sParams, "43804496F28A4F0FBF1195AA0F1Abcde");


            //var appId = "<%=appId %>";
            //var timeStamp = "<%=timeStamp %>";
            //var nonceStr = "<%=nonceStr %>";
            //var prepay_id = "<%=prepay_id %>";
            //var paySign = "<%=paySign %>";

            ViewBag.appId     = "wx2c2f2e7b5b62daa1";
            ViewBag.timeStamp = timeStamp;
            ViewBag.nonceStr  = nonceStr;

            ViewBag.prepay_id = prepay_id;

            ViewBag.paySign = paySign;



            ViewBag.openid = paySign + "我是paySign";



            return(View());
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 统一下单
        /// </summary>
        /// <param name="unifiedOrder">预支付实体</param>
        /// <param name="unifiedOrderBack">预支付返回实体</param>
        /// <param name="message">错误信息</param>
        /// <returns>交易是否成功</returns>
        internal bool SMUnifiedOrder(UnifiedOrder unifiedOrder, out UnifiedOrderBack unifiedOrderBack, out string message)
        {
            _log.Info("统一下单 SMUnifiedOrder 开始执行");
            var data = new WxPayData();

            if (string.IsNullOrEmpty(unifiedOrder.Body) || string.IsNullOrEmpty(unifiedOrder.Out_Trade_No))
            {
                message = "商户订单或商品描述不能为空";
                _log.Error(message);
                unifiedOrderBack = null;
                return(false);
            }
            if (unifiedOrder.Total_Fee < 0)
            {
                message = "标价金额不能小于0";
                _log.Error(message);
                unifiedOrderBack = null;
                return(false);
            }
            data.SetValue("body", unifiedOrder.Body);                 //商品描述
            data.SetValue("out_trade_no", unifiedOrder.Out_Trade_No); //商户订单号
            data.SetValue("total_fee", unifiedOrder.Total_Fee);       //总金额
            data.SetValue("trade_type", "NATIVE");                    //交易类型
            if (!string.IsNullOrEmpty(unifiedOrder.Detail))
            {
                data.SetValue("detail", unifiedOrder.Detail);//商品详情
            }
            if (!string.IsNullOrEmpty(unifiedOrder.Attach))
            {
                data.SetValue("attach", unifiedOrder.Attach);//附加数据
            }
            if (!string.IsNullOrEmpty(unifiedOrder.Fee_Type))
            {
                data.SetValue("fee_type", unifiedOrder.Fee_Type);//标价币种
            }
            if (!string.IsNullOrEmpty(unifiedOrder.Time_Start))
            {
                data.SetValue("time_start", unifiedOrder.Time_Start);//交易起始时间
            }
            if (!string.IsNullOrEmpty(unifiedOrder.Time_Expire))
            {
                data.SetValue("time_expire", unifiedOrder.Time_Expire);//交易结束时间
            }
            if (!string.IsNullOrEmpty(unifiedOrder.Goods_Tag))
            {
                data.SetValue("goods_tag", unifiedOrder.Goods_Tag);//商品标记
            }
            if (!string.IsNullOrEmpty(unifiedOrder.Product_ID))
            {
                data.SetValue("product_id", unifiedOrder.Product_ID);//商品ID
            }
            //统一下单
            _log.Info("统一下单,WxPayApi.UnifiedOrder");
            var result = WxPayApi.UnifiedOrder(data);

            if (result.GetValue("return_code").ToString().ToUpper() == "SUCCESS" && result.GetValue("result_code").ToString().ToUpper() == "SUCCESS")
            {
                _log.Info("统一下单处理成功");
                unifiedOrderBack = new UnifiedOrderBack()
                {
                    Code_Url     = result.GetValue("code_url")?.ToString(),
                    Err_Code     = result.GetValue("err_code")?.ToString(),
                    Err_Code_Des = result.GetValue("err_code_des")?.ToString(),
                    Prepay_ID    = result.GetValue("prepay_id")?.ToString(),
                    Result_Code  = result.GetValue("result_code")?.ToString(),
                    Return_Code  = result.GetValue("return_code")?.ToString(),
                    Return_Msg   = result.GetValue("return_msg")?.ToString(),
                    Rrade_Type   = result.GetValue("trade_type")?.ToString()
                };
                message = "";
                return(true);
            }
            else
            {
                var return_msg   = result.GetValue("return_msg")?.ToString();
                var err_code_des = result.GetValue("err_code_des")?.ToString();
                message = $"{return_msg},{err_code_des}";
                _log.Error($"统一下单处理失败:{message}");
                unifiedOrderBack = null;
                return(false);
            }
        }
Ejemplo n.º 21
0
        public JsonResult <PayOrder> Post(UnifiedOrder obj)
        {
            ClassLoger.Info("PayController.Post", obj.PayTyp.ToString(), obj.product_id, obj.productType.TryToString());
            JsonResult <PayOrder> result = new JsonResult <PayOrder>();

            result.code = 1;
            result.msg  = "OK";
            PayOrderBll porderbll = new PayOrderBll();

            try
            {
                if (obj.PayTyp == 1)
                {
                    JsApiPay jsApiPay = new JsApiPay();
                    jsApiPay.openid = "";
                    if (!obj.openid.IsNull())
                    {
                        WeChatUserBll wuserbll = new WeChatUserBll();
                        WeChatUser    wuser    = wuserbll.GetWeChatUserByUnionID(obj.openid);
                        jsApiPay.openid = wuser.ServiceOpenID;
                    }
                    else if (!obj.userid.IsNull())
                    {
                        UserInfoBll ubll = new UserInfoBll();
                        var         user = ubll.GetUserinfoByID(obj.userid);
                        if (!user.Openid.IsNull())
                        {
                            WeChatUserBll wuserbll = new WeChatUserBll();
                            WeChatUser    wuser    = wuserbll.GetWeChatUserByUnionID(user.Openid);
                            jsApiPay.openid = wuser.ServiceOpenID;
                        }
                    }
                    jsApiPay.total_fee  = 1;
                    jsApiPay.trade_type = obj.trade_type;
                    if (obj.productType == 1)
                    {
                        //查询商品信息,获取商品价格
                        double Price = 0.1;
                        jsApiPay.total_fee = (Price * 100).TryToInt();
                        jsApiPay.body      = "商品名称";
                    }
                    jsApiPay.attach = "北京xx";
                    string out_trade_no = porderbll.GetOnlineOrder(PayTypeEnum.WeChart);
                    jsApiPay.out_trade_no = out_trade_no;
                    jsApiPay.product_id   = obj.product_id;

                    ClassLoger.Info("api/Pay/UnifiedOrder", "total_fee", jsApiPay.total_fee.ToString());
                    WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult();
                    PayOrder  porder             = new PayOrder();

                    if (unifiedOrderResult.GetValue("return_code").TryToString() == "SUCCESS" && unifiedOrderResult.GetValue("result_code").TryToString() == "SUCCESS")
                    {
                        if (unifiedOrderResult.IsSet("code_url"))
                        {
                            string code_url = unifiedOrderResult.GetValue("code_url").TryToString();
                            string filename = string.Format("WXPY{0}.png", code_url.MD5());
                            string filepath = Path.Combine(SystemSet.ResourcesPath, SystemSet.QrCodePic, filename);
                            if (!File.Exists(filepath))
                            {
                                QrCodeHelper.CreateImgCode(code_url, filepath);
                            }
                            porder.code_url = Path.Combine(SystemSet.WebResourcesSite, SystemSet.QrCodePic, filename);
                        }
                        porder.OnlineOrder = out_trade_no;
                        porder.openid      = obj.openid;
                        porder.PayState    = PayStateEnum.Unpaid;
                        porder.PayType     = PayTypeEnum.WeChart;
                        porder.prepay_id   = unifiedOrderResult.GetValue("prepay_id").TryToString();
                        porder.product_id  = obj.product_id;
                        porder.total_fee   = jsApiPay.total_fee;
                        porder.trade_type  = obj.trade_type;
                        porder.CreateTime  = DateTime.Now;
                        porder.UserID      = obj.userid;
                        porder.ID          = porderbll.AddPayOrder(porder);
                        result.Result      = porder;
                        return(result);
                    }
                    else
                    {
                        result.code      = 0;
                        result.msg       = unifiedOrderResult.GetValue("return_code").TryToString();
                        result.ResultMsg = unifiedOrderResult.GetValue("result_code").TryToString();
                    }
                }
            } catch (Exception ex)
            {
                result.code = -1;
                result.msg  = "PayController.unifiedorder:" + ex.Message;
            }
            return(result);
        }
Ejemplo n.º 22
0
        /// <summary>
        ///     Get weixin prepayId
        /// </summary>
        /// <param name="nonceStr"></param>
        /// <param name="orderPaymentId"></param>
        /// <param name="amount"></param>
        /// <param name="wxOpenId"></param>
        /// <param name="attach"></param>
        /// <param name="billCreationIp"></param>
        /// <returns></returns>
        private async Task <string> UnifiedOrder(string nonceStr, string orderPaymentId, decimal amount, string wxOpenId, string billCreationIp, string attach)
        {
            UnifiedOrder unifiedOrder = new UnifiedOrder {
                MchId     = _options.WxMchId,
                AppId     = _options.WxAppId,
                NotifyUrl = _options.WxPaymentNotifyUrl,
                SignType  = "MD5",
                TradeType = "JSAPI",
                Body      = $"{_options.WxPlatformName}订单",

                NonceStr       = nonceStr,
                OutTradeNo     = orderPaymentId,
                TotalFee       = Math.Round(amount * 100).ToString(), // unit: fen max scale is 2
                SPBillCreateIP = billCreationIp,
                OpenId         = wxOpenId,
                Attach         = attach
            };

            // Sign
            unifiedOrder.Sign = BuildSignString(unifiedOrder);

            // Xml
            string requestXml = BuildRequestXml(unifiedOrder);

            if (_options.WxIsDebug)
            {
                _logger.EnqueueMessage($"UnifiedOrder: {requestXml}");
            }

            try
            {
                HttpContent content = new ByteArrayContent(Encoding.UTF8.GetBytes(requestXml));
                var         res     = await _client.PostAsync("https://api.mch.weixin.qq.com/pay/unifiedorder", content);

                string xml = await res.Content.ReadAsStringAsync();

                if (_options.WxIsDebug)
                {
                    _logger.EnqueueMessage(xml);
                }

                //bool isReturnSuccess = xml.IndexOf("<return_code><![CDATA[SUCCESS]]></return_code>", StringComparison.Ordinal) != -1;
                bool isReturnSuccess = xml.StartsWith("<xml><return_code><![CDATA[SUCCESS]]></return_code>", StringComparison.Ordinal);
                if (!isReturnSuccess)
                {
                    return(string.Empty);
                }

                bool isResultSuccess = xml.IndexOf("<result_code><![CDATA[SUCCESS]]></result_code>", StringComparison.Ordinal) != -1;
                return(isResultSuccess ? PrepayIdPattern.Match(xml).Groups[1].Value : string.Empty /*error*/);
            }
            catch (Exception ex)
            {
                _logger.EnqueueMessage($"{nameof(WeixinPay)}.{nameof(UnifiedOrder)} error. Message: {ex.Message} InnerMessage: {ex.InnerException?.Message} StackTrace: {ex.StackTrace}");
            }

            return(string.Empty);

            string BuildRequestXml(UnifiedOrder order)
            {
                StringBuilder xmlBuilder = new StringBuilder("<xml>");

                xmlBuilder.Append($"<appid>{order.AppId}</appid>");

                if (!string.IsNullOrEmpty(order.Attach))
                {
                    xmlBuilder.Append($"<attach>{order.Attach}</attach>");
                }
                if (!string.IsNullOrEmpty(order.Body))
                {
                    xmlBuilder.Append($"<body>{order.Body}</body>");
                }
                if (!string.IsNullOrEmpty(order.Detail))
                {
                    xmlBuilder.Append($"<detail>{order.Detail}</detail>");
                }
                if (!string.IsNullOrEmpty(order.DeviceInfo))
                {
                    xmlBuilder.Append($"<device_info>{order.DeviceInfo}</device_info>");
                }
                if (!string.IsNullOrEmpty(order.FeeType))
                {
                    xmlBuilder.Append($"<fee_type>{order.FeeType}</fee_type>");
                }
                if (!string.IsNullOrEmpty(order.GoodsTag))
                {
                    xmlBuilder.Append($"<goods_tag>{order.GoodsTag}</goods_tag>");
                }
                if (!string.IsNullOrEmpty(order.LimitPay))
                {
                    xmlBuilder.Append($"<limit_pay>{order.LimitPay}</limit_pay>");
                }
                if (!string.IsNullOrEmpty(order.MchId))
                {
                    xmlBuilder.Append($"<mch_id>{order.MchId}</mch_id>");
                }
                if (!string.IsNullOrEmpty(order.NonceStr))
                {
                    xmlBuilder.Append($"<nonce_str>{order.NonceStr}</nonce_str>");
                }
                if (!string.IsNullOrEmpty(order.NotifyUrl))
                {
                    xmlBuilder.Append($"<notify_url>{order.NotifyUrl}</notify_url>");
                }
                if (!string.IsNullOrEmpty(order.OpenId))
                {
                    xmlBuilder.Append($"<openid>{order.OpenId}</openid>");
                }
                if (!string.IsNullOrEmpty(order.OutTradeNo))
                {
                    xmlBuilder.Append($"<out_trade_no>{order.OutTradeNo}</out_trade_no>");
                }
                if (!string.IsNullOrEmpty(order.ProductId))
                {
                    xmlBuilder.Append($"<product_id>{order.ProductId}</product_id>");
                }
                if (!string.IsNullOrEmpty(order.Receipt))
                {
                    xmlBuilder.Append($"<receipt>{order.Receipt}</receipt>");
                }
                if (!string.IsNullOrEmpty(order.SceneInfo))
                {
                    xmlBuilder.Append($"<scene_info>{order.SceneInfo}</scene_info>");
                }
                if (!string.IsNullOrEmpty(order.Sign))
                {
                    xmlBuilder.Append($"<sign>{order.Sign}</sign>");
                }
                if (!string.IsNullOrEmpty(order.SignType))
                {
                    xmlBuilder.Append($"<sign_type>{order.SignType}</sign_type>");
                }
                if (!string.IsNullOrEmpty(order.SPBillCreateIP))
                {
                    xmlBuilder.Append($"<spbill_create_ip>{order.SPBillCreateIP}</spbill_create_ip>");
                }
                if (!string.IsNullOrEmpty(order.TimeExpire))
                {
                    xmlBuilder.Append($"<time_expire>{order.TimeExpire}</time_expire>");
                }
                if (!string.IsNullOrEmpty(order.TimeStart))
                {
                    xmlBuilder.Append($"<time_start>{order.TimeStart}</time_start>");
                }
                if (!string.IsNullOrEmpty(order.TotalFee))
                {
                    xmlBuilder.Append($"<total_fee>{order.TotalFee}</total_fee>");
                }
                if (!string.IsNullOrEmpty(order.TradeType))
                {
                    xmlBuilder.Append($"<trade_type>{order.TradeType}</trade_type>");
                }

                return(xmlBuilder.Append("</xml>").ToString());
            }

            string BuildSignString(UnifiedOrder order)
            {
                StringBuilder signBuilder = new StringBuilder();

                signBuilder.Append($"appid={order.AppId}");

                if (!string.IsNullOrEmpty(order.Attach))
                {
                    signBuilder.Append($"&attach={order.Attach}");
                }
                if (!string.IsNullOrEmpty(order.Body))
                {
                    signBuilder.Append($"&body={order.Body}");
                }
                if (!string.IsNullOrEmpty(order.Detail))
                {
                    signBuilder.Append($"&detail={order.Detail}");
                }
                if (!string.IsNullOrEmpty(order.DeviceInfo))
                {
                    signBuilder.Append($"&device_info={order.DeviceInfo}");
                }
                if (!string.IsNullOrEmpty(order.FeeType))
                {
                    signBuilder.Append($"&fee_type={order.FeeType}");
                }
                if (!string.IsNullOrEmpty(order.GoodsTag))
                {
                    signBuilder.Append($"&goods_tag={order.GoodsTag}");
                }
                if (!string.IsNullOrEmpty(order.LimitPay))
                {
                    signBuilder.Append($"&limit_pay={order.LimitPay}");
                }
                if (!string.IsNullOrEmpty(order.MchId))
                {
                    signBuilder.Append($"&mch_id={order.MchId}");
                }
                if (!string.IsNullOrEmpty(order.NonceStr))
                {
                    signBuilder.Append($"&nonce_str={order.NonceStr}");
                }
                if (!string.IsNullOrEmpty(order.NotifyUrl))
                {
                    signBuilder.Append($"&notify_url={order.NotifyUrl}");
                }
                if (!string.IsNullOrEmpty(order.OpenId))
                {
                    signBuilder.Append($"&openid={order.OpenId}");
                }
                if (!string.IsNullOrEmpty(order.OutTradeNo))
                {
                    signBuilder.Append($"&out_trade_no={order.OutTradeNo}");
                }
                if (!string.IsNullOrEmpty(order.ProductId))
                {
                    signBuilder.Append($"&product_id={order.ProductId}");
                }
                if (!string.IsNullOrEmpty(order.Receipt))
                {
                    signBuilder.Append($"&receipt={order.Receipt}");
                }
                if (!string.IsNullOrEmpty(order.SceneInfo))
                {
                    signBuilder.Append($"&scene_info={order.SceneInfo}");
                }
                if (!string.IsNullOrEmpty(order.SignType))
                {
                    signBuilder.Append($"&sign_type={order.SignType}");
                }
                if (!string.IsNullOrEmpty(order.SPBillCreateIP))
                {
                    signBuilder.Append($"&spbill_create_ip={order.SPBillCreateIP}");
                }
                if (!string.IsNullOrEmpty(order.TimeExpire))
                {
                    signBuilder.Append($"&time_expire={order.TimeExpire}");
                }
                if (!string.IsNullOrEmpty(order.TimeStart))
                {
                    signBuilder.Append($"&time_start={order.TimeStart}");
                }
                if (!string.IsNullOrEmpty(order.TotalFee))
                {
                    signBuilder.Append($"&total_fee={order.TotalFee}");
                }
                if (!string.IsNullOrEmpty(order.TradeType))
                {
                    signBuilder.Append($"&trade_type={order.TradeType}");
                }

                signBuilder.Append($"&key={_options.WxMchKey}");
                return(signBuilder.ToString().GetHashUTF8().ToUpperInvariant());
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// native第一种扫码支付
        /// </summary>
        /// <returns></returns>
        public string Code2()
        {
            try
            {
                #region 获取到请求的值
                Stream s = System.Web.HttpContext.Current.Request.InputStream;
                byte[] b = new byte[s.Length];
                s.Read(b, 0, (int)s.Length);
                string postStr = Encoding.UTF8.GetString(b);
                #endregion



                SortedDictionary <string, string> dic = TenpayUtil.GetInfoFromXml(postStr);

                string osign = dic["sign"];//微信sign


                string sign = TenpayUtil.getsign(dic, tenpay.WeChartConfigItem.key);//自己加密后的sign



                #region 取到的各种值
                string appid        = dic["appid"];
                string openid       = dic["openid"];
                string mach_id      = dic["mch_id"];
                string is_subscribe = dic["is_subscribe"];
                string nonce_str    = dic["nonce_str"];
                string product_id   = dic["product_id"];//产品id或者订单号
                #endregion

                //    System.IO.File.AppendAllText(HttpContext.Server.MapPath("") + "native.txt", product_id + ":" + DateTime.Now.ToSafeString() + "\r\n\r\n");

                #region 统一下单
                UnifiedOrder order = new UnifiedOrder();
                order.appid            = tenpay.WeChartConfigItem.appid;
                order.attach           = "vinson1";
                order.body             = "微信扫码回调测试product_id:" + product_id;//订单描述
                order.device_info      = "";
                order.mch_id           = tenpay.WeChartConfigItem.mch_id;
                order.nonce_str        = TenpayUtil.getNoncestr();                                                              //随机字符串
                order.notify_url       = "http://mobile.mj100.com/test/h?id=100";                                               //回调网址
                order.openid           = openid;
                order.out_trade_no     = "20156666978542323" + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString(); //订单号
                order.trade_type       = "NATIVE";
                order.spbill_create_ip = Request.UserHostAddress;
                order.total_fee        = 1;
                //order.total_fee = 1;
                string prepay_id = tenpay.TenpayUtil.getPrepay_id(order, tenpay.WeChartConfigItem.key);//商户key
                #endregion

                //    System.IO.File.AppendAllText(HttpContext.Server.MapPath("") + "native.txt", prepay_id + ":" + DateTime.Now.ToSafeString() + "\r\n\r\n");


                #region 响应请求
                SortedDictionary <string, string> pdic = new SortedDictionary <string, string>();
                pdic.Add("return_code", "SUCCESS");
                pdic.Add("return_msg", "");
                pdic.Add("appid", appid);
                pdic.Add("mch_id", mach_id);
                pdic.Add("nonce_str", nonce_str);
                pdic.Add("prepay_id", prepay_id);
                pdic.Add("result_code", "SUCCESS");
                pdic.Add("err_code_des", "");
                string nesign = TenpayUtil.getsign(pdic, tenpay.WeChartConfigItem.key);
                pdic.Add("sign", nesign);



                StringBuilder sbPay = new StringBuilder();
                foreach (KeyValuePair <string, string> k in pdic)
                {
                    if (k.Key == "attach" || k.Key == "body" || k.Key == "sign")
                    {
                        sbPay.Append("<" + k.Key + "><![CDATA[" + k.Value + "]]></" + k.Key + ">");
                    }
                    else
                    {
                        sbPay.Append("<" + k.Key + ">" + k.Value + "</" + k.Key + ">");
                    }
                }
                string return_string = string.Format("<xml>{0}</xml>", sbPay.ToString().TrimEnd(','));
                #endregion



                return(return_string);
            }
            catch (Exception e)
            {
                System.IO.File.AppendAllText(HttpContext.Server.MapPath("") + "native.txt", e.Message + ":" + DateTime.Now.ToSafeString() + "\r\n\r\n");
                return("");
            }
        }
Ejemplo n.º 24
0
    private void WxPayJS()
    {
        string siteUrl = MojoCube.Web.Site.Cache.GetDomain(strLanguage);  //获取网站的域名

        MojoCube.Web.Payment.List payment = new MojoCube.Web.Payment.List();
        payment.GetDataByType(2);

        MojoCube.Web.Order.List order = new MojoCube.Web.Order.List();
        order.GetData(int.Parse(ViewState["pk_Order"].ToString()));

        if (order.pk_Order == 0 || order.StatusID > 0 || order.fk_Member.ToString() != Session["Member_UserID"].ToString())
        {
            Response.Redirect(MojoCube.Web.Site.Cache.GetUrlExtension("Order", strLanguage));
        }

        appId = payment.AppID;
        string partnerId = payment.PartnerID;
        string key       = payment.KeyCode;
        string secret    = payment.Secret;
        int    price     = (int)(order.Amount * 100);
        string body      = order.Description;

        if (body.Length > 20)
        {
            body = body.Substring(0, 20);
        }

        //调用【网页授权获取用户信息】接口获取用户的openid和access_token
        GetOpenidAndAccessToken(appId, secret);

        UnifiedOrder order1 = new UnifiedOrder();

        order1.appid            = appId;
        order1.mch_id           = partnerId;
        order1.nonce_str        = TenpayUtil.getNoncestr();
        order1.body             = body;
        order1.out_trade_no     = order.OrderNumber;
        order1.total_fee        = price;
        order1.spbill_create_ip = Page.Request.UserHostAddress;
        order1.notify_url       = siteUrl + MojoCube.Web.Site.Cache.GetUrlExtension("WxPay_Notify", strLanguage);
        order1.trade_type       = "JSAPI";
        if (ViewState["OpenID"] != null)
        {
            order1.openid = ViewState["OpenID"].ToString();  //JSAPI必须传入openid
        }

        TenpayUtil tu = new TenpayUtil();

        prepayId  = tu.getPrepay_id(order1, key);
        nonceStr  = order1.nonce_str;
        timeStamp = TenpayUtil.getTimestamp();

        SortedDictionary <string, string> sParams = new SortedDictionary <string, string>();

        sParams.Add("appId", appId);
        sParams.Add("nonceStr", nonceStr);
        sParams.Add("package", "prepay_id=" + prepayId);
        sParams.Add("signType", "MD5");
        sParams.Add("timeStamp", timeStamp);
        sign = tu.getsign(sParams, key);
    }
Ejemplo n.º 25
0
        /// <summary>
        /// 实际支付页
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult Xd(string code, string state)
        {
            //   Session["auth"] = auth;//标识用户登录
            MJAPI.Controllers.WechartController.authorization auth = null;

            if (Session["auth"] != null)
            {
                auth = Session["auth"] as MJAPI.Controllers.WechartController.authorization;
            }
            else
            {
                Response.Redirect("http://mobile.mj100.com/wechart/login");
            }


            #region 发送预支付单
            UnifiedOrder order = new UnifiedOrder();
            order.appid       = tenpay.WeChartConfigItem.appid;
            order.attach      = "vinson1";
            order.body        = "极客美家支付正式测试";//订单描述
            order.device_info = "";
            order.mch_id      = tenpay.WeChartConfigItem.mch_id;
            order.nonce_str   = TenpayUtil.getNoncestr();                                                                //随机字符串
            order.notify_url  = "http://mobile.mj100.com/test/h?id=100";                                                 //回调网址
            order.openid      = auth.openid;                                                                             //每一个微信号的唯一标识都不一样

            order.out_trade_no     = "20156666978542323" + DateTime.Now.Day + DateTime.Now.Minute + DateTime.Now.Second; //订单号
            order.trade_type       = "JSAPI";
            order.spbill_create_ip = Request.UserHostAddress;
            order.total_fee        = 1;

            string prepay_id = tenpay.TenpayUtil.getPrepay_id(order, tenpay.WeChartConfigItem.key);//商户key
            #endregion



            #region 得到paySign
            string timeStamp = TenpayUtil.getTimestamp();
            string nonceStr  = TenpayUtil.getNoncestr().ToUpper();
            SortedDictionary <string, string> sParams = new SortedDictionary <string, string>();


            sParams.Add("appId", tenpay.WeChartConfigItem.appid);

            sParams.Add("timeStamp", timeStamp);

            sParams.Add("nonceStr", nonceStr);

            sParams.Add("package", "prepay_id=" + prepay_id);

            sParams.Add("signType", "MD5");

            string paySign = TenpayUtil.getsign(sParams, tenpay.WeChartConfigItem.key);

            #endregion



            ViewBag.appId     = "wx2c2f2e7b5b62daa1";
            ViewBag.timeStamp = timeStamp;
            ViewBag.nonceStr  = nonceStr;
            ViewBag.prepay_id = prepay_id;
            ViewBag.paySign   = paySign;
            ViewBag.openid    = paySign + "我是paySign";
            return(View());
        }