微信公众号开发:商户如何给用户发红包实例讲解

红包功能简单介绍:

1、商户调用接口时,通过指定发送对象以及发送金额的方式发放红包,这样的方式,允许商户灵活的应用于各种各样丰富的活动场景

2、领取到红包后,用户的资金直接进入微信零钱,避免繁复的领奖流程源码网点我wcqh.cn,带给用户微信支付原生的流畅体验

现金红包官网文档地址:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_1源码网点我wcqh.cn

调用现金红包接口需要使用到证书,请前往商户平台下载证书

官网有关详细证书的介绍:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?源码网点我wcqh.cnchapter=4_3

因为发送现金红包是从商户平台余额扣款,所以商户平台的账户余额必须有充足的余额

下面是调用红包接口详细代码:1、签名的MD5加密类:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17源码网点我wcqh.cn

18

19

20

21

22

23

24

25

26

27

28

/// <summary>/// MD5UtilHelper 的摘要说明。/// </summary>public class MD5UtilHelper

{源码网点我wcqh.cn    public MD5UtilHelper()

{        //

// TODO: 在此处添加构造函数逻辑

//

}    /// <summary>

/// 获取大写的MD5签名结果

/// </s源码网点我wcqh.cnummary>

/// <param name=”encypStr”></param>

/// <param name=”charset”></param>

/// <returns></returns>

p源码网点我wcqh.cnublic static string GetMD5(string encypStr, string charset)

{        string retStr;

MD5CryptoServicePr源码网点我wcqh.cnovider m5 = new MD5CryptoServiceProvider();        //创建md5对象

byte[] inputBye;        byte[] outputBye源码网点我wcqh.cn;        //使用GB2312编码方式把字符串转化为字节数组.

try

{

inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr);

}源码网点我wcqh.cn        catch (Exception ex)

{

inputBye = Encoding.GetEncoding(“GB2312”).GetBytes(encypStr);

}

outputBye源码网点我wcqh.cn = m5.ComputeHash(inputBye);

retStr = System.BitConverter.ToString(outputBye);

retStr = retStr.Replace源码网点我wcqh.cn(“-“, “”).ToUpper();        return retStr;

}

}

登录后复制

2、处理参数的类:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

2源码网点我wcqh.cn6

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

7源码网点我wcqh.cn6

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

public class RequestHandler

{        publi源码网点我wcqh.cnc RequestHandler(HttpContext httpContext)

{

Parameters = new Hashtable();            this.HttpContext 源码网点我wcqh.cn= httpContext ?? HttpContext.Current;

}        /// <summary>

/// 密钥

/// </summary>

private string Key;  源码网点我wcqh.cn      protected HttpContext HttpContext;        /// <summary>

/// 请求的参数

/// </summary>

protected Hashta源码网点我wcqh.cnble Parameters;        /// <summary>

/// debug信息

/// </summary>

private string DebugInfo;        /// <s源码网点我wcqh.cnummary>

/// 初始化函数

/// </summary>

public virtual void Init()

{

}        /// <summary>

/// 获取debug信息

/// </su源码网点我wcqh.cnmmary>

/// <returns></returns>

public String GetDebugInfo()

{            return DebugInfo;

}        /// 源码网点我wcqh.cn<summary>

/// 获取密钥

/// </summary>

/// <returns></returns>

public string GetKey()

{            return Key;源码网点我wcqh.cn

}        /// <summary>

/// 设置密钥

/// </summary>

/// <param name=”key”></param>

public void SetKey(string 源码网点我wcqh.cnkey)

{            this.Key = key;

}        /// <summary>

/// 设置参数值

/// </summary>

/// <param name=”parame源码网点我wcqh.cnter”></param>

/// <param name=”parameterValue”></param>

public void SetParameter(string parameter, str源码网点我wcqh.cning parameterValue)

{            if (parameter != null && parameter != “”)

{                if (Parame源码网点我wcqh.cnters.Contains(parameter))

{

Parameters.Remove(parameter);

}

Parameters.Add(parameter, parameterValue);

}

}源码网点我wcqh.cn        /// <summary>

/// 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名

/// </summary>

/// <param name=”key”>参数名<源码网点我wcqh.cn/param>

/// <param name=”value”>参数值</param>

/// key和value通常用于填充最后一组参数

/// <returns></returns>

public vir源码网点我wcqh.cntual string CreateMd5Sign(string key, string value)

{

StringBuilder sb = new StringBuilder();

ArrayList源码网点我wcqh.cn akeys = new ArrayList(Parameters.Keys);

akeys.Sort();            foreach (string k in akeys)

{       源码网点我wcqh.cn         string v = (string)Parameters[k];                if (null != v && “”.CompareTo(v) != 0

&& “s源码网点我wcqh.cnign”.CompareTo(k) != 0 && “key”.CompareTo(k) != 0)

{

sb.Append(k + “=” + v + “&”);

}

}

sb.Append(key + “=源码网点我wcqh.cn” + value);            string sign = MD5UtilHelper.GetMD5(sb.ToString(), GetCharset()).ToUpper();   源码网点我wcqh.cn         return sign;

}        /// <summary>

/// 输出XML

/// </summary>

/// <returns></returns>

public stri源码网点我wcqh.cnng ParseXML()

{

StringBuilder sb = new StringBuilder();

sb.Append(“<xml>”);            foreach (string 源码网点我wcqh.cnk in Parameters.Keys)

{                string v = (string)Parameters[k];                if (Regex.IsM源码网点我wcqh.cnatch(v, @”^[0-9.]$”))

{

sb.Append(“<” + k + “>” + v + “</” + k + “>”);

}                else

{

sb.Append(源码网点我wcqh.cn“<” + k + “><![CDATA[” + v + “]]></” + k + “>”);

}

}

sb.Append(“</xml>”);            return sb.ToString源码网点我wcqh.cn();

}        /// <summary>

/// 设置debug信息

/// </summary>

/// <param name=”debugInfo”></param>

public void 源码网点我wcqh.cnSetDebugInfo(String debugInfo)

{            this.DebugInfo = debugInfo;

}        public Hashtable GetA源码网点我wcqh.cnllParameters()

{            return this.Parameters;

}        protected virtual string GetCharset()

{   源码网点我wcqh.cn         return this.HttpContext.Request.ContentEncoding.BodyName;

}

}

