欢迎光临
我们一直在努力

c# .net 实现微信支付jsapi v3接口(JSAPI下单)

本文章记录一下通过.net 实现微信支付调用jsapi v3接口  统一下意接口

接口地址 :

https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi

需要引用

using System.Security.Cryptography;

 

发起请求、加密、签名代码如下

 /// <summary>
    /// 
    /// </summary>
    /// <param name="url">微信的接口地址</param>
    /// <param name="postData">post请求的数据,json格式 </param>
    /// <param name="privateKey">apiclient_key.pem中的内容,不要-----BEGIN PRIVATE KEY-----  -----END PRIVATE KEY-----</param>
    /// <param name="merchantId">发起请求的商户(包括直连商户、服务商或渠道商)的商户号 mchid</param>
    /// <param name="serialNo">商户证书号</param>
    /// <returns></returns>
    public string postJson(string url, string postData, string privateKey, string merchantId, string serialNo)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/json;charset=UTF-8";
        request.UserAgent = "faloo.com/WebRequest";
        request.Accept = "application/json";

        string Authorization = GetAuthorization(url, "POST", postData, privateKey, merchantId, serialNo);
        request.Headers.Add("Authorization", Authorization);
        byte[] paramJsonBytes;
        paramJsonBytes = System.Text.Encoding.UTF8.GetBytes(postData);
        request.ContentLength = paramJsonBytes.Length;
        Stream writer;
        try
        {
            writer = request.GetRequestStream();
        }
        catch (Exception)
        {
            writer = null;
            Console.Write("连接服务器失败!");
        }
        writer.Write(paramJsonBytes, 0, paramJsonBytes.Length);
        writer.Close();
        HttpWebResponse response;
        try
        {
            response = (HttpWebResponse)request.GetResponse();
        }
        catch (WebException ex)
        {
            response = ex.Response as HttpWebResponse;
        }
        Stream resStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(resStream);
        string text = reader.ReadToEnd();
        return text;
    }

    //获取HTTP头的授权信息
    /// <summary>
    /// 
    /// </summary>
    /// <param name="url">微信的接口地址</param>
    /// <param name="method">请求的方式GET,POST,PUT</param>
    /// <param name="jsonParame">post请求的数据,json格式  ,get时传空</param>
    /// <param name="privateKey">apiclient_key.pem中的内容,不要-----BEGIN PRIVATE KEY-----  -----END PRIVATE KEY-----</param>
    /// <param name="merchantId">发起请求的商户(包括直连商户、服务商或渠道商)的商户号 mchid</param>
    /// <param name="serialNo">商户证书号</param>
    /// <returns></returns>
    protected string GetAuthorization(string url, string method, string jsonParame, string privateKey, string merchantId, string serialNo)
    {
        var uri = new Uri(url);
        string urlPath = uri.PathAndQuery;
        string nonce = Guid.NewGuid().ToString();
        var timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
        //数据签名     HTTP请求方法\n接口地址的url\n请求时间戳\n请求随机串\n请求报文主体\n
        method = string.IsNullOrEmpty(method) ? "" : method;
        string message = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n", method, urlPath, timestamp, nonce, jsonParame);
        string signTxt = Sign(message, privateKey);



        //Authorization和格式
        string authorzationTxt = string.Format("WECHATPAY2-SHA256-RSA2048 mchid=\"{0}\",nonce_str=\"{1}\",timestamp=\"{2}\",serial_no=\"{3}\",signature=\"{4}\"",
            merchantId,
            nonce,
            timestamp,
            serialNo,
            signTxt
            );
        return authorzationTxt;
    }

    protected string Sign(string message, string privateKey)
    {
        byte[] keyData = Convert.FromBase64String(privateKey);
        using (CngKey cngKey = CngKey.Import(keyData, CngKeyBlobFormat.Pkcs8PrivateBlob))
        using (RSACng rsa = new RSACng(cngKey))
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
            return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
        }
    }

 

 

调用接口代码

string merchantId = "";   //商户号
        string serialNo = "";  //证书编号
        string privateKey = @""; // NOTE: 私钥不包括私钥文件起始的-----BEGIN PRIVATE KEY----- 亦不包括结尾的-----END PRIVATE KEY-----

        StringBuilder str = new StringBuilder();
        str.Append("{");
        str.AppendFormat("	\"mchid\": \"{0}\",", merchantId);
        str.AppendFormat("	\"out_trade_no\": \"{0}_{1}\",", DateTime.Now.ToString("yyyyMMddHHmmss"), UserID);
        str.Append("	\"appid\": \"wx3ec325cc846b0202\",");
        str.Append("	\"description\": \"描述如某某充值\",");
        str.Append("	\"notify_url\": \"https://xxx.xxx.com/WXAppPayNotify.aspx\",");  //支付成功后的通知地址 
        str.Append("	\"amount\": {");
        str.AppendFormat("		\"total\": {0},", 1);  //支付金额
        str.Append("		\"currency\": \"CNY\"");
        str.Append("	},");
        str.Append("	\"payer\": {");
        str.Append("		\"openid\": \""+ UserThirdId + "\"");
        str.Append("	}");
        str.Append("}");
        

        string transactionsResponse = postJson("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi", str.ToString(), privateKey, merchantId, serialNo);

 

 

 

赞(0)
未经允许不得转载:自游互动 » c# .net 实现微信支付jsapi v3接口(JSAPI下单)
分享到: 更多 (0)

自由技术,自由自在

项目合作联系我们