php实现微信公众平台发红包功能

本文实例为大家分享PHP微信公众平台给用户发红包的具体代码,供大家参考,具体内容如下

直接上代码

代码

rush:PHP;">
  • *微信红包还有部分可选的参数,如分享预设值等将在后续版本补充上相关功能。
  • 对应官方接口更新,追加了分裂红包的玩法,详情参考官方文档。
    */
  • CLASS WXHongBao {

    private $mch_id = "****"; //商户ID写死
    private $wxappid = "****"; //微信公众号,写死
    private $client_ip = ""; //"127.0.0.1"; //调用红包接口的主机的IP,服务端IP,写死,即脚本文件所在的IP
    private $apikey = ""; //pay的秘钥值
    private $total_num = 1; //发放人数。固定值1,不可修改
    private $nick_name = "微信公众号红包"; //红包商户名称
    private $send_name = "微信公众号红包"; //红包派发者名称
    private $wishing = "欢迎再次参与"; //
    private $act_name = ""; //活动名称
    private $remark = "";
    private $nonce_str = "";
    private $mch_billno = "";
    private $re_openid = ""; //接收方的openID
    private $total_amount = 1 ; //红包金额,单位 分
    private $min_value = 1; //最小金额
    private $max_value = 1; //根据接口要求,上述3值必须一致
    private $sign = ""; //签名在send时生成
    private $amt_type; //分裂红包参数,在sendgroup中进行定义,是常量 ALL_RAND

    //证书,在构造函数中定义,注意!
    private $apiclient_cert; //= getcwd()."/apiclient_cert.pem";
    private $apiclient_key;// = getcwd()."/apiclient_key.pem";
    private $apiclient_ca;// = getcwd()."/apiclient_key.pem";

    //分享参数
    private $isShare = false; //有用?似乎是无用参数,全部都不是必选和互相依赖的参数
    private $share_content = "";
    private $share_url ="";
    private $share_imgurl = "";

    private $wxhb_inited;

    private $api_hb_group = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack";//裂变红包
    private $api_hb_single = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";

    private $error = "ok"; //init

    /**

    • WXHongBao::__construct()
    • 步骤
    • new(openid,amount)
    • setnickname
    • setsend_name
    • setwishing
    • setact_name
    • setremark
    • send()
    • @return void
      */
      function __construct(){
      //好像没有什么需要构造函数做的 引入需要的文件
      $this->wxhb_inited = false;
      $this->apiclient_cert = getcwd() . "/zzz1/apiclient_cert.pem";
      $this->apiclient_key = getcwd() . "/zzz1/apiclient_key.pem";
      $this->apiclient_ca = getcwd() . "/zzz1/rootca.pem";
      }

    public function err(){
    return $this->error;
    }

    public function error(){
    return $this->err();
    }
    /**

    • WXHongBao::newhb()
    • 构造新红包
    • @param mixed $toOpenId
    • @param mixed $amount 金额分
    • @return void
      */
      public function newhb($toOpenId,$amount){
    if(!is_numeric($amount)){
      $this->error = "金额参数<a href="https://www.jb51.cc/tag/cuowu/" target="_blank" class="keywords">错误</a>";
      return;
    }elseif($amount<100){
      $this->error = "金额太小";
      return;
    }elseif($amount>20000){
      $this->error = "金额太大";
      return;
    }
    
    $this->gen_nonce_<a href="https://www.jb51.cc/tag/str/" target="_blank" class="keywords">str()</a>;//构造<a href="https://www.jb51.cc/tag/suiji/" target="_blank" class="keywords">随机</a>字串
    $this->gen_mch_billno();//构造订单号
    $this->s<a href="https://www.jb51.cc/tag/eto/" target="_blank" class="keywords">eto</a>penId($toOpenId);
    $this->setAmount($amount);
    $this->wxhb_inited = true; //<a href="https://www.jb51.cc/tag/biaoji/" target="_blank" class="keywords">标记</a>微信红包已经初始化完毕可以发送
    
    //每次new 都要将<a href="https://www.jb51.cc/tag/fenxiang/" target="_blank" class="keywords">分享</a>的<a href="https://www.jb51.cc/tag/neirong/" target="_blank" class="keywords">内容</a>给清空掉,否则会出现残余被引用
    $this->share_content= "";
    $this->share_<a href="https://www.jb51.cc/tag/imgur/" target="_blank" class="keywords">imgur</a>l = "";
    $this->share_url = "";

    }

    /**

    • WXHongBao::sendGroup()
    • 发送裂变红包,参数为裂变数量
    • @param integer $num 3-20
    • @return
      */
      public function sendGroup($num=3){
      $this->amt_type = "ALL_RAND";//$amt; 固定值。发送裂变红包组文档指定参数,随机
      return $this->send($this->api_hb_group,$num);
      }

    public function getApiSingle(){
    return $this->api_hb_single;
    }

    public function getApiGroup(){
    return $this->api_hb_group;
    }

    public function setNickName($nick){
    $this->nick_name = $nick;
    }

    public function setSendName($name){
    $this->send_name = $name;
    }

    public function setWishing($wishing){
    $this->wishing = $wishing;
    }

    public function setActName($act){
    $this->act_name = $act;
    }

    public function setRemark($remark){
    $this->remark = $remark;
    }

    public function setopenId($openid){
    $this->re_openid = $openid;
    }

    /**

    • WXHongBao::setAmount()
    • 设置红包金额
    • 文档有两处冲突描述
    • 一处指金额 >=1 (分钱)
    • 另一处指金额 >=100 < 20000 [1-200元]
    • 有待测试验证!
    • @param mixed $price 单位 分
    • @return void
      */
      public function setAmount($price){
      $this->total_amount = (int)$price;
      $this->min_value = (int)$price;
      $this->max_value = (int)$price;
      }

    //以下方法,为设置分裂红包时使用
    public function setHBminmax($min,$max){
    $this->min_value = $min;
    $this->max_value = $max;
    }

    public function setShare($img="",$url="",$content=""){
    //https://mmbiz.qlogo.cn/mmbiz/MS1jaDO92Ep4qNo9eV0rnItptyBrzUhJqT8oxSsCofdxibnNWMJiabaqgLPkDaEJmia6fqTXAXulKBa9NLfxYMwYA/0?wx_fmt=png
    //http://mp.weixin.qq.com/s?__biz=MzA5Njg4NTk3MA==&mid=206257621&idx=1&sn=56241da30e384e40771065051e4aa6a8#rd
    $this->sharecontent = $content;
    $this->share
    imgurl = $img;
    $this->share_url = $url;
    }

    /**

    • WXHongBao::send()
    • 发出红包
    • 构造签名
    • 注意第二参数,单发时不要改动!
    • @return boolean $success
      */
      public function send(){
    $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
    $total_num = 1;
    
    if(!$this->wxhb_inited) {
      $this->error .= "(红包未准备好)";
      return false; //未初始化完成
    }
    
    $this->total_num = $total_num;
    
    $this->gen_Sign(); //<a href="https://www.jb51.cc/tag/shengcheng/" target="_blank" class="keywords">生成</a>签名
    
    //构造提交的数据    
    $xml = $this->genXML<a href="https://www.jb51.cc/tag/param/" target="_blank" class="keywords">param()</a>;
    
    //echo $xml;
    
    //debug
    file_put_contents("hbxml.debug",$xml);
    
    //提交xml,curl
    //$url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
    $ch = curl_init();   
    curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank" class="keywords">eto</a>pt($ch,CURLOPT_TIMEOUT,10);
    curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank" class="keywords">eto</a>pt($ch,CURLOPT_RETURNTRANSFER,1);    
    curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank" class="keywords">eto</a>pt($ch,CURLOPT_URL,$url);
    curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank" class="keywords">eto</a>pt($ch,CURLOPT_SSL_VERIFYPEER,false);
    curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank" class="keywords">eto</a>pt($ch,CURLOPT_SSL_VERIFYHOST,false);
    
    //curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank" class="keywords">eto</a>pt($ch,CURLOPT_SSLCERTTYPE,'PEM');
    curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank" class="keywords">eto</a>pt($ch,CURLOPT_SSLCERT,$this-><a href="https://www.jb51.cc/tag/apiclient/" target="_blank" class="keywords">apiclient</a>_cert);    
    //curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank" class="keywords">eto</a>pt($ch,CURLOPT_SSLKEYTYPE,CURLOPT_SSLKEY,$this-><a href="https://www.jb51.cc/tag/apiclient/" target="_blank" class="keywords">apiclient</a>_key);
    
    curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank" class="keywords">eto</a>pt($ch,CURLOPT_CAINFO,$this->appclient_ca);
    
    /* 
    if( count($aHeader) >= 1 ){
      curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank" class="keywords">eto</a>pt($ch,CURLOPT_HTTPHEADER,$aHeader);
    }
    */    
    curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank" class="keywords">eto</a>pt($ch,CURLOPT_POST,1);
    curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank" class="keywords">eto</a>pt($ch,CURLOPT_POSTFIELDS,$xml);
    $data = curl_exec($ch);
     //die(print_r($data));
    if($data){
      curl_close($ch);
      $rsxml = simplexml_load_string($data);
      if($rsxml->return_code == 'SUCCESS' ){
        return true;
      }else{
        $this->error = json_encode($rsxml->return_msg);
        return false;  
      }
    }else{ 
      $this->error = curl_errno($ch);
    
      curl_close($ch);
      return false;
    }

    }

    private function gennoncestr(){
    $this->nonce_str = strtoupper(md5(mt_rand().time())); //确保不重复而已
    }

    private function gen_Sign(){
    unset($param);
    //其实应该用key重排一次 right?
    $param["act_name"]=$this->act_name;//

    if($this->total_num==1){ //这些是裂变红包用不上的参数,会导致签名<a href="https://www.jb51.cc/tag/cuowu/" target="_blank" class="keywords">错误</a>
      $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["client_ip"]=$this->client_ip;
       $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["max_value"]=$this->max_value;
       $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["min_value"]=$this->min_value;
      $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["nick_name"]=$this->nick_name;
    }
    
    $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["mch_billno"] = $this->mch_billno;  //   
    $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["mch_id"]=$this->mch_id;//    
    $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["nonce_str"]=$this->nonce_str;  //  
    $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["re_openid"]=$this->re_openid;//
    $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["remark"]=$this->remark;    //
    $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["send_name"]=$this->send_name;//
    $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["total_amount"]=$this->total_amount;//
    $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["total_num"]=$this->total_num;    //
    $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["wishing"]=$this->wishing;//
    $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["wxappid"]=$this->wxappid;//
    
    //裂变红包 用不到就注释掉
     if($this->share_content) $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["share_content"] = $this->share_content;
     if($this->share_<a href="https://www.jb51.cc/tag/imgur/" target="_blank" class="keywords">imgur</a>l) $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["share_<a href="https://www.jb51.cc/tag/imgur/" target="_blank" class="keywords">imgur</a>l"] = $this->share_<a href="https://www.jb51.cc/tag/imgur/" target="_blank" class="keywords">imgur</a>l;
     if($this->share_url) $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["share_url"] = $this->share_url;
    if($this->amt_type) $p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m["amt_type"] = $this->amt_type; //
    
    ksort($p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m); //按照键名排序...艹,上面排了我好久
    
    //$sign_raw = http_build_query($p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m)."&key=".$this->apikey;
    $sign_raw = "";
    foreach($p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>m as $k => $v){
      $sign_raw .= $k."=".$v."&";
    }
    $sign_raw .= "key=".$this->apikey;
    //可以用下面<a href="https://www.jb51.cc/tag/fangfa/" target="_blank" class="keywords">方法</a>查看
    // file_put_contents("11sign.txt",$sign_raw);//debug
    $this->sign = str<a href="https://www.jb51.cc/tag/toupper/" target="_blank" class="keywords">toupper</a>(md5($sign_raw));

    }

    /**

    • WXHongBao::genXMLparam()
    • 生成post的参数xml数据包
    • 注意生成之前各项值要生成,尤其是Sign
    • @return $xml
      */
      public function genXMLparam(){
      // $xml = "
    //   <sign>".$this->sign."</sign> 
    //   <mch_billno>".$this->mch_billno."</mch_billno> 
    //   <mch_id>".$this->mch_id."</mch_id> 
    //   <wxappid>".$this->wxappid."</wxappid> 
    //   <nick_name><![CDATA[".$this->nick_name."]]></nick_name> 
    //   <send_name><![CDATA[".$this->send_name."]]></send_name> 
    //   <re_openid>".$this->re_openid."</re_openid> 
    //   <total_amount>".$this->total_amount."</total_amount> 
    //   <min_value>".$this->min_value."</min_value> 
    //   <max_value>".$this->max_value."</max_value> 
    //   <total_num>".$this->total_num."</total_num> 
    //   <wishing><![CDATA[".$this->wishing."]]></wishing> 
    //   <client_ip><![CDATA[".$this->client_ip."]]></client_ip> 
    //   <act_name><![CDATA[".$this->act_name."]]></act_name> 
    //   <remark><![CDATA[".$this->remark."]]></remark>       
    //   <nonce_str>".$this->nonce_str."</nonce_str>";

    $xml = "

    act_name."]]> client_ip."]]> ".$this->max_value." ".$this->mch_billno." ".$this->mch_id." ".$this->min_value." nick_name."]]> ".$this->nonce_str." ".$this->re_openid." remark."]]> send_name."]]> ".$this->total_amount." ".$this->total_num." wishing."]]> ".$this->wxappid." ".$this->sign." ";
      // <nick_name><![CDATA[".$this->nick_name."]]></nick_name> 
    
    
    
      // <min_value>".$this->min_value."</min_value> 
      // <max_value>".$this->max_value."</max_value> 
    
    // $xml .="</xml>";
    
    return $xml;

    }

    /**

    • WXHongBao::gen_mch_billno()
    • 商户订单号(每个订单号必须唯一)
      组成: mch_id+yyyymmdd+10位一天内不能重复的数字。
      接口根据商户订单号支持重入, 如出现超时可再调用
    • @return void
      */
      private function gen_mch_billno(){
      //生成一个长度10,的阿拉伯数字随机字符串
      $rnd_num = array('0','1','2','3','4','5','6','7','8','9');
      $rndstr = "";
      while(strlen($rndstr)<10){
      $rndstr .= $rnd_num[array_rand($rnd_num)];
      }
    $this->mch_billno = $this->mch_id.date("Ymd").$rndstr;

    }
    }
    /*
    1.上边是红包类,需要用的时候直接引入红包类。
    *2.//实例化红包类

    • $wxhongbao=new \WXHongBao();
      *3. //需要发放的openid 金额 openid 根据微信提供的接口获取,金额根据自己需求
    • $wxhongbao->newhb($user_openid,$pay_money100);
      $wxhongbao->setActName("根据自己需求设置");
    • $wxhongbao->setWishing("根据自己需求设置");
      $wxhongbao->setRemark("根据自己需求设置");
      参数设置之后发放红包
      *$wxhongbao->send();
      **/
      ?>

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

    版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

    相关推荐


    服务器优化必备:深入了解PHP8底层开发原理
    Golang的网络编程:如何快速构建高性能的网络应用?
    Golang和其他编程语言的对比:为什么它的开发效率更高?
    PHP8底层开发原理揭秘:如何利用新特性创建出色的Web应用
    将字符重新排列以形成回文(如果可能)在C++中
    掌握PHP8底层开发原理和新特性:创建高效可扩展的应用程序
    服务器性能优化必学:掌握PHP8底层开发原理
    PHP8新特性和底层开发原理详解:优化应用性能的终极指南
    将 C/C++ 代码转换为汇编语言
    深入研究PHP8底层开发原理:创建高效可扩展的应用程序
    C++程序查找法向量和迹
    PHP8底层开发原理实战指南:提升服务器效能
    重排数组,使得当 i 为偶数时,arr[i] >= arr[j],当 i 为奇数时,arr[i] <= arr[j],其中 j < i,使用 C++ 语言实现
    Golang的垃圾回收:为什么它可以减少开发人员的负担?
    C++程序:将一个数组的所有元素复制到另一个数组中
    Golang:构建智能系统的基石
    为什么AI开发者应该关注Golang?
    在C和C++中,逗号(comma)的用法是用来分隔表达式或语句
    PHP8底层开发原理解析及新特性应用实例
    利用PHP8底层开发原理解析新特性:如何构建出色的Web应用