Enterprise wechat - change from payment to employee

Keywords: C# encoding xml SQL network

This content is based on the independent "enterprise wechat";

Enterprise wechat has an independent management background, which is different from the general service number and subscription number background;

Enterprise wechat involves employees, so the payment here is from payment to employee change;

Official API documentation:

https://work.weixin.qq.com/api/doc#90000/90135/90278

 

The specific steps are as follows:

1: get access_token first

Code:

 1  protected void Button1_Click(object sender, EventArgs e)
 2     {
 3         //Enterprise WeChat ID(Replace with your own)
 4         var corpid = "wx88888888";
 5 
 6         //Enterprise wechat payment secret key(Replace with your own)
 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: exchange of userid and openid

Code:

    protected void Button2_Click(object sender, EventArgs e)
    {
        //Acquired after authorization access_token(Replace with your own)
        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: enterprise wechat signature algorithm

The payment api fixes the following fields to participate in signature:
amount / / the money paid is converted into unit (min)
appid / / enterprise wechat ID
desc / / payment description
MCH? ID / / the merchant number of wechat payment
Nonce? STR / / random string
Openid / / employee openid
Partner? Trade? No / / order number
WW? MSG? Type / / payment message type

 

Code:

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;
        string payForWeiXinOld = string.Empty;

        foreach (string temp in signList)
        {
            signOld += temp + "&";
        }
        signOld = signOld.Substring(0, signOld.Length - 1);

        //Splicing secret
        signOld += "&secret=" + Secret;

        //obtain workwx_sign
        string get_workwx_sign = Encrypt(signOld).ToUpper();

 

MD5 encryption method:

 /// <summary>
    /// Md5 encryption
    /// </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: wechat payment signature algorithm

Signature field: all fields except sign field participate in signature (including enterprise wechat signature field workwx? Sign participate in signature together).

 

SortedDictionary<string, string> dic1 = new SortedDictionary<string, string>();

        dic1.Add("appid", APPID);
        dic1.Add("mch_id", PARTNER);
        //dic.Add("device_info", "013467007045711");//May be empty
        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);//Commodity Description
        dic1.Add("spbill_create_ip", "127.0.0.1"); //Change to the public network deployed by your own code IP
        dic1.Add("workwx_sign", get_workwx_sign);
        dic1.Add("ww_msg_type", "NORMAL_MSG");
        dic1.Add("act_name", title);

        //Get payment signature
        string get_sign = BuildRequest(dic1, PARTNER_KEY);//PARTNER_KEY It's in wechat payment merchant number API secret key
The BuildRequest method includes:
1: parameter filtering
2: sort the parameter name ASCII code from small to large (dictionary order)
3: concatenate into string
4: splicing payment key
5: MD5 encryption
 public static string BuildRequest(SortedDictionary<string, string> sParaTemp, string key)
    {
        //Get filtered array
        Dictionary<string, string> dicPara = new Dictionary<string, string>();
        dicPara = FilterPara(sParaTemp);

        //Combination parameter array
        string prestr = CreateLinkString(dicPara);

        //Splicing payment key
        string stringSignTemp = prestr + "&key=" + key;

        //Vincent._Log.SaveMessage("Parameters for signature generation:" + stringSignTemp);
        Log.DBLog("Parameters for signature generation:" + stringSignTemp);

        //Get encrypted results
        string myMd5Str = GetMD5(stringSignTemp.Trim());

        //Returns the encrypted string converted to uppercase
        return myMd5Str.ToUpper();
    }

    /// <summary>
    /// Remove null values and signature parameters from the array and use letters a reach z Order of
    /// </summary>
    /// <param name="dicArrayPre">Parameter group before filtering</param>
    /// <returns>Filtered parameter group</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;
    }

    //Combination parameter array
    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();
    }

    //encryption
    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: payment to employees

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 method: it involves the certification of wechat payment merchant number.
First: the certificate needs to be placed on the server
/// <summary>
    /// post WeChat request
    /// </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);
        // Preparation request...  
        try
        {

            //CerPath Certificate path
            string certPath = string.Format(@"D:\test\ssl\cert\apiclient_cert.p12");

            //Certificate password(Initial merchant number)
            string password = "88888888";

            X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certPath, password, X509KeyStorageFlags.MachineKeySet);

            // Setting parameters  
            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();
            //Send request and get corresponding response data  
            response = request.GetResponse() as HttpWebResponse;
            //Until request.GetResponse()The program starts sending to the target web page Post request  
            instream = response.GetResponseStream();
            sr = new StreamReader(instream, encoding);
            //Return to results page( html)Code  
            string content = sr.ReadToEnd();
            string err = string.Empty;
            return content;

        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

 

Finally, because the development and debugging of wechat payment is not convenient, the Log method in txt mode is provided

    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();
            }
        }
    }

Posted by quiksilver on Thu, 14 Nov 2019 09:04:34 -0800