.net H5微信,支付宝充值

using clientpay.Data.AlipayConfig;
using clientpay.Data.BLL;
using clientpay.Data.Entity;
using Aop.Api;
using Aop.Api.Domain;
using Aop.Api.Request;
using Aop.Api.Response;
using clientpay.TemplatePage;
using Lexun.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using clientpay.Data.Entity.WxPay;
using clientpay.Data.WxH5PayConfig;

namespace clientpay
{
    /// <summary>
    /// 添加订单列表数据操作
    /// </summary>
    public partial class clientpay : PBTemplate
    {
        private BuyOrderInfo buyOrderInfo = null;   //订单信息
        private BuyOrderResult orderResult = null;//生成订单结果

        protected int result = 0;
        protected string outmsg = string.Empty;

        protected override void InitParams()
        {
            try
            {
                PBPayOrderFootParams reqData = PBPayOrderFootParams.ParseFrom(PBBuffer);
                if (null != reqData)
                {
                    buyOrderInfo = new BuyOrderInfo();
                    buyOrderInfo.userid = reqData.Userid;//用户编号                    
                    buyOrderInfo.platform = reqData.Platform;//平台类型
                    buyOrderInfo.channelid = reqData.Channelid;//渠道
                    buyOrderInfo.payflag = reqData.Payflag; // 1微信 2支付宝
                    buyOrderInfo.ip = CUser.GetUserIp();
                    buyOrderInfo.amount = reqData.Amount;//充值金额(分)
                    buyOrderInfo.imei = reqData.Imei;
                    buyOrderInfo.phonemode = reqData.Phonemodel;
                    buyOrderInfo.phonesn = reqData.Phonesn;
                    buyOrderInfo.rechargetype = reqData.Rechargetype;//充值类型(1:足球竞猜金豆充值,2:资讯彩豆充值)

                    //buyOrderInfo.userid = 1;//用户编号                    
                    //buyOrderInfo.platform = 2;//平台类型
                    //buyOrderInfo.channelid = 1;//渠道
                    //buyOrderInfo.payflag = 1; // 1微信 2支付宝
                    //buyOrderInfo.ip = CUser.GetUserIp();
                    //buyOrderInfo.amount = 100;//充值金额
                    //buyOrderInfo.imei = "23482342334224";
                    //buyOrderInfo.phonemode = "3434534534";
                    //buyOrderInfo.phonesn = "23423432";
                    //buyOrderInfo.rechargetype = 1;//充值类型(1:足球竞猜金豆充值,2:资讯彩豆充值)
                }
            }
            catch { }
        }


        protected override void InitData()
        {
            if (buyOrderInfo.userid <= 0)
            {
                outmsg = "抱歉,生成订单失败,请重新登录后再试。";
                return;
            }

            if (buyOrderInfo.amount <= 0)
            {
                outmsg = "抱歉,生成订单失败。";
                return;
            }
            //安卓 微信 暂时用官方h5支付
            if (buyOrderInfo.payflag == 1)
            {
                buyOrderInfo.paytype = PayType.PT_WXPAY;    //微信支付方式
            }
            else
            {
                buyOrderInfo.paytype = PayType.PT_ALIPAY;      //支付宝支付方式
            }

            orderResult = PayOrderBLL.GenerateOrder(buyOrderInfo);
        }


