Home > WeChat Applet > WeChat Development > C# development of WeChat portal and application of encapsulation and use of WeChat cash red envelopes

C# development of WeChat portal and application of encapsulation and use of WeChat cash red envelopes

高洛峰
Release: 2017-03-07 09:54:23
Original
2321 people have browsed it

After the last essay, after improving and reconstructing the entire WeChat framework, WeChat payment, corporate payment, cash red envelopes, vouchers and various card coupons have been packaged, and WeChat payment has been included and the shake red envelope part are common parts of official accounts and enterprise accounts. These payment-related interfaces can be called in official accounts and enterprise accounts. After a series of optimization and sorting, these contents will be added one by one. Introducing, hope everyone likes and supports.

1. The concept and use of cash red envelopes

1) Usage scenarios

WeChat Pay cash red envelopes are developed for WeChat Pay merchants. The specific capabilities are as follows:

◆ When merchants call the interface, they issue red envelopes by specifying the sending object and the sending amount. This method allows merchants to flexibly apply it to a variety of rich activity scenarios

◆ Receive After receiving the red envelope, the user's funds are directly transferred to WeChat change, avoiding the complicated award process and giving users the smooth experience of WeChat payment.

2) WeChat red envelope sending rules

Sending frequency rules

◆ The number of red envelopes sent per minute shall not exceed 1,800;

◆ The same merchant number, the maximum number of red envelopes sent per minute The same user sends a red envelope;

Red envelope rules

◆ The amount of a single red envelope is between [1.00 yuan, 200.00 yuan];

◆ The same red envelope can only be sent to one user; (If the above rules do not meet your needs, please send an email to wxhongbao@tencent.com for upgrade instructions)

◆ If the red envelope is not claimed 72 hours after it is issued, it will be processed Refund

3) WeChat red envelope interface calling process

◆Backend API call: communicate with the development team in detail when entering the joint debugging process;

◆ Notify the server: Inform the server of the openID of the user who received the WeChat red envelope, and inform the server of the amount received by the user;

◆ Deduct money from the business account: After the server obtains the information, it will deduct the money from the corresponding business account Get the corresponding amount;

◆ Call failure: The call fails due to non-compliance with the sending rules, insufficient balance of the business account, etc., and feedback to the caller;

◆ Successful sending: public with WeChat red envelope The account sends the corresponding red envelope to the corresponding user;

C#开发微信门户及应用微信现金红包的封装及使用


2. Description of the cash red envelopeAPI interface and The C# package

is used by enterprises to send red envelopes to individual WeChat users. It currently supports issuing red envelopes of specified amounts to the openid of designated WeChat users.

Although cash red envelopes can be issued through the merchant backend of WeChat, we can also use the interface API provided by WeChat to send cash red envelopes.


Interface call request description


Request Url https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack
Is it required? The certificate is (see the merchant certificate for certificate and usage instructions)
Request method POST


Request Parameters


##Field nameFieldRequiredExample valueType Description##Random string Signature Merchant order numberMerchant order number (each order number must be unique) Merchant numberpublic account appidMerchant nameuser openidUsers who accept red envelopesPayment amountTotal number of people to whom red envelopes are issuedThe total number of people given red envelopesRed Packet BlessingsIp addressActivity nameRemarks

Data example:


<xml><xml> 
  <sign><![CDATA[E1EE61A91C8E90F299DE6AE075D60A2D]]></sign>  
  <mch_billno><![CDATA[0010010404201411170000046545]]></mch_billno>  
  <mch_id><![CDATA[888]]></mch_id>  
  <wxappid><![CDATA[wxcbda96de0b165486]]></wxappid>  
  <send_name><![CDATA[send_name]]></send_name>  
  <re_openid><![CDATA[onqOjjmM1tad-3ROpncN-yUfa6uI]]></re_openid>  
  <total_amount><![CDATA[200]]></total_amount>  
  <total_num><![CDATA[1]]></total_num>  
  <wishing><![CDATA[恭喜发财]]></wishing>  
  <client_ip><![CDATA[127.0.0.1]]></client_ip>  
  <act_name><![CDATA[新年红包]]></act_name>  
  <remark><![CDATA[新年红包]]></remark>  
  <nonce_str><![CDATA[50780e0cca98c8c8e814883e5caa672e]]></nonce_str> 
  </xml>
