微信支付

简单的说,就是得到微信用户的openid,用openid请求微信支付订单,得到订单后,使用JSAPI调用微信支付

1.通过微信授权方式得到微信用户openid 2.生成业务订单,用openid请求微信支付订单信息(get) 3.得到订单信息后,使用jsapi调用微信支付

注意: 1大小写要与配置一致 2调用微信支付的JSAPI要在TenPayV3下 3使get方式获取订单信息

 
引用<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
如果是有证书,使用https

function wxpay()
{
     WeixinJSBridge.invoke('getBrandWCPayRequest', {
                                        "appId": r.AppId, //公众号名称,由商户传入
                                        "timeStamp": r.TimeStamp, //时间戳
                                        "nonceStr": r.NonceStr, //随机串
                                        "package": r.Package,//扩展包
                                        "signType": "MD5", //微信签名方式:1.sha1
                                        "paySign": r.PaySign //微信签名
                                    }, function (res) {

                                        WeixinJSBridge.log(res.err_msg);
                                        alert(res.err_code + res.err_desc + res.err_msg);

                                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                                            alert("微信支付成功!");
                                        } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                                            alert("用户取消支付!");
                                        } else {
                                            alert("支付失败,原因:" + res.err_msg);
                                        }
                                        // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
                                        //因此微信团队建议,当收到ok返回时,向商户后台询问是否收到交易成功的通知,若收到通知,前端展示交易成功的界面;若此时未收到通知,商户后台主动调用查询订单接口,查询订单的当前状态,并反馈给前端展示相应的界面。
                                    });

}

    function callpay()
    {
        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', wxPay, false);
            }
            else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', wxPay);
                document.attachEvent('onWeixinJSBridgeReady', wxPay);
            }
        }
        else {
            wxPay();
        }
    }
微信支付JSAPI
TenPayUtil.GetNoncestr();//随机数
TenPayUtil.GetTimestamp();//时间戳

TenPayV3Info.AppId;//web.config中配置的appid
TenPayV3Info.AppSecret;//web.config中配置的secret
TenPayV3Info.Key//web.config中配置的key
TenPayV3Info.MchId //web.config中配置的商户Id
TenPayV3Info.TenPayV3Notify; //web.config中配置的回调地址

private static TenPayV3Info _tenPayV3Info;
        public static TenPayV3Info TenPayV3Info
        {
            get
            {
                if (_tenPayV3Info == null)
                {
                    _tenPayV3Info =
                        TenPayV3InfoCollection.Data[System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"]];
                }
                return _tenPayV3Info;
            }
        }

控制器里
 //会员充值        
        public ActionResult Recharge()
        {
            ViewBag.UserId = LoginUserInfo.UserId;
            ViewBag.OpenId = LoginUserInfo.WxOpenId;
            ViewBag.Points = LoginUserInfo.Points;
            return View();
        }
后端代码1
        public ActionResult JsApi(string code, string state)
        {
            #region 验证传参
            if (string.IsNullOrEmpty(code))
            {
                return Content("您拒绝了授权!");
            }

            if (!state.Contains("|"))
            {
                //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下
                //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证
                return Content("验证失败!请从正规途径进入!1001");
            }
            #endregion

            #region 用code获取accesstoken
            //通过,用code换取access_token
            var openIdResult = OAuthApi.GetAccessToken(TenPayV3Info.AppId, TenPayV3Info.AppSecret, code);
            if (openIdResult.errcode != ReturnCode.请求成功)
            {
                return Content("错误:" + openIdResult.errmsg);
            }
            #endregion

            #region 获取订单信息
            string timeStamp = "";
            string nonceStr = "";
            string paySign = "";

            string sp_billno = Request["order_no"];
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");



            //获取订单信息
            sp_billno = Request["order_no"].ToString();
            var order = rechargeService.Get(sp_billno);
            if (order == null) return Content("订单信息错误");
            #endregion


            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);
            //初始化
            packageReqHandler.Init();

            timeStamp = TenPayV3Util.GetTimestamp();
            nonceStr = TenPayV3Util.GetNoncestr();

            #region 设置package订单参数
            packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);          //公众账号ID
            packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);          //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                    //随机字符串
            packageReqHandler.SetParameter("body", "聚惠会员服务");    //商品信息
            packageReqHandler.SetParameter("out_trade_no", sp_billno);        //商家订单号
            packageReqHandler.SetParameter("total_fee", (order.Amount * 100).ToString());                    //商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);   //用户的公网ip,不是商户服务器IP
            packageReqHandler.SetParameter("notify_url", TenPayV3Info.TenPayV3Notify);            //接收财付通通知的URL
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                        //交易类型
            packageReqHandler.SetParameter("openid", openIdResult.openid);                        //用户的openId

            string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            packageReqHandler.SetParameter("sign", sign);                        //签名

            string data = packageReqHandler.ParseXML();

            var result = TenPayV3.Unifiedorder(data);
            var res = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;
            #endregion

            #region 设置支付参数
            RequestHandler paySignReqHandler = new RequestHandler(null);
            paySignReqHandler.SetParameter("appId", TenPayV3Info.AppId);
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            #endregion

            //得到支付参数
            ViewData["appId"] = TenPayV3Info.AppId;
            ViewData["timeStamp"] = timeStamp;
            ViewData["nonceStr"] = nonceStr;
            ViewData["package"] = string.Format("prepay_id={0}", prepayId);
            ViewData["paySign"] = paySign;

            return View();
        }
