上篇文章经过开通商家转账到零钱,以及设置安全证书,APIv3密钥,接下来访问接口,获取证书的key,以及密钥。
废话不多说,上酸菜,不对,上代码。
一、首先小程序appid,商户号,证书编号,后台配置好,方便读取
//小程序ID
public static readonly String APPID = GetAppletAppID();
//小程序秘钥
public static readonly String APPSECRET = GetAppletSecret();
//商户号
public static readonly String MCHID = GetMchID();
//商户秘钥
public static readonly String KEY = GetKey();
//证书编号
public static readonly String SERIALNO = GetSERIALNO();
二、安全证书路径
这是也是在配置文件中配置好,或后台上传,读取路径
//=======【证书路径设置】=====================================
/*这是也是在配置文件中配置好,或后台上传,读取路径
/* 证书路径,注意应该填写绝对路径
*/
public const string SSLCERT_PATH = @"D:\安全证书\小程序安全证书\apiclient_cert.p12";
public const string SSLCERT_PASSWORD = "商户号";
服务器物理路径,为了安全起见,不要直接获取privateKey里边的内容
三、获取相关参数,发起请求。这里边为了方便检查问题,写了日志文件Log.Info
Log.Info("开始发起商户转账到零钱:", "开===始");
Log.Info("开始发起商户转账到零钱:", "获取提现金额,amount=" + amount);
Log.Info("开始发起商户转账到零钱:", "获取客户信息,openID=" + openID);
//appid,mchId,serialNo,读取对应的配置文件,openID,amount,读取获取的值,partnerTradeNo自行生成
string partnerTradeNo = "xcx" + DateTime.Now.ToString("yyyyMMddHHmmfff");
string result = ResultV3Withdraw.WithDrawsToWx(appid, mchId, serialNo, openID, partnerTradeNo, Convert.ToInt32(amount * 100));
Log.Info("商户转账到零钱结果:", result);
JObject objs = JObject.Parse(result);
Log.Info("商户转账到零钱结果out_batch_no=", objs["out_batch_no"].ToString());
Log.Info("商户转账到零钱结果batch_id=", objs["batch_id"].ToString());
Log.Info("商户转账到零钱结果create_time=", objs["create_time"].ToString());
发起请求传递参数
public static string WithDrawsToWx(string appid,string mchid,string serialNo,string openID,string partnerTradeNo,decimal totalFee)
{
Log.Info("开始申请商户转账到零钱", "发起请求");
SortedDictionary <string, object> dic = new SortedDictionary<string,object>();
dic.Add("appid", appid);
dic.Add("out_batch_no", partnerTradeNo);
dic.Add("batch_name",DateTime.Now.ToString("D")+"提现记录");
dic.Add("batch_remark", DateTime.Now.ToString("D") + "提现记录");
dic.Add("total_amount",totalFee);
dic.Add("total_num", 1);
List<object> list = new List<object>();
SortedDictionary<string, object> dic1 = new SortedDictionary<string, object>();
dic1.Add("out_detail_no", partnerTradeNo);
dic1.Add("transfer_amount",totalFee);
dic1.Add("transfer_remark", "提现记录");
dic1.Add("openid", openID);
list.Add(dic1);
dic.Add("transfer_detail_list",list);
var url = "https://api.mch.weixin.qq.com/v3/transfer/batches";
string transactionsResponse = WxV3PostJson(url, Newtonsoft.Json.JsonConvert.SerializeObject(dic), mchid, serialNo);
//Log.Info("商户转账到零钱返回:" , transactionsResponse);
return transactionsResponse; ;
}
获取返回结果
public static string WxV3PostJson(string url, string postData, string mchId, string serialNo)
{
Log.Info("发起开始申请商户转账到零钱请求", "发起请求");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36";
request.Accept = "application/json";
//Log.Info("发起开始申请商户转账到零钱请求", "发起请求1");
string Authorization = GetAuthorization(url, "POST", postData, mchId, serialNo);
request.Headers.Add("Authorization", Authorization);
//Log.Info("返回申请商户转账到零钱结果", 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头的授权信息
protected static string GetAuthorization(string url, string method, string jsonParame, string mchId, 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);
//Log.Info("请求message:", message);
//string signTxt = Sign(message, privateKey);
string signTxt = Sign(message);
Log.Info("返回签名:", signTxt);
//Authorization和格式
string authorzationTxt = string.Format("WECHATPAY2-SHA256-RSA2048 mchid=\"{0}\",nonce_str=\"{1}\",timestamp=\"{2}\",serial_no=\"{3}\",signature=\"{4}\"",
mchId,
nonce,
timestamp,
serialNo,
signTxt
);
return authorzationTxt;
}
获取签名,官网给出的签名,记得加上static
protected string Sign(string message)
{
// NOTE: 私钥不包括私钥文件起始的-----BEGIN PRIVATE KEY-----
// 亦不包括结尾的-----END PRIVATE KEY-----
string privateKey = "{你的私钥}";
byte[] keyData = Convert.FromBase64String(privateKey);
var rsa = RSA.Create();
rsa.ImportPkcs8PrivateKey(keyData, out _);
byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
}
如果有疑问,欢迎咨询,创作不易,最后一键三联哦