Copy after login

The above is a description of the interface and input parameters, generally In this case, we need to decide how to implement C# code encapsulation based on these. First, we define the interfaces and classes we need, as shown below.

C#开发微信门户及应用微信现金红包的封装及使用

By analyzing the above interface description, we can find that some of the interfaces are fixed conventional parameters, that is, the identity information of general public accounts or enterprise accounts, and some are business parameters, so we separate them separately, which is conducive to our encapsulation and use of the interface. We can obtain those regular parameters through the official account identity. For business information, we can define an entity class to carry out data Just store and exchange.

C#开发微信门户及应用微信现金红包的封装及使用

corresponds to the fixed conventional parameters in the above figure, as shown below in the interface description.

C#开发微信门户及应用微信现金红包的封装及使用

Therefore, we can set and obtain this information from the account. We can configure them in the management background, and then take them out and use them in the code logic.

C#开发微信门户及应用微信现金红包的封装及使用

C#开发微信门户及应用微信现金红包的封装及使用

According to the above introduction, we can define the red packet interface code as follows.

/// <summary>
    /// 微信红包(摇一摇红包)操作API
    /// </summary>
    public interface ILotteryApi
    {              
        /// <summary>
        /// 用于企业向微信用户个人发现金红包。需要商户证书
        /// 目前支持向指定微信用户的openid发放指定金额红包。
        /// </summary>
        /// <returns></returns>
        SendRedPackResult SendRedPack(SendRedPackJson json);
Copy after login

SendRedPackJson is the business parameter we changed. We defined a class to carry information to facilitate the transfer of information through the interface.

/// <summary>
    /// 现金红包和裂变红包的基础信息
    /// </summary>
    public class BaseRedPackJson
    {
        /// <summary>
        /// 接受红包的用户
        /// 用户openid    
        /// </summary>
        public string re_openid { get; set; }

        /// <summary>
        /// 付款金额,单位分
        /// </summary>
        public int total_amount { get; set; }

        /// <summary>
        /// 红包发放总人数
        /// </summary>
        public int total_num { get; set; }

        /// <summary>
        /// 红包祝福语
        /// </summary>
        public string wishing { get; set; }

        /// <summary>
        /// 活动名称
        /// </summary>
        public string act_name { get; set; }

        /// <summary>
        /// 备注信息
        /// </summary>
        public string remark { get; set; }
    }

    /// <summary>
    /// 发送红包的数据信息
    /// </summary>
    public class SendRedPackJson :BaseRedPackJson
    {
        /// <summary>
        /// 调用接口的机器Ip地址
        /// </summary>
        public string client_ip { get; set; }

        public SendRedPackJson()
        {
            this.total_num = 1;//红包发放总人数
        }
    }
Copy after login

According to the definition of the above parameters, we implement the interface of the cash red envelope. The specific code is as follows. The logical content inside is mainly to pass in the regular Parameters and business parameters, then call the interface address to submit data (POST), obtain the returned results and parse them.

/// <summary>
        /// 用于企业向微信用户个人发现金红包。需要商户证书
        /// 目前支持向指定微信用户的openid发放指定金额红包。
        /// </summary>
        /// <returns></returns>
        public SendRedPackResult SendRedPack(SendRedPackJson json)
        {
            CheckAccount();//检查AccountInfo的对象属性值

            //加入常规的参数
            WxPayData data = new WxPayData();
            data.SetValue("wxappid", AccountInfo.UniteAppId);//公众账号appid
            data.SetValue("mch_id", AccountInfo.MchID);//商户号
            data.SetValue("nonce_str", data.GenerateNonceStr());//随机字符串
            data.SetValue("send_name", AccountInfo.Name);//    红包发送者名称
            
            //商户订单号(每个订单号必须唯一) 组成:mch_id+yyyymmdd+10位一天内不能重复的数字。
            //接口根据商户订单号支持重入,如出现超时可再调用。
            data.SetValue("mch_billno", data.GenerateOutTradeNo(AccountInfo.MchID));

            data.SetValue("re_openid", json.re_openid);
            data.SetValue("total_amount", json.total_amount);
            data.SetValue("total_num", json.total_num);
            data.SetValue("wishing", json.wishing);
            data.SetValue("client_ip", json.client_ip);
            data.SetValue("act_name", json.act_name);
            data.SetValue("remark", json.remark);

            data.SetValue("sign", data.MakeSign(AccountInfo.PayAPIKey));//最后生成签名

            var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
            return Helper.GetPayResultWithCert<SendRedPackResult>(data, url, AccountInfo.CertPath, AccountInfo.CertPassword);
        }
Copy after login

The operation of sending red envelopes requires a certificate, so the corresponding certificate needs to be added. The certificate is downloaded from the WeChat merchant platform.

Download the certificate from the [API Security] project in the merchant backend for use in our development environment.

C#开发微信门户及应用微信现金红包的封装及使用

After downloading the certificate, in a Windows environment, we generally need to double-click to install it and enter the required merchant number as the password.

C#开发微信门户及应用微信现金红包的封装及使用

In the code, we can use the certificate class to add

HttpHelper helper = new HttpHelper();

            helper.ClientCertificates = new X509CertificateCollection();
            certPath = Path.Combine(System.Environment.CurrentDirectory, certPath);
            helper.ClientCertificates.Add(new X509Certificate2(certPath, certPassword));
            string response = helper.GetHtml(url, xml, true);
Copy after login

3. Results of using WeChat red envelopes

For example, our calling code in the test example is as follows.

//现金红包
                SendRedPackJson packJson = new SendRedPackJson()
                {
                    act_name = "恭喜发财",
                    client_ip = NetworkUtil.GetIPAddress(),
                    remark = "企业红包",
                    wishing = "企业红包",
                    total_amount = 100,
                    total_num = 1,
                    re_openid = tosendOpenId //发送给用户的OpenID
                };
                var result = hbApi.SendRedPack(packJson);
                var message = string.Format("企业发送红包:{0} {1}", result.Success ? "成功" : "失败", result.Message);
                Console.WriteLine(message);
                Console.WriteLine(result.ToJson());
Copy after login

The hbApi is the structure of the above interface, as shown in the following code.

AccountInfo  accountInfo = new AccountInfo()
    {
       Name = this.SendName,
        AppID = this.AppId,
        AppSecret = this.AppSecret,
        MchID = this.MchID,
        PayAPIKey = this.PayAPIKey,
        CertPath = this.CertPath,
        CertPassword = this.CertPassword,
         PayNotifyUrl = this.PayNotifyUrl
     };
 ILotteryApi hbApi = new LotteryApi(accountInfo);
Copy after login

After successful call, we can see the red envelope information results in the conversation of the official account. The following is the entire process of sending and opening the red envelope.

C#开发微信门户及应用微信现金红包的封装及使用 C#开发微信门户及应用微信现金红包的封装及使用 C#开发微信门户及应用微信现金红包的封装及使用

For more C# development of WeChat portal and application of WeChat cash red envelope packaging and use, please pay attention to the PHP Chinese website for related articles!


nonce_str is 5K8264ILTKCH16CQ2502SI8ZNMTM67VS String(32) Random string, no longer than 32 characters
sign is C380BEC2BFD727A4B6845133519F3AD6 String(32) See signature generation algorithm for details
mch_billno is 10000098201411111234567890 String(28)

Composition: mch_id+yyyymmdd+10 digits cannot be repeated within one day number.

The interface supports re-entry based on the merchant's order number. If a timeout occurs, it can be called again.

mch_id is 10000098 String(32) The merchant number assigned by WeChat payment
wxappid is wx8888888888888888 String(32) The public account ID assigned by WeChat (corporate number corpid is this appId). All appids passed in through the interface should be the appid of the public account (applied at mp.weixin.qq.com), not the appid of the APP (applied at open.weixin.qq.com).
send_name is Tianhong Department Store String(32) Red envelope sender name
re_openid is oxTWIuGaIt6gTKsQRLau2M0yL16E String(32 )

The user’s openid under wxappid

total_amount is 1000 int Payment amount, unit points
total_num is 1 int

total_num=1

wishing Yes Thank you for participating in the lantern riddle guessing activity, and I wish you a happy Lantern Festival! String(128) Red envelope blessings
client_ip is 192.168.0.1 String(15) Machine IP address calling the interface
act_name is Guessing lantern riddles and grabbing red envelope activities String(32) Activity name
remark Yes The more you guess, the more you get, come and grab it! String(256) Remarks
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template