后端处理JSAPI
        public ActionResult PayNotifyUrl()
        {
            ResponseHandler resHandler = new ResponseHandler(null);

            string return_code = resHandler.GetParameter("return_code");
            string return_msg = resHandler.GetParameter("return_msg");

            #region 附加的参数
            string result_code = resHandler.GetParameter("result_code");//业务结果:SUCCESS/FAIL
            string appid = resHandler.GetParameter("appid");
            string mch_id = resHandler.GetParameter("mch_id");
            string device_info = resHandler.GetParameter("device_info");
            string nonce_str = resHandler.GetParameter("nonce_str");
            string sign = resHandler.GetParameter("sign");
            string err_code = resHandler.GetParameter("err_code");
            string err_code_des = resHandler.GetParameter("err_code_des");
            string openid = resHandler.GetParameter("openid");
            string is_subscribe = resHandler.GetParameter("is_subscribe");
            string trade_type = resHandler.GetParameter("trade_type");
            string bank_type = resHandler.GetParameter("bank_type");
            string total_fee = resHandler.GetParameter("total_fee");//总金额
            string coupon_fee = resHandler.GetParameter("coupon_fee");
            string fee_type = resHandler.GetParameter("fee_type");
            string transaction_id = resHandler.GetParameter("transaction_id");//微信支付订单号
            string out_trade_no = resHandler.GetParameter("out_trade_no");//商户订单号
            string attach = resHandler.GetParameter("attach"); //参数attach  1充值订单 2微信购物订单
            string time_end = resHandler.GetParameter("time_end");//支付完成时间
            #endregion

            string res = null;

            resHandler.SetKey(TenPayV3Info.Key);
            //验证请求是否从微信发过来(安全)
            if (resHandler.IsTenpaySign())
            {
                res = "success";

                //正确的订单处理
                if (result_code == "SUCCESS")
                {
                    decimal money = Convert.ToInt32(total_fee) / 100;
                    if (attach == "1")
                    {
                        //充值业务
                        if (rechargeService.Pay(out_trade_no, transaction_id))
                        {
                            string msg = string.Format("您己成功充值{0}积分", money);
                            if (true)
                            {
                                msg += ",并赠送" + decimal.Round(money * 0.05m, 2) + "金豆";
                            }
                            CustomApi.SendText(appid, openid, msg);                           
                        }
                    }
                    if (attach == "2")
                    {
                        //2微信购物订单,会员消费
                        if (consumeService.WeixinPay(out_trade_no, transaction_id))
                        {
                          
                        }
                    }
                }
                else
                { 
                   log.Error("微信支付错误"+return_msg);
                }

            }
            else
            {
                res = "wrong";
                log.Warn("异步回调微信支付验签失败");
                //错误的订单处理
            }

            var fileStream = System.IO.File.OpenWrite(Server.MapPath("~/1.txt"));
            fileStream.Write(Encoding.Default.GetBytes(res), 0, Encoding.Default.GetByteCount(res));
            fileStream.Close();

            string xml = string.Format(@"<xml>
   <return_code><![CDATA[{0}]]></return_code>
   <return_msg><![CDATA[{1}]]></return_msg>
</xml>", return_code, return_msg);

            return Content(xml, "text/xml");

        }
异步回调处理
 /// <summary>
        /// 订单查询
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderQuery(string merorderno,string wxorderno)
        {
            string nonceStr = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);          //公众账号ID
            packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);          //商户号
            packageReqHandler.SetParameter("transaction_id", wxorderno);       //填入微信订单号 
            packageReqHandler.SetParameter("out_trade_no", merorderno);         //填入商家订单号
            packageReqHandler.SetParameter("nonce_str", nonceStr);             //随机字符串
            string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            packageReqHandler.SetParameter("sign", sign);                        //签名

            string data = packageReqHandler.ParseXML();

            var result = TenPayV3.OrderQuery(data);
            var res = XDocument.Parse(result);
            string openid = res.Element("xml").Element("sign").Value;

            return Content(openid);
        }
订单查询
/// <summary>
        /// 退款申请接口
        /// </summary>
        /// <returns></returns>
        public ActionResult Refund()
        {
            string nonceStr = TenPayV3Util.GetNoncestr();
            RequestHandler packageReqHandler = new RequestHandler(null);

            //设置package订单参数
            packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);          //公众账号ID
            packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);          //商户号
            packageReqHandler.SetParameter("out_trade_no", "");                 //填入商家订单号
            packageReqHandler.SetParameter("out_refund_no", "");                //填入退款订单号
            packageReqHandler.SetParameter("total_fee", "");               //填入总金额
            packageReqHandler.SetParameter("refund_fee", "");               //填入退款金额
            packageReqHandler.SetParameter("op_user_id", TenPayV3Info.MchId);   //操作员Id,默认就是商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);              //随机字符串
            string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            packageReqHandler.SetParameter("sign", sign);                        //签名
            //退款需要post的数据
            string data = packageReqHandler.ParseXML();

            //退款接口地址
            string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            //本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
            string cert = @"F:\apiclient_cert.p12";
            //私钥(在安装证书时设置)
            string password = "";
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //调用证书
            X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            #region 发起post请求
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.ClientCertificates.Add(cer);
            webrequest.Method = "post";

            byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream;
            stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();
            #endregion

            var res = XDocument.Parse(responseContent);
            string openid = res.Element("xml").Element("out_refund_no").Value;

            return Content(openid);
        }
申请退款

 

posted @ 2016-06-23 15:29  奎宇工作室  阅读(444)  评论(0编辑  收藏  举报