登录后复制

3、调用现金红包处理类:

1

2

3

4

5

6

7

8

9

10

11

12源码网点我wcqh.cn

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

/// <summary>

/// 企业号微信支付接口源码网点我wcqh.cn

/// </summary>

public static class TenPay

{     #region 企业向用户发红包

/// <summary>

/// 用于企业向微信用户个人发红包

/// 目前支源码网点我wcqh.cn持向指定微信用户的openid个人发红包

/// </summary>

/// <param name=”certPassword”>apiclient_cert.p12证书密码即商户号</param>

/源码网点我wcqh.cn// <param name=”data”>微信支付需要post的xml数据</param>

/// <param name=”certPath”>apiclient_cert.p12的证书物理位置(例源码网点我wcqh.cn如:E:\projects\文档\微信商户平台证书\商户平台API证书</param>

/// <param name=”timeOut”></param>

/// <returns></returns>源码网点我wcqh.cn

public static string Sendredpack(string data, string certPassword,string certPath, int timeOut = Con源码网点我wcqh.cnfig.TIME_OUT)

{         var urlFormat = “https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack”源码网点我wcqh.cn;         string cert = certPath;

ServicePointManager.ServerCertificateValidationCallback = new Remot源码网点我wcqh.cneCertificateValidationCallback(CheckValidationResult);

X509Certificate2 cer = new X509Certificate2(ce源码网点我wcqh.cnrt, certPassword, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);         va源码网点我wcqh.cnr formDataBytes = data == null ? new byte[0] : Encoding.UTF8.GetBytes(data);

MemoryStream ms = new Me源码网点我wcqh.cnmoryStream();

ms.Write(formDataBytes, 0, formDataBytes.Length);

ms.Seek(0, SeekOrigin.Begin);//设置指针读取位源码网点我wcqh.cn

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlFormat);

request.ClientCertificates.Ad源码网点我wcqh.cnd(cer);

request.Method = “POST”;

request.Timeout = timeOut;

request.UserAgent = “Mozilla/5.0 (Windows N源码网点我wcqh.cnT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36″;         #re源码网点我wcqh.cngion 输入二进制流

if (ms != null)

{

ms.Position = 0;             //直接写入流

Stream requestStream = request.GetReq源码网点我wcqh.cnuestStream();             byte[] buffer = new byte[1024];             int bytesRead = 0;            源码网点我wcqh.cn while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) != 0)

{

requestStream.Write(buffer, 0, bytesRe源码网点我wcqh.cnad);

}

ms.Close();//关闭文件访问

}         #endregion

HttpWebResponse response = (HttpWebResponse)request.GetR源码网点我wcqh.cnesponse();         using (Stream responseStream = response.GetResponseStream())

{             using (源码网点我wcqh.cnStreamReader myStreamReader = new StreamReader(responseStream, Encoding.GetEncoding(“utf-8”)))

{     源码网点我wcqh.cn            string retString = myStreamReader.ReadToEnd();                 return retString;

}

}

}     源码网点我wcqh.cnprivate static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chai源码网点我wcqh.cnn, SslPolicyErrors errors)

{         if (errors == SslPolicyErrors.None)             return true;    源码网点我wcqh.cn     return false;

}     #endregion

}

