thinkphp框架下的微信验证、关注回复图文,文本、向用户推送消息、首次登录入库或更新用户资料等

时间:2022-09-24 16:16:04

1.thinkphp框架下的微信验证、关注回复图文,文本、向用户推送消息、首次登录入库或更新用户资料等

2.代码很不规范,以后再改了,先实现了

多图文正在做。。。。。。。。。。。。。。。。。。。

<?php
/*
* 微信端验证
*/
class WechatAction extends Action
{
private $member_nums = 0;
/*
* 验证token | 关注提醒
*/
public function index(){
//file_put_contents('/var/log/test.txt', date('Y-m-d H:i:s',time())."\n",FILE_APPEND);
$store_id = $_GET['sid'];
$this ->store_id = $store_id;
$wxshop_model = M('wxshop');
$token = $wxshop_model ->where("store_id = '$store_id'") ->getField('token');

if(empty($token)) $token = "isempty";
$token = trim($token);
if (!class_exists('SimpleXMLElement')) {
die('SimpleXMLElement class not exist');
}
if (!function_exists('dom_import_simplexml')) {
die('dom_import_simplexml function not exist');
}
import("ORG.Wechat.Wechat");
$weixin = new Wechat($token);
$data = $weixin->request();
$this->data = $data;
//file_put_contents('/var/log/test.txt', $data,FILE_APPEND);

//===不为空则表示接收到微信Post过来的请求【用户关注或取消】
if ($this->data) {

list($content, $type) = $this->reply($data);//将数组赋给变量
// $fp = fopen('/var/log/test.txt','w+');
// fwrite($fp,var_export($content,true));
// fclose($fp);
$weixin->response($content, $type);
}

}
/*
* 消息推送,用户关注时
*/
private function reply($data)
{
$openid = $data['FromUserName']; //用户openid
$store_id = $this ->store_id;//商家id
//file_put_contents('/var/log/test.txt', $store_id.'\n',FILE_APPEND);
//语音功能
if (isset($data['MsgType'])) {
if ('voice' == $data['MsgType']) {
$data['Content'] = $data['Recognition'];
$this->data['Content'] = $data['Recognition'];
}
}
//==监听事件,判断是否关注
if (isset($data['Event'])) {
if ('CLICK' == $data['Event']) {
$data['Content'] = $data['EventKey'];
$this->data['Content'] = $data['EventKey'];
}
if ($data['Event'] == 'SCAN') { //语音
$data['Content'] = $this->getRecognition($data['EventKey']);
$this->data['Content'] = $data['Content'];

} elseif ($data['Event'] == 'MASSSENDJOBFINISH') {


} elseif ('subscribe' == $data['Event']) {
//关注后
//***********************************************/
// 表member_points,member_points_log,member_relation
//1、推送关注提示信息,更改关注标识
//2、更改用户资料
//3、关注时间、关注排名等
//**********************************************/

$rr = $this->_get_appid_appsecret();
$appid = $rr['appid'];
$appsecret = $rr['appsecret'];
$access_token = $this->_get_access_token();
//获取用户信息
$url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid;
$json=json_decode($this->curlGet($url));
$data['is_subscribe'] = $json->subscribe;
//$data['user_name'] = isset($json->nickname)?$json->nickname : '';
$data['wx_name'] = isset($json->nickname)?$json->nickname : '';
$data['sex'] = isset($json->sex)?$json->sex : '';
$data['add_time'] = time();
$data['headimgurl'] = isset($json->headimgurl)?$json->headimgurl : '';
$data['store_id'] = $store_id;
$data['openid'] = $openid;
//==判断是否存在上下级,并推送下级关注提醒消息

$member_mod = M('member');
$member_relation_mod = M('member_relation');
$member_info = $member_mod ->field('id,store_id,openid,is_subscribe') ->where("openid='$openid' AND store_id = '$store_id'") -> find();
//==获取商铺设置的关注
$wx_atteninfo_model = M("wx_atteninfo");
$atteninfo_res = $wx_atteninfo_model ->where("wxshop_id =".$store_id) ->find();

if(empty($member_info) || $member_info === FALSE){//没有此用户则创建
$data['user_name'] = empty($member_info['user_name']) ? '':$json ->nickname;
file_put_contents('/var/log/test.txt', 'fc3'.PHP_EOL,FILE_APPEND);
$res_mem_add = $member_mod -> data($data) ->add();
//===更新关注数 [虚假,只为营销]

$begin_num = $atteninfo_res['begin_num'];
file_put_contents('/var/log/test.txt', $begin_num.PHP_EOL,FILE_APPEND);
if(!empty($begin_num)){
$update['begin_num'] = $begin_num + 1;
$wx_atteninfo_model ->where('wxshop_id='.$data['store_id'])->save($update);
$atteninfo_res = $wx_atteninfo_model ->where("wxshop_id =".$store_id) ->find();

}
}elseif($member_info['is_subscribe'] == '0'){//用户还没有关注则更新
unset($data['store_id']);
$res_mem_update = $member_mod ->where("store_id='$store_id' AND openid='$openid'")-> data($data) ->save();
$uid = $member_info['id'];//当前用户id
//==好友关注三级提醒
for($i=0;$i<3;$i++)
{
$parent_uid = $member_relation_mod ->where("store_id = '$store_id' AND uid = ".$uid) ->getField('parent_uid');//获取用户上级id
if(!empty($parent_uid))
{//如果存在父id,则推送消息

$parent_openid = $member_mod ->where('store_id='.$store_id.' AND id='.$parent_uid.'') ->getField('openid');//获取父类用户openid
$uid = $parent_uid;//查找上级父id
$friend_reply_url = 'http://'.$_SERVER['HTTP_HOST'].'/index.php?m=Member&a=index&sid='.$store_id.'';
if(!empty($atteninfo_res['friend_reply_url'])){
$friend_reply_url = $atteninfo_res['friend_reply_url'];
}
if(!empty($atteninfo_res['friend_reply'])){
$friend_replay = $atteninfo_res['friend_reply'];
}
$this->send(array('friend_reply'=>$friend_replay, 'friend_reply_url'=>$friend_reply_url, 'store_id'=>$store_id,'openid'=>$parent_openid,'appid'=>$appid,'appsecret'=>$appsecret,'nickname'=> $data['wx_name']),'guanzhudaili');
}
}
/*if(!empty($parent_uid))
{//如果存在父id,则推送消息【一级】
$parent_openid = $member_mod ->where('store_id='.$store_id.' AND id='.$parent_uid.'') ->getField('openid');//获取父类用户openid
//file_put_contents('/var/log/test.txt', $member_mod->getLastSql().'\n',FILE_APPEND);
//file_put_contents('/var/log/test.txt', $parent_openid,FILE_APPEND);

$this->send(array('store_id'=>$store_id,'openid'=>$parent_openid,'appid'=>$appid,'appsecret'=>$appsecret,'nickname'=> $data['wx_name']),'guanzhudaili');
}*/
}


//==推送关注公众号的提醒消息

//file_put_contents('/var/log/test.txt', $wx_atteninfo_model->getLastSql().PHP_EOL,FILE_APPEND);

/* $fp = fopen('/var/log/test.txt','w+');
fwrite($fp,var_export($atteninfo_res,true));
fclose($fp);*/
$wxshop_mod = M('wxshop');
$shop_name = $wxshop_mod ->where('store_id='.$store_id) ->getField('name');
if($atteninfo_res !== FALSE){
//查找图文
$wx_article_model = M('wx_article');
$rts = $wx_article_model ->where("wxshop_id ='$store_id' AND is_subscribe ='1'") -> find();
//file_put_contents('/var/log/test.txt', $wx_article_model->getLastSql().PHP_EOL,FILE_APPEND);

if($rts === FALSE || $rts['atteninfo_res']=='0'){
return array('感谢您关注('.$shop_name.')商城', 'text');
}else{
$type = $rts['type'];
if($type=="txt"){ //文本信息
$begin_num = $atteninfo_res['begin_num'];
if(!empty($begin_num) && is_numeric($begin_num) && $begin_num > 0){
$rts['content'] = '亲,['.$data['wx_name'].']欢迎您关注['.$shop_name.'],您是第['. $atteninfo_res['begin_num'].']会员'. $atteninfo_res['atten_reply'];
}
return array($rts['content'], 'text');
}else{
//回复图文信息
//$url = $rts['art_url'];//文章的链接地址
$id = $rts['article_id'];
$url = "http://".$_SERVER["HTTP_HOST"]."/".'index.php?m=Index&a=WxArticle&article_id='.$id;//文章的链接地址
if(empty($atteninfo_res['atten_reply_url'])){
$data['url'] = $url;
}else{
$data['url'] = $atteninfo_res['atten_reply_url'];
}
$img = "http://".$_SERVER["HTTP_HOST"]."/".$rts['article_img'];
$about = $atteninfo_res['atten_reply'];
$title = $rts['article_title'];
$data['title'] = $title;
$data['keyword'] = $about;
$data['picurl'] = $img;

$begin_num = $atteninfo_res['begin_num'];
//file_put_contents('/var/log/test.txt',$begin_num.PHP_EOL,FILE_APPEND);
if(!empty($begin_num) && is_numeric($begin_num) && $begin_num > 0){
//file_put_contents('/var/log/test.txt',$begin_num.PHP_EOL,FILE_APPEND);
$data['keyword'] = '亲,['.$data['wx_name'].']欢迎您关注['.$shop_name.'],您是第['. $atteninfo_res['begin_num'].']会员,'.$data['keyword'];
}
return array(array(array($data['title'], $data['keyword'], $data['picurl'], $data['url'])), 'news');
}
}
}else{
//file_put_contents('/var/log/test.txt', $wx_article_model->getLastSql().PHP_EOL,FILE_APPEND);
return array('感谢您关注('.$shop_name.')商城', 'text');
}

if ($follow_data['home'] == 1) {
return $this->keyword($follow_data['keyword']);
} else {
return array(html_entity_decode($follow_data['content']), 'text');
}

} elseif ('unsubscribe' == $data['Event']) { //取消关注
$member_mod = M('member');
$data['is_subscribe'] = '0';
$member_mod ->where("store_id ='$store_id' AND openid='$openid'") -> data($data)->save();
} elseif ($data['Event'] == 'LOCATION') { //自动获取位置回复
//return array('LOCATION', 'text');
}
}
return $this->keyword($data['Content']);
}
/*
* 推送消息到公众号
*/
public function send($rts=array(),$type="")
{
if(empty($rts['openid'])) return;
$access_token = $this->_get_access_token();
//==好友关注数(根据后台推广层级而定)只算三层
$openid = $rts['openid'];
$member_relation_mod = M('member_relation');
$member_mod = M('member');
$uid = $member_mod ->where("openid='$openid'") ->getField('id');//推送用户的id
$one_level_list = $member_relation_mod ->field('parent_uid,uid,store_id') ->where("parent_uid ='$uid'") ->select();//一级朋友列表
if(is_array($one_level_list) && count($one_level_list) >0){
$one_level_nums = count($one_level_list);
$this ->member_nums += $one_level_nums;//一级朋友数量
if($one_level_nums >0){
foreach ($one_level_list as $key=>$val){
$nums_list = $member_relation_mod ->field('parent_uid,uid,store_id') ->where('parent_uid ='.$val['uid'])->select();

$tuo_num_list = count($nums_list);//临时变量
if(is_array($nums_list) && count($nums_list) >0){
$this ->member_nums += count($nums_list);//二级朋友数量
foreach($nums_list as $key =>$val){
$three_list = $member_relation_mod ->field('parent_uid,uid,store_id') ->where('parent_uid='.$val['uid']) ->select();//三级朋友列表
if(is_array($three_list) && count($three_list) >0 ){
$this ->member_nums +=count($three_list);//三级朋友数量
}
}
}
}
}
}
$data = $this->_get_send_con($rts,$type);
//file_put_contents('/var/log/test.txt', $data.'\n',FILE_APPEND);
$rt=$this->curlPost('https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token,$data,0);

}
public function _get_send_con($rt=array(),$ty='')
{
/*$fp = fopen('/var/log/test.txt','w+');
fwrite($fp,var_export($rt,true));
fclose($fp); */

$data = array();
switch($ty){
case 'guanzhu':
$openid = $rt['openid'];
$str = '你的好友['.$rt['nickname'].']已经关注你啦;\n\n服务类型:关注已返积分\n提交时间:'.date('Y-m-d H:i:s').'\n\n备注:再接再厉哦!返积分详情点击进入查看!';
$data='{"touser": "'.$openid.'","msgtype": "news","news": {"articles": [{"title": "服务申请提交成功", "description": "'.$str.'","url":"'.str_replace('api','m',ADMIN_URL).'user.php?act=mypoints"}]}}';
break;
case 'guanzhudaili':
$openid = $rt['openid'];//服务类型:用户关注下级已返积分\n
//$str = '你的好友['.$rt['nickname'].']同学已经关注你啦;\n\n提交时间:'.date('Y-m-d H:i:s').'\n\n备注:他还需要购买你才有收入哦!';
//$str = '亲,【'.$rt['nickname'].'】欢迎您关注【'.$rt['name'].'】,您是第【'.$rt['begin_num'].'】个会员,【我们真诚的为您提供最优质的产品和服务】';
// $str = '恭喜您, 您的朋友['.$rt['nickname'].']已关注您,您共有['.$this->member_nums.']位朋友,[朋友越多,奖励越多1、超过100个朋友,奖励100元话费2、超过1000个奖励IWATCH3、超过10000个奖励一台IPHONE6,朋友加油]';
$str = '恭喜您, 您的朋友['.$rt['nickname'].']已关注您,您共有['.$this->member_nums.']位朋友.'.$rt['friend_reply'].'';
$data='{"touser": "'.$openid.'","msgtype": "news","news": {"articles": [{"title": "分享创造价值", "description": "'.$str.'","url":"'.$rt['friend_reply_url'].'"}]}}';
break;
}
//file_put_contents('/var/log/test.txt', $data.'\n',FILE_APPEND);
return $data;
}
public function get_access_token()
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx86526eefe97f5541&secret=475c208e114c80684afaa2c19d74303e";
$data = json_decode(file_get_contents($url),true);
if($data['access_token'])
{
return $data['access_token'];
}
else
{

return "获取access_token错误";
}
}


public function get_jsapi_ticket()
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx86526eefe97f5541&secret=475c208e114c80684afaa2c19d74303e";

$data = json_decode(file_get_contents($url),true);

if($data['access_token'])
{
$url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$data['access_token']."&type=jsapi";
$data = json_decode(file_get_contents($url),true);
if($data['ticket'])
{
return $data['ticket'];
}
else
{
return "获取jsapi_ticket错误";
}
}
else
{

return "获取access_token错误";
}
}

