.Net Core微信服务商二次进件的开发
程序员文章站
2022-03-02 11:36:18
最近商城进行微信服务商二次进件的开发,大致有几个点一,服务商签名二,服务商证书获取三,图片上传四,敏感信息加密五,查询进件状态除此之外,就是进件信息的拼装电商二级商户进件申请单-状态流转一 服务商签名...
最近商城进行微信服务商二次进件的开发,大致有几个点
一,服务商签名
二,服务商证书获取
三,图片上传
四,敏感信息加密
五,查询进件状态
除此之外,就是进件信息的拼装
电商二级商户进件申请单-状态流转
一 服务商签名
首先准备必须的配置:商户号、证书、秘钥、小程序appid、appsecret
#region 服务商签名 private string srvpaybuildauthasync(string uri, string body, string method = "post") { var timestamp = datetimeoffset.now.tounixtimeseconds(); string nonce = guid.newguid().tostring(); string message = $"{method}\n{uri}\n{timestamp}\n{nonce}\n{body}\n"; string signature = srvsign(message); return $"mchid=\"{_wxcfg.srvpaymerchantid}\",nonce_str=\"{nonce}\",timestamp=\"{timestamp}\",serial_no=\"{_wxcfg.srvpaycertno}\",signature=\"{signature}\""; } private string srvsign(string message) { var bytes = utils.readbytesifexist(_wxcfg.srvpaycertfile); if (bytes is null) { return ""; } x509certificate2 cert = new(bytes, _wxcfg.srvpaymerchantid); rsa rsa = cert.getrsaprivatekey(); var signdata = rsa.signdata(encoding.utf8.getbytes(message), hashalgorithmname.sha256, rsasignaturepadding.pkcs1); return convert.tobase64string(signdata); }
二 获取证书
分为:第一步获取证书,第二步解密证书
1 获取证书
https://api.mch.weixin.qq.com/v3/certificates
#region 获取平台证书 public async task<certificatesoutmodel> getsrvcert() { string uri = "/v3/certificates"; var auth = srvpaybuildauthasync(uri, "", "get"); var header = new dictionary<string, string> { { "authorization",$"wechatpay2-sha256-rsa2048 {auth}"}, { "accept","*/*" }, { "accept-encoding","gzip,deflate,brn" }, { "user-agent", "mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/90.0.4430.85 safari/537.36 edg/90.0.818.46" }, }; return await geturlasync<certificatesoutmodel>(uri, header); } #endregion
使用的实体:certificatesoutmodel
public sealed class certificatesoutmodel : iwxresponse { [jsonpropertyname("data")] public ienumerable<certificates> data { get; set; } public string code { get; set; } public string message { get; set; } } public class certificates { [jsonpropertyname("serial_no")] public string serialno { get; set; } [jsonpropertyname("effective_time")] public string effectivetime { get; set; } [jsonpropertyname("expire_time")] public string expiretime { get; set; } [jsonpropertyname("encrypt_certificate")] public encryptcertificate encryptcertificate { get; set; } }
请求方法:geturlasync
protected async task<t> geturlasync<t>(string url, dictionary<string, string> headers = null) { httpresponsemessage res = null; try { if (headers != null && headers.count > 0) { foreach (var header in headers) { _client.defaultrequestheaders.tryaddwithoutvalidation(header.key, header.value); } } res = await _client.getasync(url); res.ensuresuccessstatuscode(); var result = await res.content.readasstringasync(); if (result == null) { return default; } return result.tojson<t>(); } catch { var result = await res.content.readasstringasync(); if (result == null) { return default; } return result.tojson<t>(); } }
解密方法
//获取证书 var cert = await _wxclient.getsrvcert(); var certificatemodel = cert.data.firstordefault(); if (!cert.data.any()) { return new mkresult<v3wxpayapplymentidoutmodel>(code: 400, msg: "未获取到平台证书"); } if (!string.isnullorempty(applyment.body.serialno)) { certificatemodel = cert.data.singleordefault(s => s.serialno == applyment.body.serialno); } certificatemodel.encryptcertificate.ciphertext = aesutility.aesgcmdecrypt( _wxcfg.srvapiv3key, certificatemodel.encryptcertificate.associateddata, certificatemodel.encryptcertificate.nonce, certificatemodel.encryptcertificate.ciphertext );
三,上传图片
因为我的图片保存在oss,首先要网络图片bytes,对图片进行sha256,方法在后面
protected async task<byte[]> geturlbytesasync(string url, dictionary<string, string> headers = null) { try { if (headers != null && headers.count > 0) { foreach (var header in headers) { _client.defaultrequestheaders.tryaddwithoutvalidation(header.key, header.value); } } var res = await _client.getasync(url); res.ensuresuccessstatuscode(); return await res.content.readasbytearrayasync(); } catch { return default; } }
然后上传图片
/// <summary> /// 上传图片 /// </summary> /// <param name="url"></param> /// <returns></returns> public async task<mkresult<v3wxpayfileuploadoutmodel>> uploadfile(string url) { string filecontenttype; string filetype; if (url!.contains(".bmp", stringcomparison.ordinalignorecase)) { filecontenttype = "image/bmp"; filetype = ".bmp"; } else if (url!.contains(".jpg", stringcomparison.ordinalignorecase)) { filecontenttype = "image/jpeg"; filetype = ".jpg"; } else if (url!.contains(".jpeg", stringcomparison.ordinalignorecase)) { filecontenttype = "image/jpeg"; filetype = ".jpeg"; } else { filecontenttype = "image/png"; filetype = ".png"; } uploadmerchantmediaimagerequest meta = new(); var filebytes = await geturlbytesasync(url);//获取网络图片bytes if ((filebytes?.length ?? 0) == 0) { return new mkresult<v3wxpayfileuploadoutmodel>(code: 400, msg: "转换图片失败"); } meta.filehash = gethash(filebytes); meta.filename = guid.newguid().tostring("n").tolower() + filetype; string boundary = "--boundary--" + datetimeoffset.now.ticks.tostring("x"); using var filecontent = new bytearraycontent(filebytes); using var metacontent = new stringcontent(meta.tojson(), encoding.utf8, "application/json"); using var httpcontent = new multipartformdatacontent(boundary); httpcontent.add(metacontent, "\"meta\"");//meta 必须要加双引号 httpcontent.add(filecontent, "\"file\"", "\"" + meta.filename + "\"");//必须要加双引号 httpcontent.headers.contenttype = mediatypeheadervalue.parse("multipart/form-data; boundary=" + boundary);// boundary不能加引号 metacontent.headers.contenttype = mediatypeheadervalue.parse("application/json"); filecontent.headers.contenttype = mediatypeheadervalue.parse(filecontenttype); var uri = $"/v3/merchant/media/upload"; var res = await v3uploadfile<v3wxpayfileuploadoutmodel>(uri, meta.tojson(), httpcontent); return new mkresult<v3wxpayfileuploadoutmodel>(res, 1); }
private async task<t> v3uploadfile<t>(string uri, string meta, multipartformdatacontent content) { var auth = srvpaybuildauthasync(uri, meta); var header = new dictionary<string, string> { { "authorization",$"wechatpay2-sha256-rsa2048 {auth}"}, { "accept","*/*" }, { "accept-encoding","gzip,deflate,brn" }, { "user-agent", "mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/90.0.4430.85 safari/537.36 edg/90.0.818.46" }, }; return await v3postfileasync<t>(uri, header, content); }
protected async task<t> v3postfileasync<t>(string url, dictionary<string, string> headers, multipartformdatacontent content) { httpresponsemessage res = null; try { if (headers != null && headers.count > 0) { foreach (var header in headers) { _client.defaultrequestheaders.tryaddwithoutvalidation(header.key, header.value); } } res = await _client.postasync(url, content); res.ensuresuccessstatuscode(); var result = await res.content.readasstringasync(); if (result == null) { return default; } return result.tojson<t>(); } catch { var result = await res.content.readasstringasync(); if (result == null) { return default; } return result.tojson<t>(); } finally { if (content != null) { content.dispose(); } } }
#region 二进制内容进行sha256 private static string gethash(byte[] bytes) { if (bytes == null) throw new argumentnullexception(nameof(bytes)); using sha256 sha = sha256.create(); byte[] hashbytes = sha.computehash(bytes); return bitconverter.tostring(hashbytes).replace("-", "").tolower(); }
四,敏感信息加密
使用获取到的证书certificatemodel,进行加密
public static class rsautility { public static string rsaencrypt(string text, certificates certificatemodel) { var bytes = encoding.utf8.getbytes(certificatemodel.encryptcertificate.ciphertext); using var x509 = new x509certificate2(bytes); var rsaparam = x509.getrsapublickey().exportparameters(false); var rsa = new rsacryptoserviceprovider(); rsa.importparameters(rsaparam); var buff = rsa.encrypt(encoding.utf8.getbytes(text), true); return convert.tobase64string(buff); } }
五,查询进件状态
直接使用进件返回的id,调用接口查询就ok了
到此这篇关于.net core微信服务商二次进件的文章就介绍到这了,更多相关.net core微信服务商内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 高通ais cam.xml配置
下一篇: 前端H5实现调用麦克风,录音功能