/// <summary>
        /// 新增prepayinfo
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public bool AddPayInfo(PrePayInfo info)
        {
            bool result = false;

            context.PrePayInfo.Add(info);
            if (context.SaveChanges() > 0)
            {
                result = true;
            }
            return(result);
        }
        /// <summary>
        /// 获取扫描支付的二维码地址
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetPayUrl(string id)
        {
            var order = new PayService().GetOrderByOrderNo(id);

            PrePayInfo info = new PrePayInfo();

            info.OrderNo    = order.No;
            info.PrePayNo   = FCake.Core.Common.DataHelper.GetSystemID();
            info.NeedPay    = int.Parse(order.NeedPay.ToString().Split('.')[0]) * 100;
            info.LogingTime = DateTime.Now;
            new PrePayInfoService().AddPayInfo(info);



            WxPayData data = new WxPayData();

            data.SetValue("body", "Fancake-蛋糕");                                                         //商品描述
            data.SetValue("attach", "Fancake");                                                          //附加数据
            data.SetValue("out_trade_no", info.PrePayNo);                                                //订单号
            data.SetValue("total_fee", Convert.ToInt32((order.NeedPay * 100).ToString().Split('.')[0])); //总金额(order.NeedPay * 100).ToString().Split('.')[0]
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));                        //交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));        //交易结束时间
            data.SetValue("goods_tag", "Fancake");                                                       //商品标记
            data.SetValue("trade_type", "NATIVE");                                                       //交易类型
            data.SetValue("product_id", order.Id);                                                       //商品ID

            WxPayData result = WxPayApi.UnifiedOrder(data);                                              //调用统一下单接口
            string    temp   = result.GetValue("code_url").ToString();                                   //获得统一下单接口返回的二维码链接
            //temp = HttpUtility.UrlEncode(temp);

            //生成二维码
            //初始化二维码生成工具
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();

            qrCodeEncoder.QRCodeEncodeMode   = QRCodeEncoder.ENCODE_MODE.BYTE;
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            qrCodeEncoder.QRCodeVersion      = 0;
            qrCodeEncoder.QRCodeScale        = 4;
            //将字符串生成二维码图片
            Bitmap image = qrCodeEncoder.Encode(temp, Encoding.Default);
            //end
            MemoryStream ms = new MemoryStream();

            image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            string strUrl = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());

            image.Dispose();


            ViewBag.src = strUrl;
            //return File(ms.ToArray(), "png");
            return(View());
        }
