微信小程序發放紅包+領取紅包(PHP) - 新聞資訊 - 雲南小程序開發|雲南軟件開發|雲南網站建設-昆明融晨信息技術有限公司

159-8711-8523

雲南網建設/小程序開發/軟件開發

知識

不(bù)管是(shì)網站,軟件還是(shì)小程序,都要(yào / yāo)直接或間接能爲(wéi / wèi)您産生價值,我們在(zài)追求其視覺表現的(de)同時(shí),更側重于(yú)功能的(de)便捷,營銷的(de)便利,運營的(de)高效,讓網站成爲(wéi / wèi)營銷工具,讓軟件能切實提升企業内部管理水平和(hé / huò)效率。優秀的(de)程序爲(wéi / wèi)後期升級提供便捷的(de)支持!

您當前位置>首頁 » 新聞資訊 » 小程序相關 >

微信小程序發放紅包+領取紅包(PHP)

發表時(shí)間:2020-9-27

發布人(rén):融晨科技

浏覽次數:72

發放紅包文檔:https://pay.weixin.qq.com/wiki/doc/api/tools/miniprogram_hb.php?chapter=13_9&index=2

領取紅包文檔:https://pay.weixin.qq.com/wiki/doc/api/tools/miniprogram_hb.php?chapter=13_10&index=3

class Index
{
    public function index(Request $request=null)
    {

        //商戶訂單号(每個(gè)訂單号必須唯一。取值範圍:0~9,a~z,A~Z)
        //組成: mch_id+yyyymmdd+10位一天内不(bù)能重複的(de)數字。
        $mch_billno = ''.rand(1000000000,9999999999);
        $mch_id = '';//商戶号
        $wxappid = '';//小程序賬号appid
        $send_name = '';//商戶名稱
        $re_openid = '';//用戶openid
        $total_amount = 30;//付款金額,單位分
        $total_num = 1;//紅包發放總人(rén)數
        $wishing = '望天宇八方清似玉';//紅包祝福語
        $client_ip = '';//調用接口的(de)服務器Ip地(dì / de)址,提前在(zài)小程序後台設置好
        $act_name = '紅包';//活動名稱
        $remark = '6666';//備注
        $notify_way = 'MINI_PROGRAM_JSAPI';//通知用戶形式JSAPI
        $scene_id = 'PRODUCT_2';//發放紅包使用場景,紅包金額大(dà)于(yú)200時(shí)必傳
        $key = '';//商戶号支付鑰匙

        $weixinpay = new WeixinPay($mch_billno, $mch_id, $wxappid, $send_name,$re_openid,$total_amount,$total_num,$wishing,$client_ip,$act_name,$remark,$notify_way,$scene_id,$key);
        $res=$weixinpay->sendhb();
        $result = [
            'timeStamp'=> time()."",
            'nonceStr'=>$this->createNoncestr(),
            'package'=>urlencode($res['package']),
            'appId'=>$wxappid,

        ];
        $result['paySign'] = $this->getSign($result);
        return json($result);
    }



    private function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        } return $str;
    }


    private function getSign($Obj) {
        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //簽名步驟一:按字典序排序參數
        ksort($Parameters);

        $String = $this->formatBizQueryParaMap($Parameters, false);
        //簽名步驟二:在(zài) string 後加入 KEY
        $String = $String . "&key=" . '商戶号支付鑰匙';

        //簽名步驟三:MD5 加密
        $String = md5($String);
        //簽名步驟四:所有字符轉爲(wéi / wèi)大(dà)寫--根據接口需要(yào / yāo)打開限制
        $result_ = $String;
        // $result_ = strtoupper($String);
        return $result_;
    }

    /**
     * 作用:格式化參數,簽名過程需要(yào / yāo)使用
     * @param $paraMap
     * @param $urlencode
     * @return string
     */
    private function formatBizQueryParaMap($paraMap, $urlencode) {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = "";
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }
}






class WeixinPay {

    private $sendurl = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendminiprogramhb';//發放紅包接口
    private $mch_billno;//商戶訂單号
    private $mch_id;//商戶号
    private $wxappid;//公衆賬号appid
    private $send_name;//商戶名稱
    private $re_openid;//用戶openid
    private $total_amount;//付款金額,單位分
    private $total_num;//紅包發放總人(rén)數
    private $wishing;//紅包祝福語
    private $client_ip;//Ip地(dì / de)址
    private $act_name;//活動名稱
    private $remark;//備注
    private $notify_way;//通知用戶形式
    private $scene_id;//發放紅包使用場景,紅包金額大(dà)于(yú)200時(shí)必傳
    private $key;//商戶号支付鑰匙

