1.首先做微信方面的开发,一定需要详细的阅读微信支付的开发文档。因为里面列举了比如消息的触达规则,接口调用的请求说明,请求的参数,错误返回示例以及成功返回示例,阅读这些,在出错了我们能够快速定位并且解决问题。
https://pay.weixin.qq.com/wiki/doc/api/index.html
2.在开发微信红包之前,你首先肯定得准备好微信商户平台,微信公众号(服务号)(在这里假设你已经全部准备好了)。
3.我这个发送红包是大转盘抽奖,抽到了红包奖品之后,通知后台去发送红包。废话不多说,前端ajax代码:
//前端发送ajax请求,请求后台去发送红包,前后端交互采用的是json格式的数据进行传输。
var redPacketRequestJson = {
"appid":$("#appid").val(),//该公众号的appid的值
"openid":$("#openid").val(),//该用户的openid的值
"redValue":$("#redValue").val()//红包的大小值,单位为分,最低为100分也就是一元
};
$.ajax({
type: "post",
url: "http://localhost/wechat/sendRedPacket",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(redPacketRequestJson),
dataType: "json",
success: function (data) {
if(data.statusCode==100){
console.log("红包发送成功")
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
后台的代码如下:
@ResponseBody
@RequestMapping("/sendRedPacket")
public String sendRedPacket(@RequestBody(required = false) String requestJson, HttpServletRequest request){
try{
logger.info("发送红包的时候,前端传输过来的信息是:"+requestJson);
JSONObject jsonObject = JSONObject.parseObject(requestJson);
//公众号的appid
String appid = jsonObject.getString("appid");
/**
* 根据APPID获取access_token
* 我的access_token是做了一个定时器,每隔两个小时刷新一次access_token的值,
* 并且保存在redis当中(需要详情的话请留言)。
*/
String access_token = RedisUtil.getJustOneMapValueFromRedis(jedisPool,appid,"access_token");
//发给谁,该用户的openid
String openid = jsonObject.getString("openid");
//红包的值,最低100分
Integer redValue = jsonObject.getInteger("redValue");
//开始发送红包
logger.info("++++++++++++++开始发送红包++++++++++++++++++");
SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
/** 当前时间 yyyyMMddHHmmss */
String currTime = CommonUtil.getCurrTime();
/** 8位日期 */
String strTime = currTime.substring(8, currTime.length());
/** 四位随机数 */
String strRandom = CommonUtil.buildRandom(4) + "";
//商户订单号
parameters.put("mch_billno",strTime + strRandom);
/** 商户号 */
String mch_id = Constants.mch_id;