Esempio n. 3
0
        /// <summary>
        /// 手机微信支付,统一支付接口
        /// </summary>
        /// <returns></returns>
        public ActionResult WXPay(string id)
        {
            try
            {
                OpResult result = new OpResult();
                result.Successed = false;
                var order = psv.GetOrderByOrderNo(id);//获取订单信息
                ViewBag.orderNo = id;
                //微信预支付数据为单订单发起多次支付
                PrePayInfo info = new PrePayInfo();
                info.OrderNo    = order.No;
                info.PrePayNo   = FCake.Core.Common.DataHelper.GetSystemID();
                info.NeedPay    = int.Parse(order.NeedPay.ToString().Split('.')[0]) * 100;
                info.LogingTime = DateTime.Now;
                bool rt = new PrePayInfoService().AddPayInfo(info);
                if (rt)
                {
                    #region 预支付数据成功创建日志记录
                    PayLog log_prePayData = new PayLog();
                    log_prePayData.ID      = FCake.Core.Common.DataHelper.GetSystemID();
                    log_prePayData.LogTime = DateTime.Now;
                    log_prePayData.Message = "创建微信支付id:" + info.PrePayNo + "成功";
                    log.Add(log_prePayData);
                    #endregion
                }

                if (order.FeeType != FeeType.WXPay && order.Status != 0)
                {
                    result.Message = "订单状态异常!";
                    return(Json(result));
                }
                #region 获取tocken
                var appid  = WxPayConfig.APPID;     //"wx8bf0e66bf9f6a009";
                var secret = WxPayConfig.APPSECRET; // "6b783c1339f64a7638158ccdfaf216f1";
                var code   = string.Empty;
                var openid = string.Empty;
                var client = new System.Net.WebClient();
                client.Encoding = System.Text.Encoding.UTF8;
                if (Session["code"] == null)
                {
                    var myurl = Request.Url.Scheme + "://" + Request.Url.Host + "/tenpay/ResponseParam";//获取code的地址
                    var url   = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect", appid, myurl);

                    return(Redirect(url));
                }
                else
                {
                    code = Session["code"].ToString();
                    var url  = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code);
                    var data = client.DownloadString(url);
                    #region 获取微信access_token结果日志记录
                    //记录返回的access_token
                    PayLog log_accessToken = new PayLog();
                    log_accessToken.ID      = FCake.Core.Common.DataHelper.GetSystemID();
                    log_accessToken.LogTime = DateTime.Now;
                    log_accessToken.Message = "accessToken:请求:" + url + "返回:" + data;
                    log.Add(log_accessToken);
                    //token end
                    #endregion
                    var    serializer = new JavaScriptSerializer();
                    var    obj        = serializer.Deserialize <Dictionary <string, string> >(data);
                    string accessToken;
                    if (!obj.TryGetValue("access_token", out accessToken))
                    {
                        return(View());
                    }

                    var opentid = obj["openid"];
                    url  = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", accessToken, opentid);
                    data = client.DownloadString(url);
                    #region 获取微信支付openid结果日志
                    //记录返回的openid
                    PayLog log_openid = new PayLog();
                    log_openid.ID      = FCake.Core.Common.DataHelper.GetSystemID();
                    log_openid.LogTime = DateTime.Now;
                    log_openid.Message = "openid:" + data;
                    log.Add(log_openid);
                    //token end
                    #endregion
                    var userInfo = serializer.Deserialize <Dictionary <string, object> >(data);

                    foreach (var key in userInfo.Keys)
                    {
                        if (key == "openid")
                        {
                            openid = userInfo[key].ToString();
                            break;
                        }
                    }
                }

                //openid get end

                #endregion

                ////若传递了相关参数,则调统一下单接口,获得后续相关接口的入口参数
                JsApiPay jsApiPay = new JsApiPay();
                jsApiPay.hostStr  = Request.Url.Host;
                jsApiPay.pathStr  = Request.Path;
                jsApiPay.queryStr = Request.Url.Query;
                jsApiPay.codeVal  = code;
                jsApiPay.orderNo  = info.PrePayNo;//订单号

                jsApiPay.openid    = openid;
                jsApiPay.total_fee = Convert.ToInt32((order.NeedPay * 100).ToString().Split('.')[0]); //订单金额,先写死为1   int.Parse((order.NeedPay * 100).ToString());

                //JSAPI支付预处理

                WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult();

                #region 请求预支付id发送数据日志
                PayLog log_sendPrePayData = new PayLog();
                log_sendPrePayData.ID      = FCake.Core.Common.DataHelper.GetSystemID();
                log_sendPrePayData.LogTime = DateTime.Now;
                log_sendPrePayData.Message = "请求预字符id发送数据:" + unifiedOrderResult.ToXml().ToString();
                log.Add(log_sendPrePayData);
                #endregion


                var wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数

                //记录的Exception
                #region 调jsapi支付参数日志
                PayLog log_sendJsApiData = new PayLog();
                log_sendJsApiData.ID      = FCake.Core.Common.DataHelper.GetSystemID();
                log_sendJsApiData.LogTime = DateTime.Now;
                log_sendJsApiData.Message = "pl20:" + wxJsApiParam;
                log.Add(log_sendJsApiData);
                #endregion
                //Exception end
                //在页面上显示订单信息
                ViewBag.PayInfo = wxJsApiParam;

                if (Session["code"] != null)
                {
                    Session.Remove("code");
                }
                if (Session["orderid"] != null)
                {
                    Session.Remove("orderid");
                }


                return(View());
            }
            catch (Exception e)
            {
                #region 异常日志
                //记录的Exception
                PayLog log_Exception = new PayLog();
                log_Exception.ID      = FCake.Core.Common.DataHelper.GetSystemID();
                log_Exception.LogTime = DateTime.Now;
                log_Exception.Message = "error:" + e.Message;
                log.Add(log_Exception);
                //Exception end
                #endregion
            }

            return(View());
        }