<?php
header('Content-type:text');
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
//通过get获取字符串
if (!isset($_GET['echostr'])) {
    $wechatObj->responseMsg();
}else{
    $wechatObj->valid();
}
/**
 *
 */
class wechatCallbackapiTest
{
    /**
     * 签名消息入口
     * @return [type] [description]
     */
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }
     /**
     * 响应本消息
     * @return [type] [description]
     */
    public function responseMsg()
    {
        $postStr = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
        
        if (!empty($postStr)){
            $this->logger("R ".$postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
            }
            $this->logger("T ".$result);
            echo $result;
        }else {
            echo "";
            exit;
        }
    }
    /**
     * 收到文本消息的处理
     * @param  [type] $postObj [description]
     * @return [type]          [description]
     */
    private function receiveText($postObj){
        //获取到的文本内容
        $msg = $postObj->Content;
        //获取openid
        $openid = $postObj->FromUserName;
        //$result = $this->transmitText($postObj,$openid.':'.$text);
        if($msg == '红包'){
            //调用微信支付
            $this->sendredpack($openid);
            $text = '感谢您领取红包';
        }else{
            $text = '感谢您XXXXX衣柜的关注!';
        }
        
        //回复消息
        $result = $this->transmitText($postObj,$text);
        return $result;
    }
    /**
     * 检验签名信息
     * @return [type] [description]
     */
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 关注消息回复
     * @param  [type] $object [description]
     * @return [type]         [description]
     */
    private function receiveEvent($object)
    {
        $content = "";
        //判断是否送红包
        $isSend = false;
        switch ($object->Event)
        {
            case "subscribe":
                $content = "欢迎关注XXX衣柜!请输入关键词“红包”领取!";
                //设为发送红包
                $isSend = ture;
                break;
            case "unsubscribe":
                $content = "取消关注";
                break;
        }
        $result = $this->transmitText($object, $content);
        if($isSend){
            //发送红包
            $openid = $openid = $postObj->FromUserName;
            //调用微信支付
            $this->sendredpack($openid);
        }
        return $result;
    }
    /**
     * 转化为xml消息
     * @param  [type] $object  [description]
     * @param  [type] $content [description]
     * @return [type]          [description]
     */
    private function transmitText($object, $content)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);

return $result;
    }

/**
     * 日志记录
     * @param  [type] $log_content [description]
     * @return [type]              [description]
     */
    private function logger($log_content)
    {
        if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
            $max_size = 10000;
            $log_filename = "log.xml";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
        }
    }
    /**
     * 公众号curlpost消息
     * @param  [type]  $url     [description]
     * @param  [type]  $vars    [description]
     * @param  integer $second  [description]
     * @param  array   $aHeader [description]
     * @return [type]           [description]
     */
    public function curl_post_ssl($url, $vars, $second=30,$aHeader=array())
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理,如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
       
        //以下两种方式需选择一种
       
        //第一种方法,cert 与 key 分别属于两个.pem文件
        //默认格式为PEM,可以注释
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/apiclient_cert.pem');
        // 默认格式为PEM,可以注释
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/apiclient_key.pem');
       
        //第二种方式,两个文件合成一个.pem文件
        //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');
     
         if( count($aHeader) >= 1 ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }
     
        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            return $data;
        }
        else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }

//$re = sendredpack();
    //var_dump($re);
    /**
     * 发红包
     * @return [type] [description]
     */
    public function sendredpack($openid){
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
        $mch_billno = '随机字符串如(1235583002)' . date ( "YmdHis", time () ) . rand ( 1000, 9999 );      //商户订单号
        //$mch_billno = '1235583002'.uniqid(); //商户订单号
        $mch_id = '商户号';                         //微信支付分配的商户号
        $wxappid = '你的APPID';                //公众账号appid
        $send_name = "名字,尽量别超过四个字";
        $re_openid = $openid;
        $total_amount = 100;                             // 付款金额,单位分
        $total_num = 1;                                  //红包发放总人数
        $wishing = "恭喜发财";                           //红包祝福语
        $client_ip = "211.149.199.227 ";                    //Ip地址
        $act_name = "首次关注";                          //活动名称
        $remark = "红包";                                //备注
        $apikey = "商户apikey";    // key 商户后台设置的  微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
        $nonce_str =  md5(rand());                       //随机字符串,不长于32位
        $m_arr = array (
            '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,
            'nonce_str' => $nonce_str
        );
        array_filter ( $m_arr ); // 清空参数为空的数组元素
        ksort ( $m_arr ); // 按照参数名ASCII码从小到大排序
        $stringA = "";
        foreach ( $m_arr as $key => $row ) {
            $stringA .= "&" . $key . '=' . $row;
        }
        $stringA = substr ( $stringA, 1 );
        // 拼接API密钥:
        $stringSignTemp = $stringA."&key=" . $apikey;
        $sign = strtoupper ( md5 ( $stringSignTemp ) );         //签名

$textTpl = '<xml>
                           <sign><![CDATA[%s]]></sign>
                            <mch_billno><![CDATA[%s]]></mch_billno>
                            <mch_id><![CDATA[%s]]></mch_id>
                            <wxappid><![CDATA[%s]]></wxappid>
                            <send_name><![CDATA[%s]]></send_name>
                            <re_openid><![CDATA[%s]]></re_openid>
                            <total_amount><![CDATA[%s]]></total_amount>
                            <total_num><![CDATA[%s]]></total_num>
                            <wishing><![CDATA[%s]]></wishing>
                            <client_ip><![CDATA[%s]]></client_ip>
                            <act_name><![CDATA[%s]]></act_name>
                            <remark><![CDATA[%s]]></remark>
                            <nonce_str><![CDATA[%s]]></nonce_str>
                            </xml>';
        $resultStr = sprintf($textTpl, $sign, $mch_billno, $mch_id, $wxappid, $send_name,$re_openid,$total_amount,$total_num,$wishing,$client_ip,$act_name,$remark,$nonce_str);
        return $this->curl_post_ssl($url,$resultStr);
    }
}

