PHP自动发红包代码示例
<?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资料