August 26, 2019

C# HttpClient 添加 SSL 证书

using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var certPath = $"{AppDomain.CurrentDomain.BaseDirectory}apiclient_cert.p12";
        var certPassword = "PW";
        var certificate = new X509Certificate2(path, certPassword);

        var handler = new HttpClientHandler();
        handler.ClientCertificates.Add(certificate);

        var client = new HttpClient(handler);
        var requestUrl = "https://domian_com";
        var requestBody = "";
        var response = await client.PostAsync(requestUrl, requestBody);
        var responseBody = await response.Content.ReadAsStringAsync();

        Console.WriteLine(responseBody);
    }
}

以微信支付接口(转账到零钱)例:

using System;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var mchAppid = "mock";
        var mchId = "mock";
        var mchKey = "mock";
    
        // 使用官方 SDK 中提供的 WxPayData 类
        var data = new WxPayData();
        data.SetValue("mch_appid", mchAppid);
        data.SetValue("mchid", mchId);
        data.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", string.Empty));
        data.SetValue("partner_trade_no", DateTime.Now.ToString("yyyyMMddHHmmssffffff"));
        data.SetValue("openid", "");
        data.SetValue("check_name", "NO_CHECK");
        data.SetValue("amount", 100);
        data.SetValue("desc", "测试");
        data.SetValue("spbill_create_ip", "0.0.0.0");
        data.SetValue("sign", data.MakeSign(mchKey));

        var requestBody = new StringContent(data.ToXml());
        Console.WriteLine(requestBody);

        var path = $"{AppDomain.CurrentDomain.BaseDirectory}apiclient_cert.p12";
        var certificate = new X509Certificate2(path, mchId);

        var handler = new HttpClientHandler();
        handler.ClientCertificates.Add(certificate);

        var client = new HttpClient(handler);
        var requestUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        var response = await client.PostAsync(requestUrl, requestBody);
        var responseBody = await response.Content.ReadAsStringAsync();

        Console.WriteLine(responseBody);
    }
}