        protected override void OutPut()
        {
            string outmsg = string.Empty;
            string payurl = string.Empty;
            string urlprefix = string.Empty;
            int usebrowser = 0;

            PBPayOrderFootResult.Builder resData = PBPayOrderFootResult.CreateBuilder();

            if (null == orderResult || orderResult.retval == -100)
            {
                outmsg = (null == orderResult) ? "抱歉,生成订单失败." : orderResult.outmsg;
            }
            else
            {
                //产生订单成功
                if (null != orderResult && orderResult.retval > 0 && !string.IsNullOrEmpty(orderResult.orderid))
                {
                    if (buyOrderInfo.paytype == PayType.PT_WXPAY)
                    {
                        urlprefix = "http://ball.szbocx.com";
                        if (buyOrderInfo.platform == 1) //安卓
                            payurl = GetH5PayUrl(orderResult.orderid, orderResult.amount);
                        else
                            payurl = string.Format("http://ball.szbocx.com/callpay.aspx?payflag=1&orderid={0}", orderResult.orderid);
                    }
                    else if (buyOrderInfo.paytype == PayType.PT_ALIPAY)
                    {
                        payurl = string.Format("http://ball.szbocx.com/callpay.aspx?payflag=2&orderid={0}", orderResult.orderid);
                    }

                    if (!string.IsNullOrEmpty(payurl))
                    {
                        result = 1;
                        outmsg = "生成订单成功";
                        resData.SetUrlprefix(urlprefix);
                        resData.SetPayurl(payurl);
                        resData.SetUsebrowser(usebrowser);
                    }
                }
                else
                {
                    if (null != orderResult && !string.IsNullOrEmpty(orderResult.outmsg))
                        outmsg = orderResult.outmsg;
                    else
                        outmsg = "抱歉,生成订单失败!";
                }
            }

            resData.SetResult(result);
            resData.SetOutmsg(outmsg);
            Response.ContentType = "text/plain";
            Response.BinaryWrite(resData.Build().ToByteArray());
            Response.End();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public string GetH5PayUrl(string orderNo, int amount)
        {
            try
            {
                WxPayParam wxPayParam = new WxPayParam()
                {
                    APPID = WxH5PayConfig.APPID,
                    KEY = WxH5PayConfig.KEY,
                    MCHID = WxH5PayConfig.MCHID,
                    NOTIFY_URL = WxH5PayConfig.NOTIFY_URL,
                    IP = WxH5PayConfig.IP,
                    REPORT_LEVENL = WxH5PayConfig.REPORT_LEVENL
                };

                Log.Info(this.GetType().ToString(), "Native pay mode 2 url is producing...");
                //场景信息
                string scene_info = "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://www.szbocx.com\",\"wap_name\": \"全红体育充值\"}}";

                WxPayData data = new WxPayData();
                data.SetValue("body", "全红体育");//商品描述                
                data.SetValue("out_trade_no", orderNo);//商户订单号
                data.SetValue("total_fee", amount);//订单总金额,单位为分
                data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
                data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易结束时间
                data.SetValue("trade_type", "MWEB");//交易类型
                data.SetValue("scene_info", scene_info);//场景信息
                data.SetValue("notify_url", "http://ball.szbocx.com/callback/callback_wxh5pay.aspx");

                WxPayData result = WxPayApi.UnifiedOrderH5(data, wxPayParam, WxPayUtil.IPAddress);//调用统一下单接口
                if (result != null)
                {
                    if (result.GetValue("mweb_url") != null)
                    {
                        return result.GetValue("mweb_url").ToString();
                    }
                    return string.Empty;
                }
                else
                {
                    return string.Empty;
                }
            }
            catch (Exception ex)
            {
                CLog.WriteLog(" go_wx_form_h5 Message=" + ex.Message + "StackTrace=" + ex.StackTrace);
                return string.Empty;
            }
        }

    }
}
H5 支付请求
using clientpay.Data.BLL;
using clientpay.Data.Entity;
using Aop.Api;
using Aop.Api.Domain;
using Aop.Api.Request;
using Aop.Api.Response;
using Lexun.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using clientpay.Data.AlipayConfig;
using clientpay.Data.Entity.WxPay;
using clientpay.Data.WxH5PayConfig;

namespace clientpay
{
    /// <summary>
    /// 订单验证返回
    /// </summary>
    public partial class callpay : System.Web.UI.Page
    {
        private string outmsg = string.Empty;
        private string orderid = string.Empty;
        private int payflag = 1;            //1 微信 2支付宝

        private string errorMsg = "";
        private int errorType = 0;

        private string formHtml = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            InitParams();

            InitData();

            OutPut();
        }

        protected void InitParams()
        {
            orderid = CRequest.GetString("orderid");
            payflag = CRequest.GetInt("payflag");

            //orderid = "20191118100631930992";
            //payflag = 1;

        }

        protected void InitData()
        {
            if (string.IsNullOrEmpty(orderid))
            {
                errorMsg = "抱歉,订单号不正确。";
                errorType = 101;
                return;

            }

            string payType = string.Empty;
            if (payflag == 1)
                payType = PayType.PT_WXPAY;
            else if (payflag == 2)
                payType = PayType.PT_ALIPAY;
            else
            {
                outmsg = "抱歉,订单不存在。";
                errorType = 101;
                return;
            }

            PayOrderInfo orderInfo = PayOrderBLL.GetPayOrderInfo(orderid, payType);
            if (orderInfo == null)
            {
                errorMsg = "抱歉,订单不存在。";
                errorType = 102;
                return;
            }

            if (payflag == 1)//微信
                formHtml = GetH5PayUrl(orderInfo.orderid, orderInfo.amount / 100, orderInfo.userid);//将分转元,以便充值界面展示
            else if (payflag == 2)//支付宝
                formHtml = GetFormHtml(orderInfo.orderid, orderInfo.amount / 100);//将分转元,以便充值界面展示
        }

