朱纯树博客
VPS测评推荐网站
cloudacead cloudacead

记一次开发小程序红包的经历

当时接到这个需求,瞬间就想到了微信的小程序红包,后来大体翻了一下文档,觉得就是给这个需求量身定做的.在第一个30天流水失败后,找了个微信商户的合作公司,坐快车,2天开通了微信小程序红包,微信企业付款到零钱功能.

接下来就是开发了,主要是3个接口,发放红包,领取红包,和验证红包状态,4个步骤,发放红包,验证红包状态,领取红包,验证红包状态.这里是官方链接: https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.PHP?chapter=18_4&index=1

    1.         1. 发放红包,参数很多,我就不一一细说,可以看看官方的说明,我直接上代码

1) 为了方便请求,封装一个红包基类Red.PHP

        1. <?php
        2. namespace appapicontroller;
        3. /*
        4. * 微信支付:小程序红包接口
        5. */
        6. use thinkController;
        7. class Red extends Controller
        8. {
        9.     private $sendurl = ‘https://api.mch.weixin.qq.com/mmpaymkttransfers/sendminiprogramhb’;//发放红包接口
        10.     private $searchurl = ‘https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo’;//红包查询接口
        11.     private $mch_id = ‘你的商户号’;//商户号
        12.     private $wxappid = ‘你的公众账号appid’;//公众账号appid
        13.     private $send_name = ‘随便写’;//商户名称
        14.     private $total_num = 1;//红包发放总人数,默认都是1个
        15.     private $notify_way = ‘MINI_PROGRAM_JSAPI’;//通知用户形式,这里不用改
        16.     private $scene_id = ”;//发放红包使用场景,红包金额大于200时必传
        17.     private $key=’你的秘钥’;//商户号支付钥匙
        18.  
        19.     /**
          1.   * 发放红包
        20.      * @param $mch_billno
        21.      * @param $re_openid
        22.      * @param $total_amount
        23.      * @param $wishing
        24.      * @param $act_name
        25.      * @param $remark
        26.      * @return mixed
        27.      * @throws Exception
        28.      */
        29.     public function sendhb($mch_billno,$re_openid,$total_amount,$wishing,$act_name,$remark)
        30.     {
        31.         //随机字符串
        32.         $nonce_str = $this->createNoncestr();
        33.         $parameters = array(
        34.             ‘nonce_str’ => $nonce_str,
        35.             ‘mch_billno’ => $mch_billno,
        36.             ‘mch_id’ => $this->mch_id,
        37.             ‘wxappid’ => $this->wxappid,
        38.             ‘send_name’ => $this->send_name,
        39.             ‘re_openid’ => $re_openid,
        40.             ‘total_amount’ => $total_amount,
        41.             ‘total_num’ => $this->total_num,
        42.             ‘wishing’ => $wishing,
        43.             ‘act_name’ => $act_name,
        44.             ‘remark’ => $remark,
        45.             ‘notify_way’ => $this->notify_way,
        46.             ‘scene_id’ => $this->scene_id
        47.         );
        48.         //生成签名,所有参数+key然后MD5
        49.         $parameters[‘sign’] = $this->getSign($parameters);
        50.         $xmlData = $this->arrayToXml($parameters);
        51.         $curlres = $this->postXmlCurl($xmlData, $this->sendurl);
        52.         $res = $this->xmlToArray($curlres);
        53.         return $res;
        54.     }
        55.  
        56.     /**
        57.      * 根据订单号查询红包状态
        58.      * @param $mch_billno
        59.      * @param $mch_id
        60.      * @param $appid
        61.      * @return mixed
        62.      * @throws Exception
        63.      */
        64.     public function searchhb($mch_billno,$mch_id,$appid)
        65.     {
        66.         //随机字符串
        67.         $nonce_str = $this->createNoncestr();
        68.         $parameters = array(
        69.             ‘nonce_str’ => $nonce_str,
        70.             ‘mch_billno’ => $mch_billno,
        71.             ‘mch_id’ => $mch_id,
        72.             ‘appid’ => $appid,
        73.             ‘bill_type’ => ‘MCHT’
        74.         );
        75.         //生成签名,所有参数+key然后MD5
        76.         $parameters[‘sign’] = $this->getSign($parameters);
        77.         $xmlData = $this->arrayToXml($parameters);
        78.         $curlres = $this->postXmlCurl($xmlData, $this->searchurl);
        79.         $res = $this->xmlToArray($curlres);
        80.         return $res;
        81.     }
        82.  
        83.     private function postXmlCurl($xml, $url)
        84.     {
        85.         $ch = curl_init();
        86.         curl_setopt($ch, CURLOPT_URL, $url);
        87.         //设置header
        88.         curl_setopt($ch, CURLOPT_HEADER, FALSE);
        89.         //要求结果为字符串且输出到屏幕上
        90.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        91.         //post提交方式
        92.         curl_setopt($ch, CURLOPT_POST, TRUE);
        93.         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        94.         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        95.         curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        96.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        97.         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        98.         //证书的位置
        99.         curl_setopt($ch, CURLOPT_SSLCERT, APP_PATH . ‘/certRed/apiclient_cert.pem’);    //你的证书所在路径
        100.         //证书key的位置
        101.         curl_setopt($ch, CURLOPT_SSLKEY, APP_PATH . ‘/certRed/apiclient_key.pem’);    //你的证书key所在路径
        102.  
        103.         //运行curl
        104.         $data = curl_exec($ch);
        105.         //返回结果
        106.         if ($data) {
        107.             curl_close($ch);
        108.             return $data;
        109.         } else {
        110.             $error = curl_errno($ch);
        111.             curl_close($ch);
        112.             throw new Exception(“curl出错,错误码:$error”);
        113.         }
        114.     }
        115.  
        116. //数组转换成xml
        117.     private function arrayToXml($arr)
        118.     {
        119.         $xml = “”;
        120.         foreach ($arr as $key => $val) {
        121.             if (is_array($val)) {
        122.                 $xml .= “” . $this->arrayToXml($val) . “” . $key . “>”;
        123.             } else {
        124.                 $xml .= “” . $val . “” . $key . “>”;
        125.             }
        126.         }
        127.         $xml .= “”;
        128.         return $xml;
        129.     }
        130.  
        131.     //xml转换成数组
        132.     private function xmlToArray($xml)
        133.     {
        134.         //禁止引用外部xml实体
        135.         libxml_disable_entity_loader(true);
        136.         $xmlstring = simplexml_load_string($xml, ‘SimpleXMLElement’, LIBXML_NOCDATA);
        137.         $val = json_decode(json_encode($xmlstring), true);
        138.         return $val;
        139.     }
        140.  
        141.     //作用:产生随机字符串,不长于32位
        142.     public function createNoncestr($length = 32)
        143.     {
        144.         $chars = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”;
        145.         $str = “”;
        146.         for ($i = 0; $i
        147.             $str .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
        148.         }
        149.         return $str;
        150.     }
        151.  
        152.     //作用:生成签名
        153.     public function getSign($Obj)
        154.     {
        155.         foreach ($Obj as $k => $v) {
        156.              //不为空的参数才参与签名
        157.             if (!empty($v)) {
        158.                 $Parameters[$k] = $v;
        159.             }
        160.         }
        161.         //签名步骤一:按字典序排序参数
        162.         ksort($Parameters);
        163.         $String = $this->formatBizQueryParaMap($Parameters, false);
        164.         //签名步骤二:在string后加入KEY
        165.         $String = $String . “&key=” . $this->key;
        166.         //签名步骤三:MD5加密
        167.         $String = md5($String);
        168.          //签名步骤四:所有字符转为大写
        169.         $result = strtoupper($String);
        170.         return $result;
        171.     }

           

        172.      //作用:格式化参数,签名过程需要使用
        173.     private function formatBizQueryParaMap($paraMap, $urlencode)
        174.     {
        175.         $buff = “”;
        176.         ksort($paraMap);
        177.         foreach ($paraMap as $k => $v) {
        178.             if ($urlencode) {
        179.                 $v = urlencode($v);
        180.             }
        181.             $buff .= $k . “=” . $v . “&”;
        182.         }
        183.         $reqPar = ”;
        184.         if (strlen($buff) > 0) {
        185.             $reqPar = substr($buff, 0, strlen($buff) – 1);
        186.         }
        187.         return $reqPar;
        188.     }
        189. }
        190.  

