<?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. PHP记录商品历史纪录

    /* 记录浏览历史 */ if (!empty($_COOKIE['history'])) { if(stripos($_COOKIE['history'].',',$goods_id.',')=== ...

  2. var和dynamic的应用 var、动态类型 dynamic 深入浅析C#中的var和dynamic ----demo

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  3. HDU 1160 FatMouse&#39;s Speed(DP)

    题意  输入n个老鼠的体重和速度   从里面找出最长的序列  是的重量递增时速度递减 简单的DP  令d[i]表示以第i个老鼠为所求序列最后一个时序列的长度  对与每一个老鼠i  遍历全部老鼠j  当 ...

  4. RabbitMQ通过shovel插件迁移数据

    前言 生产环境中会遇到RabbitMQ数据迁移的场景,例如:切换云服务厂商.不同Region之间数据迁移.新搭建RabbitMQ实例,数据需要同步至新的RabbitMQ实例. 前提条件: 源Rabbi ...

  5. Android 4.4.2 动态加入JNI库方法记录 (二 app应用层)

    欢迎转载,务必注明出处:http://blog.csdn.net/wang_shuai_ww/article/details/44458553 源代码下载地址:http://download.csdn ...

  6. VC2010 利用 def 文件生成 dll 文件的方法

    近期有个需求,要生成一个dll 文件.文件里的函数都是採用 stdcall 函数调用约定,可是不希望函数名被修饰(add 被修饰成 add@8). 这时就要用def 文件了. 比方我有以下两个函数: ...

  7. 如何使用jQuery向asp.net Mvc传递复杂json数据

    jQuery提供的ajax方法能很方便的实现客户端与服务器的异步交互,在asp.net mvc 框架使用jQuery能很方便地异步获取提交数据,给用户提供更好的体验! 调用jQuery的ajax方法时 ...

  8. JavaScript学习14:表单处理

    什么是表单? 在HTML中,表单是由<form>元素来表示的.而在JavaScript中,表单相应的则是HTMLFormElement类型.HTMLFormElement继承了HTMLEl ...

  9. SoapUI中读取Office365邮件

    常见邮件服务一般使用IMAP邮件访问协议,如果你所在公司更换到Office 365则需要另一个组件. Office 365使用的是Exchange Server电子邮件服务组件,需要微软的Jar包来支 ...

  10. java的Date日期使用

    import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; imp ...