        protected void OutPut()
        {
            //产生订单成功
            if (errorType == 0 && !string.IsNullOrEmpty(formHtml))
            {
                Response.Write(formHtml);
                Response.End();
            }
            else
            {
                if (string.IsNullOrEmpty(errorMsg))
                    errorMsg = "抱歉,生成订单失败!";
            }
        }

        /// <summary>
        /// 支付宝支付返回请求
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="price"></param>
        /// <returns></returns>
        public string GetFormHtml(string orderid, int price)
        {
            string sHtmlText = string.Empty;

            DefaultAopClient client = new DefaultAopClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.private_key, "json", "1.0", AlipayConfig.sign_type, AlipayConfig.alipay_public_key, AlipayConfig.charset, false);
            // 外部订单号,商户网站订单系统中唯一的订单号
            string out_trade_no = orderid;

            // 订单名称
            string subject = "全红体育";

            //订单金额(元)
            string total_amount = price.ToString();

            // 商品描述
            string body = "全红体育";

            // 支付中途退出返回商户网站地址
            string quit_url = "http://www.szbocx.com/";

            // 组装业务参数model
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.Body = body;
            model.Subject = subject;
            model.TotalAmount = total_amount;
            model.OutTradeNo = out_trade_no;
            model.ProductCode = "QUICK_WAP_WAY";
            model.QuitUrl = quit_url;

            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            // 设置支付完成同步回调地址
            request.SetReturnUrl("http://ball.szbocx.com/callback/callback_alipay.aspx");
            // 设置支付完成异步通知接收地址
            request.SetNotifyUrl("http://ball.szbocx.com/callback/callback_alipay.aspx");
            // 将业务model载入到request
            request.SetBizModel(model);

            AlipayTradeWapPayResponse response = null;
            try
            {
                response = client.pageExecute(request, null, "post");
                sHtmlText = response.Body.ToString();
            }
            catch (Exception ex)
            {
                CLog.WriteLog("clientpay->OutPut StackTrace={0},Message={1}", ex.StackTrace, ex.Message);
            }
            return sHtmlText;
        }


        /// <summary>
        /// 微信支付返回请求
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="amount"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public string GetH5PayUrl(string orderNo, int amount, int userid)
        {
            try
            {
                WxPayParam wxPayParam = new WxPayParam()
                {
                    APPID = WxH5PayConfig.APPID,
                    KEY = WxH5PayConfig.KEY,
                    MCHID = WxH5PayConfig.MCHID,
                    NOTIFY_URL = WxH5PayConfig.NOTIFY_URL,
                    IP = WxH5PayConfig.IP,
                    REPORT_LEVENL = WxH5PayConfig.REPORT_LEVENL
                };

                Log.Info(this.GetType().ToString(), "Native pay mode 2 url is producing...");
                //场景信息
                string scene_info = "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://www.szbocx.com\",\"wap_name\": \"全红体育充值\"}}";

                WxPayData data = new WxPayData();
                data.SetValue("body", "全红体育");//商品描述                
                data.SetValue("out_trade_no", orderNo);//商户订单号
                data.SetValue("total_fee", amount * 100);//订单总金额,单位为分
                data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
                data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易结束时间
                data.SetValue("trade_type", "MWEB");//交易类型
                data.SetValue("scene_info", scene_info);//场景信息
                data.SetValue("notify_url", "http://ball.szbocx.com/callback/callback_wxh5pay.aspx");

                WxPayData result = WxPayApi.UnifiedOrderH5(data, wxPayParam, WxPayUtil.IPAddress);//调用统一下单接口
                if (result != null)
                {
                    if (result.GetValue("mweb_url") != null)
                    {
                        string mweb_url = result.GetValue("mweb_url").ToString();
                        mweb_url = mweb_url + "&redirect_url=" + HttpUtility.UrlEncode("ball.szbocx.com://");
                        return string.Format("<script>window.location.href ='{0}';</script>", mweb_url);
                    }
                    return string.Empty;
                }
                else
                {
                    errorMsg = result.GetValue("return_msg").ToString();
                    return string.Empty;
                }
            }
            catch (Exception ex)
            {
                CLog.WriteLog("go_wx_form_h5 Message=" + ex.Message + "StackTrace=" + ex.StackTrace);
                return string.Empty;
            }
        }
    }
}
支付回调
using clientpay.Data.Entity.WxPay;
using clientpay.Data.WxH5PayConfig;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace clientpay.callback
{
    public partial class callback_wxh5pay : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            WxPayParam wxPayParam = new WxPayParam()
            {
                APPID = WxH5PayConfig.APPID,
                KEY = WxH5PayConfig.KEY,
                MCHID = WxH5PayConfig.MCHID,
                NOTIFY_URL = WxH5PayConfig.NOTIFY_URL,
                IP = WxH5PayConfig.IP,
                REPORT_LEVENL = WxH5PayConfig.REPORT_LEVENL
            };

            ResultNotify resultNotify = new ResultNotify(this);
            resultNotify.ProcessNotify(wxPayParam);
        }
    }
}
微信回调接口界面
using clientpay.Data.BLL;
using clientpay.Data.Entity;
using clientpay.Data.Entity.AliPay;
using Aop.Api.Util;
using Lexun.Common;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using clientpay.Data.AlipayConfig;