2). 在另外一个控制器,写个测试方法调用接口

          1. /**
        1.      *  测试红包发放/红包查询接口
        2.      * @param string $mch_billno  订单号
        3.      * @param string $mch_id      商户号
        4.      * @param string $appid       appid
        5.      * @throws Exception
        6.      */
        7.     public function test($mch_billno=”,$mch_id=”,$appid=”)
        8.     {
        9.         if ($mch_billno && $mch_id) {   //查询红包状态
        10.             $weixinpay = new Red();
        11.             $res = $weixinpay->searchhb($mch_billno, $mch_id, $appid);
        12.             print_r($res);
        13.         } else {     //发放红包
        14.             $money = mt_rand(100, 999);   //红包金额,测试金额1元~9.99元
        15.             $mch_billno = date(“YmdHis”) . rand(100, 999);//商户订单号
        16.             $re_openid = $this->openid;//用户openid
        17.             $total_amount = $money;//付款金额,单位分
        18.             $wishing = ‘恭喜’;//红包祝福语
        19.             $act_name = ‘奖励’;//活动名称
        20.             $remark = ‘您的专属红包’;//备注
        21.             $weixinpay = new Red();
        22.             $res = $weixinpay->sendhb($mch_billno, $re_openid, $total_amount, $wishing, $act_name, $remark);
        23.             print_r($res);
        24.         }
        25.     }