/**
* 作用:产生随机字符串,不长于32位
*/
public 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;
}
/*
* 获取appid、appsecret
*/
public function _get_appid_appsecret(){
$wxshop_model = M('wxshop');

$store_id = $this -> store_id;
//$store_id = '2';//测试
$result = $wxshop_model -> where('store_id='.$store_id) ->field('store_id,appid,appsecret') ->find();

$res['appid'] = $result['appid'];
$res['appsecret'] = $result['appsecret'];
return $res;
}
/*
* 获取access_token
*/
public function _get_access_token(){

$res = $this->_get_appid_appsecret();
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$res['appid'].'&secret='.$res['appsecret'];
$con = $this->curlGet($url);
$json=json_decode($con);
$access_token = $json->access_token; //获取 access_token

return $access_token;
}
/*
* curl提交
*/
public function curlGet($url)
{
$ch = curl_init();
$header = "Accept-Charset: utf-8";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//curl_setopt($ch, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
//curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$temp = curl_exec($ch);
return $temp;
}
/*
* post提交
*/
public function curlPost($url, $data,$showError=1){
$ch = curl_init();
$header = "Accept-Charset: utf-8";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$tmpInfo = curl_exec($ch);
$errorno=curl_errno($ch);
if ($errorno) {
return array('rt'=>false,'errorno'=>$errorno);
}else{
$js=json_decode($tmpInfo,1);
if (intval($js['errcode']==0)){
return array('rt'=>true,'errorno'=>0,'media_id'=>$js['media_id'],'msg_id'=>$js['msg_id']);
}else {
if ($showError){
return array('rt'=>true,'errorno'=>10,'msg'=>'发生了Post错误:错误代码'.$js['errcode'].',微信返回错误信息:'.$js['errmsg']);
}
}
}
}
}