namespace clientpay.callback
{
    /// <summary>
    /// 支付宝充值回调界面
    /// </summary>
    public partial class callback_alipay : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            /* 实际验证过程建议商户添加以下校验。
      1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号,
      2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额),
      3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email)
      4、验证app_id是否为该商户本身。
      */
            Dictionary<string, string> sArray = GetRequestPost();
            if (sArray.Count != 0)
            {
                bool flag = AlipaySignature.RSACheckV1(sArray, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type, false);
                if (flag)
                {
                    PayOrderInfo orderInfo = PayOrderBLL.GetPayOrderInfo(Request["out_trade_no"], "");
                    if (orderInfo != null)
                    {
                        if (orderInfo.amount != CTools.ToInt((CTools.ToDouble(Request["total_amount"]) * 100).ToString()))//订单金额与实际创建订单金额不相等
                        {
                            CLog.WriteLog("支付宝回调操作,添加订单金额{0},实际订单金额{1}", orderInfo.amount, CTools.ToInt((CTools.ToDouble(Request["total_amount"]) * 100).ToString()));
                            Response.Write("fail");
                            return;
                        }
                    }
                    if (Request["app_id"] == AlipayConfig.app_id)
                    {
                        try
                        {
                            //商户订单号
                            string out_trade_no = Request["out_trade_no"];//商户订单号
                            //支付宝交易号
                            string trade_no = Request["trade_no"];//支付宝交易号
                            //交易状态
                            string trade_status = Request["trade_status"];//交易状态
                            string buyer_email = Request["buyer_email"];
                            string buyer_id = Request["buyer_id"];//买家支付宝用户号
                            string discount = Request["discount"];
                            string gmt_close = Request["gmt_close"];//该笔交易结束时间。格式为yyyy-MM-dd HH:mm:ss
                            string gmt_create = Request["gmt_create"];//该笔交易创建的时间。格式为yyyy-MM-dd HH:mm:ss
                            string gmt_payment = Request["gmt_payment"];//该笔交易的买家付款时间。格式为yyyy-MM-dd HH:mm:ss
                            string is_total_fee_adjust = Request["is_total_fee_adjust"];
                            string notify_id = Request["notify_id"];//通知校验ID
                            string notify_time = Request["notify_time"];//通知的发送时间。格式为yyyy-MM-dd HH:mm:ss
                            string notify_type = Request["notify_type"];//通知类型
                            string payment_type = PayType.PT_ALIPAY;
                            string price = Request["total_amount"];
                            string quantity = "1";
                            string seller_email = Request["seller_email"];//卖家支付宝账号
                            string seller_id = Request["seller_id"];//卖家支付宝用户号
                            string total_fee = Request["total_amount"];//Request["total_fee"];//订单金额(分)

                            if (trade_status == "TRADE_SUCCESS" || trade_status == "TRADE_FINISHED")
                            {
                                string outmsg = "";
                                int userid = 0;
                                AlipayBackInfo backinfo = new AlipayBackInfo()
                                {
                                    buyer_email = buyer_email,
                                    buyer_id = buyer_id,
                                    discount = CTools.ToDecimal(discount),
                                    gmt_close = CTools.ToDateTime(gmt_close),
                                    gmt_create = CTools.ToDateTime(gmt_create),
                                    gmt_payment = CTools.ToDateTime(gmt_payment),
                                    is_total_fee_adjust = is_total_fee_adjust,
                                    notify_id = notify_id,
                                    notify_time = CTools.ToDateTime(notify_time),
                                    notify_type = notify_type,
                                    orderid = out_trade_no,
                                    out_trade_no = out_trade_no,
                                    payment_type = payment_type,
                                    price = CTools.ToInt((CTools.ToDouble(total_fee) * 100).ToString()),//单位分
                                    quantity = CTools.ToInt(quantity),
                                    seller_email = seller_email,
                                    seller_id = seller_id,
                                    total_fee = CTools.ToInt((CTools.ToDouble(total_fee) * 100).ToString()),//单位分
                                    trade_no = trade_no,
                                    trade_status = trade_status
                                };

                                AlipayBLL.AddAliPayCallBack(backinfo, out userid, out outmsg);

                            }
                        }
                        catch (Exception ex)
                        {
                            CLog.WriteLog("callback_alipay-> StackTrace={0},Message={1}", ex.StackTrace, ex.Message);
                        }
                        Response.Write("success");
                    }
                    else
                    {
                        Response.Write("fail");
                    }
                }
                else
                {
                    Response.Write("fail");
                }
            }
        }
        public Dictionary<string, string> GetRequestPost()
        {
            int i = 0;
            Dictionary<string, string> sArray = new Dictionary<string, string>();
            NameValueCollection coll;
            //coll = Request.Form;
            coll = Request.Form;
            String[] requestItem = coll.AllKeys;
            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], Request.Form[requestItem[i]]);
            }
            return sArray;

        }
    }
}
支付宝回调接口界面
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace clientpay.Data.AlipayConfig
{
    /// <summary>
    /// config 的摘要说明
    /// </summary>
    public class AlipayConfig
    {
        public AlipayConfig()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        // 应用ID,您的APPID
        public static string app_id = "";

        // 支付宝网关
        public static string gatewayUrl = "https://openapi.alipay.com/gateway.do";

        // 商户私钥,您的原始格式RSA私钥
        public static string private_key = "";

        // 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
        public static string alipay_public_key = "";

        // 签名方式
        public static string sign_type = "RSA2";

        // 编码格式
        public static string charset = "UTF-8";
    }
}
支付宝配置
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace clientpay.Data.WxH5PayConfig
{
    public class WxH5PayConfig
    {
        //=======【基本信息设置】=====================================
        /* 微信公众号信息配置
        * APPID:绑定支付的APPID(必须配置)
        * MCHID:商户号(必须配置)
        * KEY:商户支付密钥,参考开户邮件设置(必须配置)
        * APPSECRET:公众帐号secert(仅JSAPI支付的时候需要配置)
        */
        public const string APPID = "";
        public const string MCHID = "";
        public const string KEY = "";

        public const string APPSECRET = "";

        //=======【证书路径设置】===================================== 
        /* 证书路径,注意应该填写绝对路径(仅退款、撤销订单时需要)
        */
        public const string SSLCERT_PATH = "cert/apiclient_cert.p12";
        public const string SSLCERT_PASSWORD = "";// "1233410002";



        //=======【支付结果通知url】===================================== 
        /* 支付结果通知回调url,用于商户接收支付结果
        */
        public const string NOTIFY_URL = "http://ball.szbocx.com/callback/callback_wxh5pay.aspx";

        //=======【商户系统后台机器IP】===================================== 
        /* 此参数可手动配置也可在程序中自动获取
        */
        public const string IP = "120.79.136.88";


        //=======【代理服务器设置】===================================
        /* 默认IP和端口号分别为0.0.0.0和0,此时不开启代理(如有需要才设置)
        */
        public const string PROXY_URL = "http://10.152.18.220:8080";

        //=======【上报信息配置】===================================
        /* 测速上报等级,0.关闭上报; 1.仅错误时上报; 2.全量上报
        */
        public const int REPORT_LEVENL = 1;

        //=======【日志级别】===================================
        /* 日志等级,0.不输出日志;1.只输出错误信息; 2.输出错误和正常信息; 3.输出错误信息、正常信息和调试信息
        */
        public const int LOG_LEVENL = 0;
    }
}
微信配置

猜你喜欢

转载自www.cnblogs.com/www-mcl-1234/p/11884409.html