微信公眾號下發紅包 -- PHP

Purgatory001發表於2018-08-16

不記得是轉載的誰的啦~~~

 

$sendpay = new SendpayController();
$data['state'] = $sendpay->index($user['openid'], $money);//傳入 公眾號openid ,和金額,最小金額為 1元,最大金額為200

 

<?php

class SendpayController {

    function index($toOpenId = "", $price = 1) {
        if ($toOpenId == "") {
            $toOpenId = 'oA5V_jraRDQtTCXZd6Q8gQ9rPHhI'; //接收紅包的使用者的微信OpenId
        }
        $hb = new wxpay();
        if ($price < 1 || $price > 200) {
            return 0;
        } else {
            $price = $price * 100;
            $hb->newhb($toOpenId, $price); //新建一個10元的紅包,第二引數單位是 分,注意取值範圍 1-200元
            //獲取後臺設定
            $res = M("redword")->where("state = 1")->find();
            //以下若干項可選操作,不指定則使用class指令碼頂部的預設值
            if($res) {
//                $hb->setNickName($res['rname']);
                $hb->setSendName($res['rusername']);
                $hb->setWishing($res['blessing']);
                $hb->setActName($res['rname']);
//                $hb->setRemark($res['blessing']);
            }
            //傳送紅包
            if (!$hb->send()) { //傳送錯誤
                return 0;
//                echo $hb->err();
            } else {
                return 1;
            }
        }
    }

}

/**
 * Description of PayController
 *
 * @author Administrator
 */
class wxpay {

    private $mch_id = ""; //商戶ID寫死
    private $wxappid = ""; //微信公眾號,寫死
    private $client_ip = ""; //呼叫紅包介面的主機的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 = "oA5V_jraRDQtTCXZd6Q8gQ9rPHhI"; //接收方的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 $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() . "/apiclient_cert.pem";
        $this->apiclient_key = getcwd() . "/apiclient_key.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 = "金額引數錯誤";
            return;
        } elseif ($amount < 100) {
            $this->error = "金額太小";
            return;
        } elseif ($amount > 20000) {
            $this->error = "金額太大";
            return;
        }

        $this->gen_nonce_str(); //構造隨機字串
        $this->gen_mch_billno(); //構造訂單號
        $this->setOpenId($toOpenId);
        $this->setAmount($amount);
        $this->wxhb_inited = true; //標記微信紅包已經初始化完畢可以傳送
        //每次new 都要將分享的內容給清空掉,否則會出現殘餘被引用
        $this->share_content = "";
        $this->share_imgurl = "";
        $this->share_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(); //生成簽名
        //構造提交的資料    
        $xml = $this->genXMLParam();


        //debug
        file_put_contents(date("Y-m-d_H:i:s") . "hbxml.txt", $xml);

        //提交xml,curl
        //$url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT, $this->apiclient_cert);
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, $this->apiclient_key);

        /*
          if( count($aHeader) >= 1 ){
          curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
          }
         */
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $data = curl_exec($ch);
        if ($data) {
            curl_close($ch);
            $rsxml = simplexml_load_string($data);
            if ($rsxml->return_code == 'SUCCESS') {
                return true;
            } else {
                $this->error = $rsxml->return_msg;
                return false;
            }
        } else {
            $this->error = curl_errno($ch);

            curl_close($ch);
            return false;
        }
    }

    /**
     * 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;
    }

    /**
     * WXHongBao::setActName()
     * 活動名稱
     * @param mixed $act
     * @return void
     */
    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 = $price;
        $this->min_value = $price;
        $this->max_value = $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->share_content = $content;
        $this->share_imgurl = $img;
        $this->share_url = $url;
    }

    private function gen_nonce_str() {
        $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) { //這些是裂變紅包用不上的引數,會導致簽名錯誤
            $param["client_ip"] = $this->client_ip;
            $param["max_value"] = $this->max_value;
            $param["min_value"] = $this->min_value;
            $param["nick_name"] = $this->nick_name;
        }

        $param["mch_billno"] = $this->mch_billno;  //   
        $param["mch_id"] = $this->mch_id; //    
        $param["nonce_str"] = $this->nonce_str;  //  
        $param["re_openid"] = $this->re_openid; //
        $param["remark"] = $this->remark;    //
        $param["send_name"] = $this->send_name; //
        $param["total_amount"] = $this->total_amount; //
        $param["total_num"] = $this->total_num;    //
        $param["wishing"] = $this->wishing; //
        $param["wxappid"] = $this->wxappid; //

        if ($this->share_content)
            $param["share_content"] = $this->share_content;
        if ($this->share_imgurl)
            $param["share_imgurl"] = $this->share_imgurl;
        if ($this->share_url)
            $param["share_url"] = $this->share_url;

        if ($this->amt_type)
            $param["amt_type"] = $this->amt_type; //

        ksort($param); //按照鍵名排序...艹,上面排了我好久
        //$sign_raw = http_build_query($param)."&key=".$this->apikey;
        $sign_raw = "";
        foreach ($param as $k => $v) {
            $sign_raw .= $k . "=" . $v . "&";
        }
        $sign_raw .= "key=" . $this->apikey;

        //file_put_contents("sign.raw",$sign_raw);//debug
        $this->sign = strtoupper(md5($sign_raw));
    }

    /**
     * WXHongBao::genXMLParam()
     * 生成post的引數xml資料包
     * 注意生成之前各項值要生成,尤其是Sign
     * @return $xml
     */
    public function genXMLParam() {

        $xml = "<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>
      ";


        if ($this->share_content)
            $xml .= "<share_content><![CDATA[" . $this->share_content . "]]></share_content>
    ";
        if ($this->share_imgurl)
            $xml .= "<share_imgurl><![CDATA[" . $this->share_imgurl . "]]></share_imgurl>
    ";
        if ($this->share_url)
            $xml .= "<share_url><![CDATA[" . $this->share_url . "]]></share_url>
    ";
        if ($this->amt_type)
            $xml .= "<amt_type><![CDATA[" . $this->amt_type . "]]></amt_type>
    ";

        $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;
    }

}

 

相關文章