3). 测试红包发放接口,尴尬,余额不足.这里提醒一下,刚开通小程序红包的朋友,一定要进行产品设置,限额限数限ip,我改一下金额再跑一下

记一次开发小程序红包的经历插图

第二次发放成功了,说明发放接口没问题

记一次开发小程序红包的经历插图1

4). 测试红包验证接口,这次很顺利,请求成功,status对照文档看

记一次开发小程序红包的经历插图2

      1.   2. 领取红包,这个动作要在小程序中调用,还是直接上代码
        1. 1). 这里我将领取红包的参数在方法里处理好,用接口返回到小程序
          1. $arr[‘appId’] = ‘你的appid’;
          2. $arr[‘timeStamp’] = ‘”‘.time().'”‘;    //时间戳要转字符串格式
          3. $arr[‘package’] = ‘urlencode之后的package,这个参数在红包发放成功之后可获取’;   //package要进行urlencode
          4. $weixinpay = new Red();
          5. $arr[‘nonceStr’] = $weixinpay->createNoncestr();
          6. $arr[‘paySign’] = $weixinpay->getSign($arr);

            $arr[‘signType’] = ‘MD5’;   //不参与签名加密

            $this->success(‘发送成功’,$arr);

2). 小程序端接口接收参数

//后端传参,前端调用sendBizRedPacket函数

httpGet(“/api/web/getRed”, function(res) {

if (res.code == 1) {

console.log(‘拆红包’);

wx. sendBizRedPacket ({

timeStamp: res.data.timeStamp, // 支付签名时间戳,

nonceStr: res.data.nonceStr, // 支付签名随机串,不长于 32 位

package: res.data.package, //扩展字段,由商户传入

signType: res.data.signType, // 签名方式,

paySign: res.data.paySign, // 支付签名

success:function(res){

console.log(‘成功’,res);

},

fail:function(res){

console.log(‘失败’,res);

},

complete:function(res){

console.log(‘结束’,res);

}

})

console.log(‘拆红包之后’);

}

})

3). 查看执行结果

记一次开发小程序红包的经历插图3

4). gg,彩蛋时间到了,场景值不支持.有没有想到什么,目前小程序红包仅支持用户微信扫码打开小程序,进行红包领取

记一次开发小程序红包的经历插图4

我是gg了,我们的业务要求是用户发布信息成功之后,触发红包发放功能.如果你的需求是营销拉新,扫码触发.恭喜你,直接复制粘贴吧,记得改参数

文章来源于互联网:记一次开发小程序红包的经历

赞(0) 打赏
未经允许不得转载:VPS测评推荐网站 - 朱纯树博客 » 记一次开发小程序红包的经历

评论 21

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #30

    Greetings from California! I’m bored at work so I decided to browse your website on my iphone during lunch break.
    I love the info you provide here and can’t wait to take a look when I get home.
    I’m surprised at how quick your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyways, amazing site!

  2. #29

    Hi Dear, are you in fact visiting this web site on a regular basis,
    if so afterward you will definitely get good experience.

  3. #28

    I truly love your site.. Very nice colors & theme. Did you build this web
    site yourself? Please reply back as I’m wanting to create my own site and would love
    to learn where you got this from or exactly what the theme is called.
    Thanks!

  4. #27

    Hello are using Wordpress for your site platform?
    I’m new to the blog world but I’m trying to get started and
    create my own. Do you require any html coding knowledge to make your own blog?
    Any help would be greatly appreciated!

  5. #26

    You are so awesome! I don’t think I’ve read a single thing like this before.

    So good to find another person with some unique thoughts on this topic.

    Really.. thanks for starting this up. This site is something that is required on the
    internet, someone with a little originality!

  6. #25

    Just want to say your article is as amazing. The clarity
    in your post is simply great and i could assume you’re an expert on this
    subject. Fine with your permission allow me to grab your feed to keep up to date with forthcoming post.
    Thanks a million and please carry on the enjoyable work.

    www.evergale.org1周前 (08-10)回复