本次内容是基于独立的“企业微信”而言的;
企业微信有独立的管理后台,和一般的服务号,订阅号后台不同;
企业微信涉及员工,所以这里的支付是付款到员工零钱;
官方API文档:
https://work.weixin.qq.com/api/doc#90000/90135/90278
下面具体步骤:
1:先获取access_token
代码:
1 protected void Button1_Click(object sender, EventArgs e) 2 { 3 //企业微信ID(替换成自己的) 4 var corpid = "wx88888888"; 5 6 //企业微信支付秘钥(替换成自己的) 7 var corpsecret = "88888888"; 8 9 var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", corpid, corpsecret); 10 11 var msg = HttpGet(url); 12 13 Log.DBLog(msg); 14 15 }
2:userid与openid互换
代码:
protected void Button2_Click(object sender, EventArgs e) { //授权后获取的access_token(替换成自己的) var token = "88888888"; var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token={0}", token); var msg = HttpPost(url, "{\"userid\": \"chenhaibo\"}"); Log.DBLog(msg); }
3:企业微信签名算法
付款api固定如下几个字段参与签名:
amount //支付的钱转成单位(分)
appid //企业微信ID
desc //付款说明
mch_id //微信支付的商户号
nonce_str //随机字符串
openid //员工openid
partner_trade_no //订单号
ww_msg_type //付款消息类型
代码:
string[] signTemp = { "amount=" + total_fee, "appid=" + APPID, "desc=" + title, "mch_id=" + PARTNER, "nonce_str=" + wx_nonceStr, "openid=" + toOpenid, "partner_trade_no=" + Bill_No, "ww_msg_type=" + "NORMAL_MSG" }; List<string> signList = signTemp.ToList(); signList.Sort(); string signOld = string.Empty; foreach (string temp in signList) { signOld += temp + "&"; } signOld = signOld.Substring(0, signOld.Length - 1); //拼接secret signOld += "&secret=" + Secret; //得到workwx_sign string get_workwx_sign = Encrypt(signOld).ToUpper();
MD5加密的方法:
/// <summary> /// Md5加密 /// </summary> /// <param name="s"></param> /// <returns></returns> public static String Encrypt(String s) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(s); bytes = md5.ComputeHash(bytes); md5.Clear(); string ret = ""; for (int i = 0; i < bytes.Length; i++) { ret += Convert.ToString(bytes[i], 16).PadLeft(2, ‘0‘); } return ret.PadLeft(32, ‘0‘); }
4:微信支付签名算法
签名字段:除sign字段外所有字段都参与签名(包括企业微信签名字段workwx_sign一起参与签名)。
SortedDictionary<string, string> dic1 = new SortedDictionary<string, string>(); dic1.Add("appid", APPID); dic1.Add("mch_id", PARTNER); //dic.Add("device_info", "013467007045711");//可为空 dic1.Add("nonce_str", wx_nonceStr); dic1.Add("partner_trade_no", Bill_No); dic1.Add("openid", toOpenid); dic1.Add("check_name", "NO_CHECK"); dic1.Add("amount", total_fee); dic1.Add("desc", title);//商品描述 dic1.Add("spbill_create_ip", "127.0.0.1"); //换成你自己的代码部署的公网IP dic1.Add("workwx_sign", get_workwx_sign); dic1.Add("ww_msg_type", "NORMAL_MSG"); dic1.Add("act_name", title); //得到支付签名 string get_sign = BuildRequest(dic1, PARTNER_KEY);//PARTNER_KEY是微信支付商户号里面的API密钥
BuildRequest方法包含:
1:参数过滤
2:参数名ASCII码从小到大排序(字典序)
3:拼接成字符串
4:拼接支付密钥
5:MD5加密
public static string BuildRequest(SortedDictionary<string, string> sParaTemp, string key) { //获取过滤后的数组 Dictionary<string, string> dicPara = new Dictionary<string, string>(); dicPara = FilterPara(sParaTemp); //组合参数数组 string prestr = CreateLinkString(dicPara); //拼接支付密钥 string stringSignTemp = prestr + "&key=" + key; //Vincent._Log.SaveMessage("生成签名的参数:" + stringSignTemp); Log.DBLog("生成签名的参数:" + stringSignTemp); //获得加密结果 string myMd5Str = GetMD5(stringSignTemp.Trim()); //返回转换为大写的加密串 return myMd5Str.ToUpper(); } /// <summary> /// 除去数组中的空值和签名参数并以字母a到z的顺序排序 /// </summary> /// <param name="dicArrayPre">过滤前的参数组</param> /// <returns>过滤后的参数组</returns> public static Dictionary<string, string> FilterPara(SortedDictionary<string, string> dicArrayPre) { Dictionary<string, string> dicArray = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> temp in dicArrayPre) { if (temp.Key != "sign" && !string.IsNullOrEmpty(temp.Value)) { dicArray.Add(temp.Key, temp.Value); } } return dicArray; } //组合参数数组 public static string CreateLinkString(Dictionary<string, string> dicArray) { StringBuilder prestr = new StringBuilder(); foreach (KeyValuePair<string, string> temp in dicArray) { prestr.Append(temp.Key + "=" + temp.Value + "&"); } int nLen = prestr.Length; prestr.Remove(nLen - 1, 1); return prestr.ToString(); } //加密 public static string GetMD5(string pwd) { MD5 md5Hasher = MD5.Create(); byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(pwd)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); }
5:向员工付款
string _req_data = "<xml>"; _req_data += "<appid>" + APPID + "</appid>"; _req_data += "<mch_id>" + PARTNER + "</mch_id>"; _req_data += "<nonce_str>" + wx_nonceStr + "</nonce_str>"; _req_data += "<sign>" + get_sign + "</sign>"; _req_data += "<partner_trade_no>" + Bill_No + "</partner_trade_no>"; _req_data += "<openid>" + toOpenid + "</openid>"; _req_data += "<check_name>NO_CHECK</check_name>"; _req_data += "<amount>" + total_fee + "</amount>"; _req_data += "<desc>" + title + "</desc>"; _req_data += "<spbill_create_ip>101.132.79.228</spbill_create_ip>"; _req_data += "<workwx_sign>" + get_workwx_sign + "</workwx_sign>"; _req_data += "<ww_msg_type>" + "NORMAL_MSG" + "</ww_msg_type>"; _req_data += "<act_name>" + title + "</act_name>"; _req_data += "</xml>"; var result = PostPage(url, _req_data.Trim());
PostPage方法:涉及需要认证微信支付商户号中的证书。
首先:证书需要放到服务器上
/// <summary> /// post微信请求 /// </summary> /// <param name="posturl"></param> /// <param name="postData"></param> /// <returns></returns> public static string PostPage(string posturl, string postData) { Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); // 准备请求... try { //CerPath证书路径 string certPath = string.Format(@"D:\test\ssl\cert\apiclient_cert.p12"); //证书密码(初始为商户号) string password = "88888888"; X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certPath, password, X509KeyStorageFlags.MachineKeySet); // 设置参数 request = WebRequest.Create(posturl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "text/xml"; request.ContentLength = data.Length; request.ClientCertificates.Add(cert); outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //发送请求并获取相应回应数据 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); string err = string.Empty; return content; } catch (Exception ex) { return ex.Message; } }
最后,因为微信支付开发调试不方便,所以提供txt方式的Log方法
public class Log { public static void DBLog(string strMemo) { LogBase("Error.txt", "\r\n" + DateTime.Now.ToString() + " " + strMemo); } public static void DBLog(string sql, string strMemo) { LogBase("Error.txt", "\r\n" + DateTime.Now.ToString() + " " + strMemo + "\r\nSQL:" + sql); } public static void WriteLog(string strMemo) { LogBase("Log.txt", strMemo); } public static void LogBase(string fileName, string str) { string filename = "D:/blwxtest/" + fileName; if (!Directory.Exists("D:/blwxtest/")) Directory.CreateDirectory("D:/blwxtest/"); StreamWriter sr = null; try { if (!File.Exists(filename)) { sr = File.CreateText(filename); } else { sr = File.AppendText(filename); } sr.WriteLine(str); } catch { } finally { if (sr != null) sr.Close(); } } }