PC 端客戶端完全可以直接使用 HTTPS 與微信後台通信。HTTPS 不是瀏覽器專用,任何支持 TLS/SSL 的 HTTP 客戶端庫均可發起請求。
using System.Net.Http;
using System.Text;
using System.Security.Cryptography.X509Certificates;
public async Task<string> PostToWeChatAsync(string url, string xmlData, string certPath, string certPassword) {
var handler = new HttpClientHandler();
// 加載商戶證書(雙向認證)
var cert = new X509Certificate2(certPath, certPassword);
handler.ClientCertificates.Add(cert);
// 忽略服務端證書驗證(生產環境請勿忽略,需配置信任根證書)
handler.ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) => true;
using (var client = new HttpClient(handler)) {
var content = new StringContent(xmlData, Encoding.UTF8, "application/xml");
var response = await client.PostAsync(url, content);
return await response.Content.ReadAsStringAsync();
}
}
apiclient_cert.p12,記住密碼(默認商戶號)。HttpClient 發送 application/xml 數據。return_code 和 result_code。async/await。HttpClient 應單例復用,避免端口耗盡。官方 Demo:https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1
C# SDK:https://github.com/WeChatPay/WeChatPaySDK