[关闭]
@net8848 2024-09-17T03:02:17.000000Z 字数 3095 阅读 88

以下是使用 C# 和 ASP.NET 接入微信支付 H5 页面的示例代码及相关步骤讲解:
C# 和 ASP.NET 接入微信支付 H5 示例代码

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Linq;

public class WeChatPayService
{
// 微信支付配置信息(请替换为你的实际配置)
private string appId = "你的微信公众号 APPID";
private string mchId = "你的商户号";
private string key = "你的商户支付密钥";

// 统一下单接口地址
private string unifiedOrderUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";

public string WeChatH5Pay(string orderId, string totalFee, string body, string notifyUrl, string returnUrl)
{
    // 换算金额,以分为单位
    int totalMoney = Convert.ToInt32(Convert.ToDecimal(totalFee) * 100);

    // 生成随机字符串
    string nonceStr = GenerateNonceStr();

    // 创建请求处理器
    Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
    packageReqHandler.SetParameter("appid", appId);
    packageReqHandler.SetParameter("mch_id", mchId);
    packageReqHandler.SetParameter("nonce_str", nonceStr);
    packageReqHandler.SetParameter("body", body);
    packageReqHandler.SetParameter("out_trade_no", orderId);
    packageReqHandler.SetParameter("total_fee", totalMoney.ToString());
    packageReqHandler.SetParameter("spbill_create_ip", GetClientIP());
    packageReqHandler.SetParameter("notify_url", notifyUrl);
    packageReqHandler.SetParameter("trade_type", "MWEB");
    packageReqHandler.SetParameter("sign", packageReqHandler.CreateMd5Sign("key", key));

    string data = packageReqHandler.ParseXML();

    // 发送 HTTP POST 请求
    var result = HttpPost(unifiedOrderUrl, null, data);

    // 解析返回结果,获取支付跳转链接 mweb_url
    string mwebUrl = "";
    var res = XDocument.Parse(result);
    if (res.Element("xml").Element("return_code").Value == "SUCCESS")
    {
        mwebUrl = res.Element("xml").Element("mweb_url").Value;
    }

    return mwebUrl;
}

private string GenerateNonceStr()
{
    // 生成随机字符串的逻辑,你可以根据实际情况修改
    return Guid.NewGuid().ToString().Replace("-", "").Substring(0, 32);
}

private string GetClientIP()
{
    // 获取客户端 IP 的逻辑,你可以根据实际情况修改
    return HttpContext.Current.Request.UserHostAddress;
}

private string HttpPost(string url, string postData)
{
    byte[] data = Encoding.UTF8.GetBytes(postData);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;

    using (Stream stream = request.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
    }

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
        {
            return reader.ReadToEnd();
        }
    }
}

}

相关步骤讲解
配置信息准备:
appId:微信公众号的 APPID,在微信公众平台注册并获取。
mchId:微信支付商户号,在微信商户平台申请获得。
key:商户支付密钥,在微信商户平台设置。
unifiedOrderUrl:微信支付统一下单接口地址,一般固定为https://api.mch.weixin.qq.com/pay/unifiedorder
方法参数说明:
orderId:商户订单号,保证唯一性,用于标识每一笔交易。
totalFee:订单总金额,单位为元,需要转换为分传入。
body:商品描述信息。
notifyUrl:微信支付异步通知回调地址,用于接收支付结果通知。
returnUrl:支付完成后的跳转返回地址(一般可以和商户网站相关页面链接)。
核心流程:
生成随机字符串:使用GenerateNonceStr方法生成一个不超过 32 位的随机字符串,用于保证请求的唯一性。
设置请求参数:通过Senparc.Weixin.MP.TenPayLibV3.RequestHandler类设置请求统一下单接口的参数,包括appid、mch_id、nonce_str、body、out_trade_no、total_fee、spbill_create_ip、notify_url、trade_type等,其中trade_type设置为"MWEB"表示 H5 支付。
生成签名:使用CreateMd5Sign方法根据参数和密钥生成签名。
发送 HTTP POST 请求:将封装好的 XML 数据发送到微信支付统一下单接口,获取返回结果。
解析返回结果:从返回的 XML 结果中提取mweb_url,即微信支付的跳转链接,如果返回结果中return_code为"SUCCESS",则表示下单成功,获取到mweb_url后,前端可以使用该链接在 H5 页面中调起微信支付。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注