登录后复制

4、调用现金红包接口

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

3源码网点我wcqh.cn0

31

32

33

34

35

36

37

38

39

#region 发送红包bool fals = false;   //记录发送红包是否成功string xmlResult = null;  //现金红包接口返回源码网点我wcqh.cn的xmlstring certPath = null;  //证书在服务器的物理位置string data = null;  //调用现金红包接口需要的数据try

{

//创建支付应答对象

RequestH源码网点我wcqh.cnandler packageReqHandler = new RequestHandler(null);

//初始化

packageReqHandler.Init();

string nonceStr = 源码网点我wcqh.cnTenPayV3Util.GetNoncestr();  //时间戳

//设置package订单参数

packageReqHandler.SetParameter(“nonce_str”, nonceSt源码网点我wcqh.cnr);    //随机字符串,不长于32位

packageReqHandler.SetParameter(“mch_billno”, System.Configuration.Configuration源码网点我wcqh.cnManager.AppSettings[“TenPayV3_MchId”] + model.JournalNumber);//商户订单号(每个订单号必须唯一)组成:mch_id+yyyymmdd+10源码网点我wcqh.cn位一天内不能重复的数字。接口根据商户订单号支持重入,如出现超时可再调用。

packageReqHandler.SetParameter(“mch_id”, System.Configuration.Co源码网点我wcqh.cnnfigurationManager.AppSettings[“TenPayV3_MchId”]);  //微信支付分配的商户号

packageReqHandler.SetParameter(“wxap源码网点我wcqh.cnpid”, System.Configuration.ConfigurationManager.AppSettings[“TenPayV3_AppId”]);//微信分配的公众账号ID(企业号corp源码网点我wcqh.cnid即为此appId)。接口传入的所有appid应该为公众号的appid(在mp.weixin.qq.com申请的),不能为APP的appid(在open.weixin.qq.com申请的)。

pack源码网点我wcqh.cnageReqHandler.SetParameter(“send_name”, “测试”);//商户名称

packageReqHandler.SetParameter(“re_openid”, mode源码网点我wcqh.cnl.BankCard);  //用户openid  接受红包的用户用户在wxappid下的openid

packageReqHandler.SetParameter(“total_amount”, Co源码网点我wcqh.cnnvert.ToInt32((decimal)(model.Amount * 100M)).ToString(CultureInfo.InvariantCulture));  //付款金额 单位分

pa源码网点我wcqh.cnckageReqHandler.SetParameter(“total_num”, “1”);  //红包发放总人数

packageReqHandler.SetParameter(“wishing”, 源码网点我wcqh.cn“测试红包”);  //红包祝福语

packageReqHandler.SetParameter(“client_ip”, HttpContext.Current.Request.UserHostAdd源码网点我wcqh.cnress);//Ip地址

packageReqHandler.SetParameter(“act_name”, “测试红包”);//活动名称

packageReqHandler.SetParameter(源码网点我wcqh.cn“remark”, “测试红包”);     //备注

string sign = packageReqHandler.CreateMd5Sign(“key”, System.Configuration源码网点我wcqh.cn.ConfigurationManager.AppSettings[“TenPayV3_Key”]);

packageReqHandler.SetParameter(“sign”, sign);    源码网点我wcqh.cn                    //签名

data = packageReqHandler.ParseXML();

certPath = Server.MapPath(“~/”) + System源码网点我wcqh.cn.Configuration.ConfigurationManager.AppSettings[“certPath”];

xmlResult = Sendredpack(data, System.Con源码网点我wcqh.cnfiguration.ConfigurationManager.AppSettings[“TenPayV3_MchId”],certPath);

var res = XDocument.Parse(xm源码网点我wcqh.cnlResult);

string return_code = res.Element(“xml”).Element(“return_code”).Value;

if (“SUCCESS”.Equals(r源码网点我wcqh.cneturn_code))

{

string result_code = res.Element(“xml”).Element(“result_code”).Value;

if (“SUCCESS”.Equa源码网点我wcqh.cnls(result_code))

{

fals = true;

}

}

}

catch (Exception exception)

{

}#endregion

登录后复制

注意:证书所在文件夹权限,IIS必须有权限对该文源码网点我wcqh.cn件夹操作的权限。

相关文章:

PHP微信公众号自动发送红包API,php公众红包api

微信公众号红包接口开发PHP开发 CA证书出错,请登陆微信支付商户平台下载证书

相关视频:

微信公众号前段-php微信接口源码网点我wcqh.cn开发实战项目视频教程 聊天机器人

以上就是微信公众号开发:商户如何给用户发红包实例讲解的详细内容,更多请关注php中文网其它相关文章!

© 版权声明
THE END
喜欢就支持一下吧
点赞757 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容