public class WechatJSAPI
{
static string price = "1";//价格
static string ip = "----------------------------------IP------------------------";
static string WeChatH5NotifyUrl = "----------------------------------页面回调地址------------------------";
static string openid = "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o";
public static string JSapiH5Pay()
{
var dic = new Dictionary<string, string>();
dic.Add("appid", "**************");//应用ID
dic.Add("mch_id", "********");//商户号
dic.Add("nonce_str", Common.GetNoncestr());//随机数
dic.Add("body", $"*********");//商品描述
dic.Add("out_trade_no", Common.OrderID());
dic.Add("total_fee", price);//价格 微信的单位是分
dic.Add("spbill_create_ip", ip);//设备IP
dic.Add("notify_url", WeChatH5NotifyUrl);//回调地址
dic.Add("trade_type", "JSAPI");//支付类型手机网站
dic.Add("openid", openid);//openid
string sign = Common.GetSignContent(dic) + "&key=*************";//参数排序 //签名 第一步 把参数按照字母排序 并加上key
sign = Common.MD5(sign);//第二步 MD5加密
dic.Add("sign", sign);//加密的签名
string requestXml = JsonConvert.DeserializeXmlNode(JsonConvert.SerializeObject(dic), "xml").InnerXml;//dic转Xml
string result = null;
try
{
result = Common.HttpPostWechatPay("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXml);//开始请求微信支付
return result;
}
catch (Exception ex)
{
return ex.Message;
}
}
}
------------------------------Common公共方法----------------------------
/// <summary>
/// 生成订单ID
/// </summary>
/// <returns></returns>
public static string OrderID()
{
//随机6位数字
string time = DateTime.Now.ToString("yyyyMMddHHmmss");
Random r = new Random();
int num = r.Next(1, 1001);
string OrderID = time + (num < 10 ? "0" + num : num.ToString());
return OrderID;
}
/// <summary>
/// 生成随机字符串
/// </summary>
/// <returns></returns>
public static string GetNoncestr()
{
Random random = new Random();
return MD5(random.Next(1000).ToString(), "utf-8");
}
/// <summary>
/// 获取大写的MD5签名结果
/// </summary>
/// <param name="encypStr"></param>
/// <param name="charset"></param>
/// <returns></returns>
public static string MD5(string encypStr, string charset)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] bs = Encoding.GetEncoding(charset).GetBytes(encypStr);
bs = md5.ComputeHash(bs);
return BytesToHexString(bs);
}
/// <summary>
/// 获取大写的MD5签名结果
/// </summary>
/// <param name="encypStr"></param>
/// <returns></returns>
public static string MD5(string encypStr)
{
return MD5(encypStr, "utf-8");
}
public static string BytesToHexString(byte[] bytes)
{
StringBuilder s = new StringBuilder();
foreach (byte b in bytes)
{
s.Append(b.ToString("x2").ToUpper());
}
return s.ToString();
}
public static string GetSignContent(IDictionary<string, string> parameters)
{
// 第一步:把字典按Key的字母顺序排序
IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
// 第二步:把所有参数名和参数值串在一起
StringBuilder query = new StringBuilder("");
while (dem.MoveNext())
{
string key = dem.Current.Key;
string value = dem.Current.Value;
if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
{
query.Append(key).Append("=").Append(value).Append("&");
}
}
string content = query.ToString().Substring(0, query.Length - 1);
return content;
}
/// <summary>
/// HTTP POST方式请求数据
/// </summary>
/// <param name="url">URL.</param>
/// <param name="param">POST的数据</param>
/// <returns></returns>
public static string HttpPostWechatPay(string url, string param)
{
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((a, b, c, d) => { return true; });
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
}
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.Timeout = 55000; //阀值调整
request.AllowAutoRedirect = false;
StreamWriter requestStream = null;
WebResponse response = null;
string responseStr = null;
try
{
requestStream = new StreamWriter(request.GetRequestStream());
requestStream.Write(param);
requestStream.Close();
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception ex)
{
throw;
}
finally
{
request = null;
requestStream = null;
response = null;
}
return responseStr;
}
--------------------------------------------请求参数XML格式------------------------------------
----------------------请求参数:----------------------
微信官方:
<xml>
<appid>----------</appid>
<attach>支付测试</attach>
<body>JSAPI支付测试</body>
<mch_id>10000100</mch_id>
<nonce_str>1add1a30ac87aa2db72f57a2375d8fec</nonce_str>
<notify_url>----------------</notify_url>
<openid>-----------------</openid>
<out_trade_no>--------------</out_trade_no>
<spbill_create_ip>14.23.150.211</spbill_create_ip>
<total_fee>1</total_fee>
<trade_type>JSAPI</trade_type>
<sign>---------</sign>
</xml>
api:
<xml>
<appid>------------</appid>
<mch_id>10010746</mch_id>
<nonce_str>--------------------</nonce_str>
<body>------------------------</body>
<out_trade_no>-----------</out_trade_no>
<total_fee>1</total_fee>
<spbill_create_ip>14.23.150.211</spbill_create_ip>
<notify_url>-------</no----------tify_url>
<trade_type>JSAPI</trade_type>
<sign>95AFF01E75E46FDD616C9D93249E2E3D</sign>
</xml>
----------------------返回参数:----------------------
<xml>
<return_code><![CDATA[SUCCESS]]></return_code>
<return_msg><![CDATA[OK]]></return_msg>
<appid><![CDATA[-------]]></appid>
<mch_id><![CDATA[-----]]></mch_id>
<nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>
<openid><![CDATA[------------]]></openid>
<sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>
<result_code><![CDATA[SUCCESS]]></result_code>
<prepay_id><![CDATA[------------------]]></prepay_id>
<trade_type><![CDATA[JSAPI]]></trade_type>
</xml>