1. 程式人生 > >php微信自動發紅包

php微信自動發紅包

sae open client function 調用 curl muse 金額 log_file

<?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微信自動發紅包