.net H5微信,支付宝充值
阅读原文时间:2023年07月15日阅读:1

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
{
///

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

    protected int result = ;  
    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 <= )  
        {  
            outmsg = "抱歉,生成订单失败,请重新登录后再试。";  
            return;  
        }

        if (buyOrderInfo.amount <= )  
        {  
            outmsg = "抱歉,生成订单失败。";  
            return;  
        }  
        //安卓 微信 暂时用官方h5支付  
        if (buyOrderInfo.payflag == )  
        {  
            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 = ;

        PBPayOrderFootResult.Builder resData = PBPayOrderFootResult.CreateBuilder();

        if (null == orderResult || orderResult.retval == -)  
        {  
            outmsg = (null == orderResult) ? "抱歉,生成订单失败." : orderResult.outmsg;  
        }  
        else  
        {  
            //产生订单成功  
            if (null != orderResult && orderResult.retval >  && !string.IsNullOrEmpty(orderResult.orderid))  
            {  
                if (buyOrderInfo.paytype == PayType.PT\_WXPAY)  
                {  
                    urlprefix = "http://ball.szbocx.com";  
                    if (buyOrderInfo.platform == ) //安卓  
                        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 = ;  
                    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().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
{
///

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

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

    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 = ;  
            return;

        }

        string payType = string.Empty;  
        if (payflag == )  
            payType = PayType.PT\_WXPAY;  
        else if (payflag == )  
            payType = PayType.PT\_ALIPAY;  
        else  
        {  
            outmsg = "抱歉,订单不存在。";  
            errorType = ;  
            return;  
        }

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

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

    protected void OutPut()  
    {  
        //产生订单成功  
        if (errorType ==  && !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 \* );//订单总金额,单位为分  
            data.SetValue("time\_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间  
            data.SetValue("time\_expire", DateTime.Now.AddMinutes().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
{
///

/// 支付宝充值回调界面 ///
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 sArray = GetRequestPost();
if (sArray.Count != )
{
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"]) * ).ToString()))//订单金额与实际创建订单金额不相等
{
CLog.WriteLog("支付宝回调操作,添加订单金额{0},实际订单金额{1}", orderInfo.amount, CTools.ToInt((CTools.ToDouble(Request["total_amount"]) * ).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 = "";
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 = ;  
                            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) \* ).ToString()),//单位分  
                                quantity = CTools.ToInt(quantity),  
                                seller\_email = seller\_email,  
                                seller\_id = seller\_id,  
                                total\_fee = CTools.ToInt((CTools.ToDouble(total\_fee) \* ).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 = ;  
        Dictionary<string, string> sArray = new Dictionary<string, string>();  
        NameValueCollection coll;  
        //coll = Request.Form;  
        coll = Request.Form;  
        String\[\] requestItem = coll.AllKeys;  
        for (i = ; 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
{
///

/// config 的摘要说明 ///
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 = ;

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

}

微信配置