c#微信支付,如何与小程序交互实例代码
时间: 2024-04-02 09:33:52 浏览: 130
以下是一个简单的C#代码示例,用于与小程序进行微信支付的交互:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
using System.Xml;
namespace WeChatPayDemo
{
public class WeChatPayHelper
{
//微信支付的API地址
private const string WECHAT_PAY_API = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//微信支付商户号
private const string WECHAT_PAY_MCHID = "XXXXXXXXXXXX";
//微信支付密钥
private const string WECHAT_PAY_KEY = "XXXXXXXXXXXX";
//小程序的AppID
private const string WECHAT_APPID = "XXXXXXXXXXXX";
//生成随机字符串
private static string GenerateNonceStr()
{
return Guid.NewGuid().ToString().Replace("-", "").Substring(0, 32);
}
//生成签名
private static string GenerateSign(Dictionary<string, string> data)
{
var list = data.ToList();
list.Sort((a, b) => string.Compare(a.Key, b.Key, StringComparison.Ordinal));
var builder = new StringBuilder();
foreach (var item in list)
{
if (!string.IsNullOrEmpty(item.Value))
{
builder.Append(item.Key).Append('=').Append(item.Value).Append('&');
}
}
builder.Append("key=").Append(WECHAT_PAY_KEY);
return MD5Helper.MD5(builder.ToString()).ToUpper();
}
//生成XML数据
private static string GenerateXml(Dictionary<string, string> data)
{
var builder = new StringBuilder();
builder.Append("<xml>");
foreach (var item in data)
{
builder.Append("<").Append(item.Key).Append(">");
builder.Append("<![CDATA[").Append(item.Value).Append("]]>");
builder.Append("</").Append(item.Key).Append(">");
}
builder.Append("</xml>");
return builder.ToString();
}
//发送HTTP请求,并返回响应数据
private static string SendHttpRequest(string url, string data)
{
var request = WebRequest.CreateHttp(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var bytes = Encoding.UTF8.GetBytes(data);
request.ContentLength = bytes.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
}
var response = request.GetResponse();
using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
//生成微信支付订单信息,并返回给小程序端
public static string GenerateWeChatPayOrder(string openid, string orderId, int totalFee, string clientIP, string notifyUrl)
{
var nonceStr = GenerateNonceStr();
var timestamp = DateTime.Now.ToUniversalTime().ToString("yyyyMMddHHmmss");
var data = new Dictionary<string, string>
{
{"appid", WECHAT_APPID},
{"mch_id", WECHAT_PAY_MCHID},
{"nonce_str", nonceStr},
{"body", "测试商品"},
{"out_trade_no", orderId},
{"total_fee", (totalFee * 100).ToString()},
{"spbill_create_ip", clientIP},
{"notify_url", notifyUrl},
{"trade_type", "JSAPI"},
{"openid", openid},
{"sign_type", "MD5"},
{"time_start", timestamp},
{"time_expire", DateTime.Now.AddMinutes(30).ToUniversalTime().ToString("yyyyMMddHHmmss")},
};
data.Add("sign", GenerateSign(data));
var xml = GenerateXml(data);
var responseXml = SendHttpRequest(WECHAT_PAY_API, xml);
var doc = new XmlDocument();
doc.LoadXml(responseXml);
var prepayId = doc.SelectSingleNode("/xml/prepay_id").InnerText;
var package = $"prepay_id={prepayId}";
var data2 = new Dictionary<string, string>
{
{"appId", WECHAT_APPID},
{"nonceStr", nonceStr},
{"package", package},
{"signType", "MD5"},
{"timeStamp", timestamp},
};
data2.Add("paySign", GenerateSign(data2));
var serializer = new JavaScriptSerializer();
return serializer.Serialize(data2);
}
}
}
```
这是一个简单的示例,仅供参考。具体的实现方式可能会因为不同的业务需求而有所变化,可以根据实际情况进行调整。
阅读全文