欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信小程序之微信支付C#后台(统一下单)

程序员文章站 2023-03-25 19:23:14
一、微信小程序支付 1、微信小程序端请求支付接口 商户在小程序中先调用该接口在微信支付服务后台生成预支付交易单,返回正确的预支付交易后调起支付。具体可以查看接口示例。 接口传入参数示例: 接口返回示例: 二、接口调用(C#) 1、支付接口方法 2、支付结果通知API 3、Utility类 4、Pay ......

一、微信小程序支付

1、微信小程序端请求支付接口

    商户在小程序中先调用该接口在微信支付服务后台生成预支付交易单,返回正确的预支付交易后调起支付。具体可以查看。

    接口传入参数示例:

<xml>
   <appid>wx2421b1c4370ec43b</appid>
   <attach>支付测试</attach>
   <body>jsapi支付测试</body>
   <mch_id>10000100</mch_id>
   <nonce_str>1add1a30ac87aa2db72f57a2375d8fec</nonce_str>
   <notify_url>http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php</notify_url>
   <openid>oupf8umuajo_m2pxb1q9znjwes6o</openid>
   <out_trade_no>1415659990</out_trade_no>
   <spbill_create_ip>14.23.150.211</spbill_create_ip>
   <total_fee>1</total_fee>
   <trade_type>jsapi</trade_type>
   <sign>0cb01533b8c1ef103065174f50bca001</sign>
</xml>

    接口返回示例:

<xml>
   <return_code><![cdata[success]]></return_code>
   <return_msg><![cdata[ok]]></return_msg>
   <appid><![cdata[wx2421b1c4370ec43b]]></appid>
   <mch_id><![cdata[10000100]]></mch_id>
   <nonce_str><![cdata[iitri8iabbblz1jc]]></nonce_str>
   <openid><![cdata[oupf8umuajo_m2pxb1q9znjwes6o]]></openid>
   <sign><![cdata[7921e432f65eb8ed0ce9755f0e86d72f]]></sign>
   <result_code><![cdata[success]]></result_code>
   <prepay_id><![cdata[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>
   <trade_type><![cdata[jsapi]]></trade_type>
</xml>

二、接口调用(c#)

1、支付接口方法

//获取请求数据
dictionary<string, string> strparam = new dictionary<string, string>();
//小程序id
strparam.add("appid", payinfo.appid);
//附加数据
strparam.add("attach", payinfo.attach);
//商品描述
strparam.add("body", payinfo.body);
//商户号
strparam.add("mch_id", payinfo.mchid);
//随机字符串
strparam.add("nonce_str", payinfo.noncestr);
//通知地址 (异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。)
strparam.add("notify_url", payinfo.notifyurl);
//用户标识
strparam.add("openid", openid);
//商户订单号
strparam.add("out_trade_no", ordernum);
//终端ip
strparam.add("spbill_create_ip", payinfo.addrip);
//标价金额
strparam.add("total_fee", convert.toint32(ordertotal * 100).tostring());
//交易类型
strparam.add("trade_type", payinfo.tradetype);
strparam.add("sign", payhelper.getsigninfo(strparam, payinfo.key));
//获取预支付id
string preinfo = utility.posthttpresponse(payinfo.orderurl, payhelper.createxmlparam(strparam));
string strcode = payhelper.getxmlvalue(preinfo, "return_code");
string strmsg = payhelper.getxmlvalue(preinfo, "return_msg");
if (strcode == "success")
{
    //再次签名
    string nonecstr = payinfo.noncestr;
    string timestamp = payinfo.timestamp;
    string package = "prepay_id=" + payhelper.getxmlvalue(preinfo, "prepay_id");
    dictionary<string, string> singinfo = new dictionary<string, string>();
    singinfo.add("appid", payinfo.appid);
    singinfo.add("noncestr", nonecstr);
    singinfo.add("package", package);
    singinfo.add("signtype", payinfo.signtype);
    singinfo.add("timestamp", timestamp);
    //返回参数
    info.msg = strmsg;
    info.code = strcode;
    info.id = orderid;
    info.appid = payinfo.appid;
    info.orderguid = ordernum;
    info.package = package;
    info.timestamp = timestamp;
    info.noncestr = nonecstr;
    info.signtype = payinfo.signtype;
    info.paysign = payhelper.getsigninfo(singinfo, payinfo.key);
    listmsg.add(info);
    result = u.successmsg(listmsg, "", "");
}
else
{
    info.code = strcode;
    info.msg = strmsg;
    listmsg.add(info);
    result = u.failmsg(listmsg);
}

2、支付结果通知api

/// <summary>
/// 支付结果通知api
/// </summary>
/// <returns></returns>
[httppost]
public string ordernotify()
{
    string strresult = string.empty;
    try
    {
        //1.获取微信通知的参数
        string strxml = utility.getpoststr();
        //判断是否请求成功
        if (payhelper.getxmlvalue(strxml, "return_code") == "success")
        {
            //判断是否支付成功
            if (payhelper.getxmlvalue(strxml, "result_code") == "success")
            {
                //获得签名
                string getsign = payhelper.getxmlvalue(strxml, "sign");
                //进行签名
                string sign = payhelper.getsigninfo(payhelper.getfromxml(strxml), payinfo.key);
                if (sign == getsign)
                {
                    //校验订单信息
                    string wxordernum = payhelper.getxmlvalue(strxml, "transaction_id"); //微信订单号
                    string ordernum = payhelper.getxmlvalue(strxml, "out_trade_no");    //商户订单号
                    string ordertotal = payhelper.getxmlvalue(strxml, "total_fee");
                    string openid = payhelper.getxmlvalue(strxml, "openid");
                    //校验订单是否存在
                    if (true)
                    {
                        //2.更新订单的相关状态
     
                        //3.返回一个xml格式的结果给微信服务器
                        if (obj > 0)
                        {
                            strresult = payhelper.getreturnxml("success", "ok");
                        }
                        else
                        {
                            strresult = payhelper.getreturnxml("fail", "订单状态更新失败");
                        }
                    }
                    else
                    {
                        strresult = payhelper.getreturnxml("fail", "支付结果中微信订单号数据库不存在!");
                    }
                }
                else
                {
                    strresult = payhelper.getreturnxml("fail", "签名不一致!");
                }
            }
            else
            {
                strresult = payhelper.getreturnxml("fail", "支付通知失败!");
            }
        }
        else
        {
            strresult = payhelper.getreturnxml("fail", "支付通知失败!");
        }
     
        #endregion
    }
    catch (exception ex)
    {
      
    }
    return strresult;
}

3、utility类

/// <summary>
/// 获得post过来的数据  
/// </summary>
/// <returns></returns>
public static string getpoststr()
{
    int32 intlen = convert.toint32(httpcontext.current.request.inputstream.length);
    byte[] b = new byte[intlen];
    httpcontext.current.request.inputstream.read(b, 0, intlen);
    return encoding.utf8.getstring(b);
}

/// <summary>  
/// 模拟post提交  
/// </summary>  
/// <param name="url">请求地址</param>  
/// <param name="xmlparam">xml参数</param>  
/// <returns>返回结果</returns>  
public static string posthttpresponse(string url, string xmlparam)
{
    httpwebrequest myhttpwebrequest = (httpwebrequest)httpwebrequest.create(url);
    myhttpwebrequest.method = "post";
    myhttpwebrequest.contenttype = "application/x-www-form-urlencoded;charset=utf-8";

    // encode the data  
    byte[] encodedbytes = encoding.utf8.getbytes(xmlparam);
    myhttpwebrequest.contentlength = encodedbytes.length;

    // write encoded data into request stream  
    stream requeststream = myhttpwebrequest.getrequeststream();
    requeststream.write(encodedbytes, 0, encodedbytes.length);
    requeststream.close();

    httpwebresponse result;

    try
    {
        result = (httpwebresponse)myhttpwebrequest.getresponse();
    }
    catch
    {
        return string.empty;
    }

    if (result.statuscode == httpstatuscode.ok)
    {
        using (stream mystream = result.getresponsestream())
        {
            using (streamreader reader = new streamreader(mystream))
            {
                return reader.readtoend();
            }
        }
    }
    return null;
}

4、payhelper类

#region 生成签名
/// <summary>
/// 获取签名数据
///</summary>
/// <param name="strparam"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string getsigninfo(dictionary<string, string> strparam, string key)
{
    int i = 0;
    string sign = string.empty;
    stringbuilder sb = new stringbuilder();
    try
    {
        foreach (keyvaluepair<string, string> temp in strparam)
        {
            if (temp.value == "" || temp.value == null || temp.key.tolower() == "sign")
            {
                continue;
            }
            i++;
            sb.append(temp.key.trim() + "=" + temp.value.trim() + "&");
        }
        sb.append("key=" + key.trim() + "");
        sign = md5core.gethashstring(sb.tostring(), encoding.utf8).toupper();
    }
    catch (exception ex)
    {
        utility.addlog("payhelper", "getsigninfo", ex.message, ex);
    }
    return sign;
}
#endregion

#region xml 处理
/// <summary>
/// 获取xml值
/// </summary>
/// <param name="strxml">xml字符串</param>
/// <param name="strdata">字段值</param>
/// <returns></returns>
public static string getxmlvalue(string strxml, string strdata)
{
    string xmlvalue = string.empty;
    xmldocument xmldocument = new xmldocument();
    xmldocument.loadxml(strxml);
    var selectsinglenode = xmldocument.documentelement.selectsinglenode(strdata);
    if (selectsinglenode != null)
    {
        xmlvalue = selectsinglenode.innertext;
    }
    return xmlvalue;
}

/// <summary>
/// 集合转换xml数据 (拼接成xml请求数据)
/// </summary>
/// <param name="strparam">参数</param>
/// <returns></returns>
public static string createxmlparam(dictionary<string, string> strparam)
{
    stringbuilder sb = new stringbuilder();
    try
    {
        sb.append("<xml>");
        foreach (keyvaluepair<string, string> k in strparam)
        {
            if (k.key == "attach" || k.key == "body" || k.key == "sign")
            {
                sb.append("<" + k.key + "><![cdata[" + k.value + "]]></" + k.key + ">");
            }
            else
            {
                sb.append("<" + k.key + ">" + k.value + "</" + k.key + ">");
            }
        }
        sb.append("</xml>");
    }
    catch (exception ex)
    {
        utility.addlog("payhelper", "createxmlparam", ex.message, ex);
    }

    return sb.tostring();
}

/// <summary>
/// xml数据转换集合(xml数据拼接成字符串)
/// </summary>
/// <param name="xmlstring"></param>
/// <returns></returns>
public static dictionary<string, string> getfromxml(string xmlstring)
{
    dictionary<string, string> sparams = new dictionary<string, string>();
    try
    {
        xmldocument doc = new xmldocument();
        doc.loadxml(xmlstring);
        xmlelement root = doc.documentelement;
        int len = root.childnodes.count;
        for (int i = 0; i < len; i++)
        {
            string name = root.childnodes[i].name;
            if (!sparams.containskey(name))
            {
                sparams.add(name.trim(), root.childnodes[i].innertext.trim());
            }
        }
    }
    catch (exception ex)
    {
        utility.addlog("payhelper", "getfromxml", ex.message, ex);
    }
    return sparams;
}

/// <summary>
/// 返回通知 xml
/// </summary>
/// <param name="returncode"></param>
/// <param name="returnmsg"></param>
/// <returns></returns>
public static string getreturnxml(string returncode, string returnmsg)
{
    stringbuilder sb = new stringbuilder();
    sb.append("<xml>");
    sb.append("<return_code><![cdata[" + returncode + "]]></return_code>");
    sb.append("<return_msg><![cdata[" + returnmsg + "]]></return_msg>");
    sb.append("</xml>");
    return sb.tostring();
}
#endregion

5、payinfo类

public class payinfo
{
    /// <summary>
    /// 小程序登录api
    /// </summary>
    public static string loginurl = configurationmanager.appsettings["loginurl"].tostring();

    /// <summary>
    /// 统一下单api
    /// </summary>
    public static string orderurl = configurationmanager.appsettings["orderurl"].tostring();

    /// <summary>
    /// 支付结果通知api
    /// </summary>
    public static string notifyurl = configurationmanager.appsettings["notifyurl"].tostring();

    /// <summary>
    /// 查询订单api
    /// </summary>
    public static string queryurl = configurationmanager.appsettings["queryurl"].tostring();

    /// <summary>
    /// 申请退款api
    /// </summary>
    public static string refundurl = configurationmanager.appsettings["refundurl"].tostring();

    /// <summary>
    /// 退款通知api
    /// </summary>
    public static string refundnotifyurl = configurationmanager.appsettings["refundnotifyurl"].tostring();

    /// <summary>
    /// 退款通知api
    /// </summary>
    public static string refundqueryurl = configurationmanager.appsettings["refundqueryurl"].tostring();

    /// <summary>
    /// 小程序唯一标识
    /// </summary>
    public static string appid = configurationmanager.appsettings["appid"].tostring();

    /// <summary>
    /// 小程序的 app secret
    /// </summary>
    public static string secret = configurationmanager.appsettings["secret"].tostring();

    /// <summary>
    /// 小程序的授权类型 
    /// </summary>
    public static string granttype = configurationmanager.appsettings["grant_type"].tostring();

    /// <summary>
    /// 商户号(微信支付分配的商户号)
    /// </summary>
    public static string mchid = configurationmanager.appsettings["mch_id"].tostring();

    /// <summary>
    ///商户平台设置的密钥key
    /// </summary>
    public static string key = configurationmanager.appsettings["key"].tostring();

    /// <summary>
    /// 随机字符串不长于 32 位
    /// </summary>
    public static string noncestr = payhelper.getnoncestr();

    /// <summary>
    /// 时间戳 从1970年1月1日00:00:00至今的秒数,即当前的时间
    /// </summary>
    public static string timestamp = payhelper.gettimestamp();

    /// <summary>
    /// 终端ip app和网页支付提交用户端ip,
    /// </summary>
    public static string addrip = payhelper.getip;

    /// <summary>
    /// 交易类型 小程序取值如下:jsapi
    /// </summary>
    public static string tradetype = "jsapi";

    /// <summary>
    /// 签名类型 默认为md5,支持hmac-sha256和md5。
    /// </summary>
    public static string signtype = "md5";

    /// <summary>
    /// 商品描述 商品简单描述,该字段请按照规范传递
    /// </summary>
    public static string body = "奇小爱的异想世界-支付";

    /// <summary>
    /// 附加数据 在查询api和支付通知中原样返回
    /// </summary>
    public static string attach = "微信支付信息";

    /// <summary>
    /// 签名,参与签名参数:appid,mch_id,transaction_id,out_trade_no,nonce_str,key
    /// </summary>
    public string sign = "";

    /// <summary>
    /// 微信订单号,优先使用
    /// </summary>
    public static string transactionid = "";

    /// <summary>
    /// 商户系统内部订单号
    /// </summary>
    public static string out_trade_no = "";

    /// <summary>
    /// 商户退款单号
    /// </summary>
    public static string out_refund_no = "";

    /// <summary>
    /// 退款金额
    /// </summary>
    public static decimal refundfee;

    /// <summary>
    /// 订单金额
    /// </summary>
    public static decimal totalfee;
}

三、微信小程序调用

1、小程序调用方法,发起支付,具体如下:

    微信小程序支付方。

微信小程序之微信支付C#后台(统一下单)

2、示例代码:

wx.requestpayment({
   'timestamp': '',
   'noncestr': '',
   'package': '',
   'signtype': 'md5',
   'paysign': '',
   'success':function(res){
   },
   'fail':function(res){
   }
})

3、测试完成支付

微信小程序之微信支付C#后台(统一下单)

 

优秀是一种习惯,欢迎大家关注学习 

微信小程序之微信支付C#后台(统一下单)