欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

企业微信-付款到员工零钱

程序员文章站 2022-07-10 23:49:18
本次内容是基于独立的“企业微信”而言的; 企业微信有独立的管理后台,和一般的服务号,订阅号后台不同; 企业微信涉及员工,所以这里的支付是付款到员工零钱; 官方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();
            }
        }
    }