麻烦用C# .net写
时间: 2023-07-27 18:28:20 浏览: 158
好的,下面是使用C# .NET Framework写的微信扫码支付的WEB应用程序示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using System.Xml.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Net;
using System.IO;
namespace WeChatPayDemo.Controllers
{
public class HomeController : Controller
{
// 商户号
const string mch_id = "your-mch-id";
// 商户API密钥
const string api_key = "your-api-key";
// 应用ID
const string appid = "your-appid";
// 通知地址
const string notify_url = "http://your-domain.com/notify";
// 支付请求地址
const string pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
// 首页
public ActionResult Index()
{
return View();
}
// 支付页面
public ActionResult Pay(string total_fee)
{
// 生成订单号
string out_trade_no = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(1000, 9999);
// 构造支付请求参数
SortedDictionary<string, object> parameters = new SortedDictionary<string, object>();
parameters.Add("appid", appid);
parameters.Add("mch_id", mch_id);
parameters.Add("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));
parameters.Add("body", "微信扫码支付");
parameters.Add("out_trade_no", out_trade_no);
parameters.Add("total_fee", int.Parse(float.Parse(total_fee) * 100 + ""));
parameters.Add("spbill_create_ip", Request.UserHostAddress);
parameters.Add("notify_url", notify_url);
parameters.Add("trade_type", "NATIVE");
// 签名
string sign = Sign(parameters);
parameters.Add("sign", sign);
// 构造XML请求内容
string requestXml = BuildXml(parameters);
// 发送支付请求
string responseXml = HttpPost(pay_url, requestXml);
// 解析响应XML
XDocument doc = XDocument.Parse(responseXml);
string prepay_id = doc.Element("xml").Element("prepay_id").Value;
string code_url = doc.Element("xml").Element("code_url").Value;
// 构造二维码图片链接
string qr_code_url = $"https://api.qrserver.com/v1/create-qr-code/?size=150x150&data={HttpUtility.UrlEncode(code_url)}";
// 传递二维码图片链接和订单号到支付页面
ViewBag.QRCodeUrl = qr_code_url;
ViewBag.OutTradeNo = out_trade_no;
return View();
}
// 支付结果通知接口
public ActionResult Notify()
{
// 接收POST数据
Stream stream = Request.InputStream;
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
string xml = Encoding.UTF8.GetString(bytes);
// 解析XML数据
XDocument doc = XDocument.Parse(xml);
string return_code = doc.Element("xml").Element("return_code").Value;
string return_msg = doc.Element("xml").Element("return_msg").Value;
string result_code = doc.Element("xml").Element("result_code").Value;
string out_trade_no = doc.Element("xml").Element("out_trade_no").Value;
string transaction_id = doc.Element("xml").Element("transaction_id").Value;
// 验证签名
SortedDictionary<string, object> parameters = new SortedDictionary<string, object>();
parameters.Add("return_code", return_code);
parameters.Add("return_msg", return_msg);
parameters.Add("result_code", result_code);
parameters.Add("out_trade_no", out_trade_no);
parameters.Add("transaction_id", transaction_id);
string sign = Sign(parameters);
string sign_received = doc.Element("xml").Element("sign").Value;
if (sign == sign_received)
{
// 处理支付结果
// ...
// 返回通知结果
return Content(BuildXml(new Dictionary<string, object> { { "return_code", "SUCCESS" }, { "return_msg", "OK" } }));
}
else
{
// 签名验证失败
// ...
// 返回错误信息
return Content(BuildXml(new Dictionary<string, object> { { "return_code", "FAIL" }, { "return_msg", "签名验证失败" } }));
}
}
// 签名算法
private string Sign(IDictionary<string, object> parameters)
{
string stringA = string.Join("&", parameters.Where(p => !string.IsNullOrEmpty(p.Value.ToString())).OrderBy(p => p.Key).Select(p => $"{p.Key}={p.Value}"));
string stringSignTemp = $"{stringA}&key={api_key}";
string sign = MD5(stringSignTemp).ToUpper();
return sign;
}
// MD5算法
private string MD5(string input)
{
MD5 md5 = MD5.Create();
byte[] buffer = Encoding.UTF8.GetBytes(input);
byte[] hash = md5.ComputeHash(buffer);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("x2"));
}
return sb.ToString();
}
// 构造XML请求内容
private string BuildXml(IDictionary<string, object> parameters)
{
StringBuilder sb = new StringBuilder();
sb.Append("<xml>");
foreach (var kv in parameters)
{
sb.Append($"<{kv.Key}>{kv.Value}</{kv.Key}>");
}
sb.Append("</xml>");
return sb.ToString();
}
// 发送HTTP POST请求
private string HttpPost(string url, string data)
{
byte[] bytes = Encoding.UTF8.GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
}
}
```
以上代码仅供参考,实际开发中需要根据实际情况进行相应的修改和完善。同时,也需要遵循相关的安全规范和隐私保护措施,确保用户信息和支付安全。
阅读全文