    function __construct($mch_billno, $mch_id, $wxappid, $send_name,$re_openid,$total_amount,$total_num,$wishing,$client_ip,$act_name,$remark,$notify_way,$scene_id,$key) {
        $this->mch_billno = $mch_billno;
        $this->mch_id = $mch_id;
        $this->wxappid = $wxappid;
        $this->send_name = $send_name;
        $this->re_openid = $re_openid;
        $this->total_amount = $total_amount;
        $this->total_num = $total_num;
        $this->wishing = $wishing;
        $this->client_ip = $client_ip;
        $this->act_name = $act_name;
        $this->remark = $remark;
        $this->notify_way = $notify_way;
        $this->scene_id = $scene_id;
        $this->key = $key;
    }

    public function sendhb(){
        //随機字符串
        $nonce_str = $this->createNoncestr();
        //商戶訂單号
        $mch_billno = $this->mch_billno;
        //商戶号
        $mch_id = $this->mch_id;
        //公衆賬号appid
        $wxappid = $this->wxappid;
        //商戶名稱
        $send_name = $this->send_name;
        //用戶openid
        $re_openid = $this->re_openid;
        //付款金額,單位分
        $total_amount = $this->total_amount;
        //紅包發放總人(rén)數
        $total_num = $this->total_num;
        //紅包祝福語
        $wishing = $this->wishing;
        //Ip地(dì / de)址
        $client_ip = $this->client_ip;
        //活動名稱
        $act_name = $this->act_name;
        //備注
        $remark = $this->remark;
        //通知用戶形式
        $notify_way = $this->notify_way;
        //發放紅包使用場景,紅包金額大(dà)于(yú)200時(shí)必傳
        $scene_id = $this->scene_id;

        $parameters = array(
            'nonce_str' => $nonce_str,
            'mch_billno' => $mch_billno,
            'mch_id' => $mch_id,
            'wxappid' => $wxappid,
            'send_name' => $send_name,
            're_openid' => $re_openid,
            'total_amount' => $total_amount,
            'total_num' => $total_num,
            'wishing' => $wishing,
            'client_ip' => $client_ip,
            'act_name' => $act_name,
            'remark' => $remark,
            'notify_way' => $notify_way,
            'scene_id' => $scene_id
        );
        //生成簽名,所有參數+key然後MD5
        $parameters['sign'] = $this->getSign($parameters);

        $xmlData = $this->arrayToXml($parameters);
//        var_dump($xmlData);
        $curlres = $this->postXmlCurl($xmlData, $this->sendurl);
//        var_dump($curlres);
        $res = $this->xmlToArray($curlres);

//        var_dump($res);
        return $res;
    }


    private function postXmlCurl($xml, $url)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        //設置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要(yào / yāo)求結果爲(wéi / wèi)字符串且輸出(chū)到(dào)屏幕上(shàng)
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //證書的(de)位置
//        var_dump(curl_setopt($ch, CURLOPT_SSLCERT, __DIR__ . '/cert/apiclient_cert.pem'));die;
        curl_setopt($ch, CURLOPT_SSLCERT,'D:/phpstudy_pro/WWW/weixinpem/apiclient_cert.pem');
        //證書key的(de)位置
        curl_setopt($ch, CURLOPT_SSLKEY,'D:/phpstudy_pro/WWW/weixinpem/apiclient_key.pem');

        //運行curl
        $data = curl_exec($ch);
        //返回結果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            throw new Exception("curl出(chū)錯,錯誤碼:$error");
        }
    }

    //數組轉換成xml
    private function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $xml .= "<" . $key . ">" . $this->arrayToXml($val) . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    //xml轉換成數組
    private function xmlToArray($xml) {
        //禁止引用外部xml實體
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring), true);
        return $val;
    }

    //作用:産生随機字符串,不(bù)長于(yú)32位
    private function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    //作用:生成簽名
    private function getSign($Obj) {
        foreach ($Obj as $k => $v) {
            //不(bù)爲(wéi / wèi)空的(de)參數才參與簽名
            if(!empty($v)){
                $Parameters[$k] = $v;
            }
        }
        //簽名步驟一:按字典序排序參數
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //簽名步驟二:在(zài)string後加入KEY
        $String = $String . "&key=" . $this->key;
        //簽名步驟三:MD5加密
        $String = md5($String);
        //簽名步驟四:所有字符轉爲(wéi / wèi)大(dà)寫
        $result = strtoupper($String);
        return $result;
    }

    //作用:格式化參數,簽名過程需要(yào / yāo)使用
    private function formatBizQueryParaMap($paraMap, $urlencode) {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

}

相關案例查看更多