<?php
namespace app\weixin\controller;
use think\Db;
use think\Controller;
use think\Cache;
define('TOKEN', 'walaibao');
class Wx extends Common
{
public $ToUserName;
public $FromUserName;
public $MsgType;
function __construct()
{
$this->appid ='*************';
$this->secrect ='********';
$accessToken=Cache::get('accessToken');
if($accessToken){
$this->accessToken = $accessToken;
}else{
$this->accessToken = $this->getToken($this->appid, $this->secrect);
Cache::set('accessToken',$this->accessToken ,7200);
}
}
public function wx()
{
if (isset($_GET["echostr"]))
{
$echoStr = $_GET["echostr"];
if($this->checkSignature()){
echo $echoStr;
exit;
}
}else
{
$this->response();
}
}
public function checkSignature()
{
if (!defined("TOKEN"))
{
throw new Exception("TOKEN is not defined!");
}
$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;
}
}
public function response()
{
$postStr=$GLOBALS["HTTP_RAW_POST_DATA"];
if(!empty($GLOBALS["HTTP_RAW_POST_DATA"])) {
$postStr=simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$this->ToUserName=$postStr->ToUserName;
$this->FromUserName=$postStr->FromUserName;
$this->MsgType=$postStr->MsgType;
$data=$this->dealdata($postStr);
echo $data;
}else{
echo '';
}
}
public function dealdata($postStr){
switch ($this->MsgType) {
case 'event':
$result=$this->receiveEvent($postStr);
break;
case 'text':
$result=$this->receiveText($postStr);
break;
default:
# code...
break;
}
return $result;
}
public function receiveEvent($postStr){
$event=$postStr->Event;
switch($event){
case "subscribe":
$Content='欢迎关注';
if (isset($postStr->EventKey)){
$scnce_id=substr($postStr->EventKey,8);
db('buyuserinfo')->where('openid',$postStr->FromUserName)->update(['activity_id'=>$scnce_id]);
$Content = "关注二维码场景 ".$scnce_id;
}
$result= $this->transmitsubscribe($postStr,$Content);
break;
case "SCAN";
$scnce_id=$postStr->EventKey;
$Content = "关注二维码场景 ".$scnce_id;
db('buyuserinfo')->where('openid',$postStr->FromUserName)->update(['activity_id'=>$scnce_id]);
$result= $this->transmitsubscribe($postStr,$Content);
break;
case "unsubscribe":
$result= $this->transmitunsubscribe($postStr,$Content);
break;
case 'CLICK':
$content=$postStr->EventKey;
if($content=='CONNECT_US'){
$Content='4000992015';
$result=$this->transmitText($postStr,$Content);
}
break;
}
return $result;
}
public function receiveText($postStr){
$this->save_receive_txt($postStr);
$Content='已收到您的留言';
$result=$this->transmitText($postStr,$Content);
return $result;
}
public function save_receive_txt($obj){
$content=$obj->Content;
$content=$this->parseXml($content);
$openid=$obj->FromUserName;
$user_check=db('wx_number')->where('openid',$openid)->field('id')->find();
$arr['wx_openid']=$openid;
$arr['msg']=$content['Content'];
$arr['ctime']=time();
$arr['orgin_id']='1';
db('wx_send_msg')->insert($arr);
}
public function transmitText($obj,$Content){
$str='
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>';
$result= sprintf($str,$this->FromUserName,$this->ToUserName,time(),$Content);
return $result;
}
public function transmitnews($obj,$Content){
if (!is_array($Content)) {
return;
}
$item='
<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>';
$item_str='';
foreach ($Content as $v) {
$item_str.=sprintf($item,$v['Title'],$v['Description'],$v['PicUrl'],$v['Url']);
}
$xml='<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount><![CDATA[%s]]></ArticleCount>
<Articles>%s</Articles>
</xml>';
$result = sprintf($xml, $this->FromUserName, $this->ToUserName, time(),count($Content),$item_str);
return $result;
}
public function transmitsubscribe($obj,$Content){
$openid = $obj->FromUserName;
$str='
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>';
$result= sprintf($str,$this->FromUserName,$this->ToUserName,time(),$Content);
return $result;
}
public function transmitunsubscribe($obj,$Content){
$openid = $obj->FromUserName;
}
public function createuserinfo($openid)
{
$user_check=db('wx_number')->where('openid',$openid)->find();
if($user_check){
db('wx_number')->where('openid',$openid)->update(['is_subscribe'=>'1','subscribetime'=>time()]);
}else{
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->accessToken . "&openid=" . $openid;
$user= $this->request_get($url);
$user = json_decode($user,true);
$nickname=urlencode($user['nickname']);
$users = array(
'openid' =>$openid,
'nickname' =>$nickname,
'faceimgurl' =>$user['headimgurl'],
'sex' =>$user['sex'],
'status' => 1,
'is_subscribe'=>'1',
'orgin_id'=>'1',
'ctime'=>$user['subscribe_time'],
'subscribetime' =>$user['subscribe_time']
);
db('wx_number')->insert($users);
}
}
protected function getToken($appid, $appsecret)
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
$token = $this->request_get($url);
$token = json_decode(stripslashes($token));
$arr = json_decode(json_encode($token), true);
$access_token = $arr['access_token'];
return $access_token;
}
public function piliang_x(){
$access_token=$this->getToken();
$url="https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->accessToken ;
$openid_list=$this->request_get($url);
$json_info=json_decode($openid_list,true);
$user_list=$json_info['data']['openid'];
$user_list[]=$json_info['next_openid'];
foreach($user_list as $v){
$user_check=db('wx_number')->where('openid',$v)->field('id')->find();
if($user_check){
continue;
}
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->accessToken . "&openid=" . $v;
$user= $this->request_get($url);
$user = json_decode($user,true);
$nickname=urlencode($user['nickname']);
$users = array(
'openid' =>$v,
'nickname' =>$nickname,
'faceimgurl' =>$user['headimgurl'],
'sex' =>$user['sex'],
'status' => 1,
'is_subscribe'=>'1',
'ctime'=>$user['subscribe_time'],
'subscribetime' =>$user['subscribe_time']
);
db('wx_number')->insert($users);
}
}
public function menuset(){
$menu_son[0]['type']='view';
$menu_son[0]['name']='兑奖中心';
$menu_son[0]['url']="****************";
$menu_send['button']=$menu_son;
$post_url= 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$this->accessToken;
$result=$this->request_post($post_url,json_encode($menu_send,JSON_UNESCAPED_UNICODE));
$result=json_decode($result,true);
var_dump($result);
}
function request_post($url = '', $param = '')
{
if (empty($url) || empty($param)) {
return false;
}
$postUrl = $url;
$curlPost = $param;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $postUrl);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function request_get($url = '')
{
if (empty($url)) {
return false;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function parseXml($xmls)
{
$array = [];
foreach ($xmls as $key => $xml) {
$count = $xml->count();
if ($count == 0) {
$res = (string) $xml;
} else {
$res = parseXml($xml);
}
$array[$key] = $res;
}
return $array;
}
}
代码演示:http://github.crmeb.net/u/LXT