【微信支付踩坑記01】v2版支付簡單示例
阿新 • • 發佈:2022-05-23
v2版生成訂單程式碼
沒什麼好說的
public string WeChatpayJSAPI(string money, string openid,string partner_trade_no,string desc)
{
PayWeChat wPay = new PayWeChat();
try
{
string TheNum = partner_trade_no;
string Appid = mch_appid;
string mch_id = mchid;
string thisurl = "";
string nonce_str = CreatenNonce_str();
string ip = "127.0.0.1";
string wechatpay = Convert.ToInt32(Convert.ToDecimal(money) * 100).ToString();
SortedDictionary<string, string> sParams = new SortedDictionary<string, string>();
sParams.Add("appid", Appid);
sParams.Add("body", string.Format(desc+"。訂單金額:" + money));
sParams.Add("device_info", "JSAPI");
sParams.Add("mch_id", mch_id);//微信商戶號
sParams.Add("nonce_str", nonce_str);
sParams.Add("notify_url", thisurl);//接收回調通知的網址
sParams.Add("openid", openid);//微信使用者openid
sParams.Add("out_trade_no", TheNum);//商戶單號
sParams.Add("spbill_create_ip", ip);//發起者ip
sParams.Add("total_fee", wechatpay);//總金額
sParams.Add("trade_type", "JSAPI");
sParams.Add("sign", MakeWxPaySign(sParams));
StringBuilder sb = new StringBuilder();
sb.Append("<xml>");
foreach (KeyValuePair<string, string> temp in sParams)
{
if (temp.Value == "" || temp.Value == null) continue;
sb.Append("<").Append(temp.Key.Trim()).Append(">");
sb.Append(temp.Value.Trim());
sb.Append("</").Append(temp.Key.Trim()).Append(">");
}
sb.Append("</xml>");
string rv = GetPage("https://api.mch.weixin.qq.com/pay/unifiedorder", sb.ToString());
return rv;
}
catch (Exception e)
{
return "error";
}
}
/// <summary> /// 生成微信支付的簽名 /// </summary> /// <param name="sParams"></param> /// <returns></returns> public static string MakeWxPaySign(SortedDictionary<string, string> sParams)// 生成微信支付的簽名 { string key = "PayKey"; StringBuilder sb = new StringBuilder(); foreach (KeyValuePair<string, string> temp in sParams) { if (temp.Value == "" || temp.Value == null || temp.Key.ToLower() == "sign") { continue; } sb.Append(temp.Key.Trim()+ "=" + temp.Value.Trim() + "&"); } sb.Append("key=" + key.Trim() + ""); string signkey = sb.ToString(); System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] data = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(signkey)); sb = new StringBuilder(); for (int n = 0; n < data.Length; n++) { sb.Append(data[n].ToString("x2")); } return sb.ToString().ToUpper(); }