本次內容是基於獨立的“企業微信”而言的; 企業微信有獨立的管理後臺,和一般的服務號,訂閱號後臺不同; 企業微信涉及員工,所以這裡的支付是付款到員工零錢; 官方API文檔: https://work.weixin.qq.com/api/doc#90000/90135/90278 下麵具體步驟: 1:先 ...
本次內容是基於獨立的“企業微信”而言的;
企業微信有獨立的管理後臺,和一般的服務號,訂閱號後臺不同;
企業微信涉及員工,所以這裡的支付是付款到員工零錢;
官方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(); } } }