?>

php微信自动发红包的更多相关文章

  1. PHP自动发红包代码示例

    <?php header('Content-type:text'); define("TOKEN", "weixin"); $wechatObj = ne ...

  2. 微信小程序发红包

    背景: 近期一个朋友公司要做活动,活动放在小程序上.小程序开发倒是不难,不过要使用小程序给微信用户发红包,这个就有点麻烦 确定模式: 小程序目前没有发红包接口,要实现的话,只能是模拟红包,即小程序上做 ...

  3. 微信小程序红包开发 小程序发红包 开发过程中遇到的坑 微信小程序红包接口的

    最近公司在开发一个小程序红包系统,客户抢到红包需要提现.也就是通过小程序来给用户发红包. 小程序如何来发红包呢?于是我想到两个方法. 之前公众号开发一直用了的.一个是红包接口,一个是企业支付接口.一开 ...

  4. 微信小程序红包开发 小程序发红包 开发过程中遇到的坑 微信小程序红包接口的

    微信小程序红包开发 小程序发红包 开发过程中遇到的坑 微信小程序红包接口的   最近公司在开发一个小程序红包系统,客户抢到红包需要提现.也就是通过小程序来给用户发红包. 小程序如何来发红包呢?于是我想 ...

  5. 微信发红包 PHP 实现

    最近做生日营销,需要微信发红包,特此从网上找了一篇教程 首先你的有个服务号,并且开通了微信支付,我在这就不说怎么去申请和开通了,我是看了微信官方文档后,想看官方文档的朋友可以到下面这个链接 https ...

  6. PHP微信发红包简明教程

    PHP微信发红包简明教程1首先进入公众号申请微信支付 申请成功账号密码会发到你指定的邮箱 是登陆商户平台的2 进入后申请发红包借口3 调用发红包接口 https://api.mch.weixin.qq ...

  7. 微信自动抢红包android实现

    AccessibilityService-微信自动抢红包 2018年02月01日 16:09:06 阅读数:1757 在领导发红包的时候,看到有些同事在1s.2s抢到红包,为什么他们能够这么快?一定是 ...

  8. 微信小程序红包开发思路 微信红包小程序开发思路讲解

    之前公司开发小程序红包,将自己在开发的过程中遇到的一些坑分享到了博客里.不少人看了以后,还是不明白怎么开发.也加了我微信咨询.所以今天,我就特意再写一篇文章,这次就不谈我开发中遇到的坑了.就主要给大家 ...

  9. 使用PHP编写发红包程序

    使用PHP编写发红包程序 http://www.jb51.net/article/69815.htm 投稿:hebedich 字体:[增加 减小] 类型:转载 时间:2015-07-22   微信发红 ...

随机推荐

  1. Java 实现桥接(Bridge)模式

    类图: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamp3d21scDQ1Ng==/font/5a6L5L2T/fontsize/400/fill/I0 ...

  2. PyTorch 60 分钟入门教程:数据并行处理

    可选择:数据并行处理(文末有完整代码下载) 作者:Sung Kim 和 Jenny Kang 在这个教程中,我们将学习如何用 DataParallel 来使用多 GPU. 通过 PyTorch 使用多 ...

  3. js数组清空和去重

    1.splice var ary = [1,2,3,4]; ary.splice(0,ary.length); console.log(ary); // 输出 Array[0],空数组,即被清空了 2 ...

  4. (1)iOS9完美越狱

    方式一:同步推越狱,其实用的也是方式二 参考:iOS9.3.5不完美越狱(点击跳转) 方式二:使用impactor越狱. 下载地址:http://www.pc6.com/mac/505285.html

  5. 织梦发布的文章如何批量替换文章"来源"和"作者"?

    做的网站中已经采集好并已生成HTML了的文章或以前已发布的文章如何快速批量替换所有“来源”和“作者”呢?第一步:打开:dede模板网站(后台目录)\templets\article_add.htm ( ...

  6. URAL2104. Game with a Strip(博弈)

    There is a strip 1 × n with two sides. Each square of the strip (their total amount is 2n, n squares ...

  7. Spring事物注意事项

    一.尽量用注解声明事务 过去开发喜欢用tx:advice+aop命名空间方式来配置事务,一次配置对满足切点规则的方法永久生效.但也可能因此导致事务滥用,在不需要用到事务的地方用了会影响系统的并发性能. ...

  8. JSP指令--include指令(静态包含)

    转自:https://blog.csdn.net/chentiefeng521/article/details/51802319 include指令         include指令是文件加载指令, ...

  9. java.lang.NoSuchMethodError: org.springframework.web.context.ConfigurableWebApplicationContext.setId

    运行spring报了这个错误,网上说是spring版本冲突,检查maven依赖,发现我依赖的是spring-core.3.0.5,但是spring-orm和spring-tx依赖了spring-bea ...

  10. Pow(x, n) 位运算总结 典型

    https://leetcode.com/problems/powx-n/ Implement pow(x, n), which calculates x raised to the power n  ...