<?php

namespace App\Http\Controllers\Web\Gznumber;
use App\Events\LoginEvent;
use App\Services\Common\User\UserAccountService;
use App\Services\Web\BaseService;
use GuzzleHttp\Utils;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

use App\Exceptions\Common\CaptchaException;
use App\Services\Common\SmsService;
use App\Services\Web\CacheService;
use App\Libraries\Verification\Sms;
use Illuminate\Support\Str;



use Illuminate\Foundation\Auth\User;
use App\Services\Common\Auth\LoginService;

define('TOKEN', 'TOKEN');

class GznumberController extends Controller
{
const ERROR_TIMES = 5;
const SEND_TIMES = 5;
const EXPIRE_TIME = 300;

protected $appid = 'wx2929f30b2bcf14d4';
protected $secret = 'c7cb108d79245d57eeb5f3bf8924897a';
//测试号
/*protected $appid = 'wx2929f30b2bcf14d4';
protected $secret = 'c7cb108d79245d57eeb5f3bf8924897a';*/

/**
* 自定义方法,用于微信访问验证开发者身份
*
* @param Request $request
* @return array|null|string
*/
public function wxtoken(Request $request)
{

// 验证消息来自微信服务器
if($request->method()=='GET'){
$signature = $request->input('signature');
$timestamp = $request->input('timestamp');
$nonce = $request->input('nonce');
$echoStr = $request->input('echostr');
if ($this->checkSignature($signature, $timestamp, $nonce)) {
ob_end_clean(); //必须清空缓冲区
return $echoStr;
} else {
return 'Token verification failed.';
}
} elseif ($request->method()=='POST') {

// 事件处理 关注/取消事件等
$postStr = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");

$payChannel='yyyyyy';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . Utils::jsonEncode($postStr) . PHP_EOL,
FILE_APPEND
);
if (!empty($postStr)) {
$postObj = simplexml_load_string($postStr);

$payChannel='bbbbbb';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . Utils::jsonEncode($postObj) . PHP_EOL,
FILE_APPEND
);

$Event = strtolower($postObj->Event);

$openid = $postObj->FromUserName;
$RX_TYPE = trim($postObj->MsgType);


switch ($RX_TYPE) {
case "text":
$resultStr = $this->handleText($postObj);
break;
case "event":
// 事件推送
$resultStr = $this->handleEvent($postObj);
break;
default:

$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";

$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
$payChannel='users';


$msgType = "text";
$contentStr = "Hi,欢迎关注跨境知道,360万新外贸人的资源平台!.\"\n\".
这里有最新的跨境电商行业资讯、干货、运营工具等等,让跨境更简单!
最后强调下.\"\n\".
1、加入跨境卖家交流群,请回复加群”.\"\n\".
2、开店业务,请回复开店”.\"\n\".
3、线上选品,请回复选品圈”.\"\n\".
4、优惠购买UPC请戳链接:https://m.ikjzd.com/upc.\"\n\".
5、观看最新直播,请回复直播”.\"\n\".
6、商务合作请添加微信:zybigbig
好了,不说了,我要去为卖家们寻找出单神器了";

$payChannel='uuuuuuu';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . Utils::jsonEncode(333) . PHP_EOL,
FILE_APPEND
);

$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;

$resultStr = "Unknow msg type: " . $RX_TYPE;
break;
}
echo $resultStr;
//die();

if($Event=='subscribe'){

//欢迎关注,加入数据库
//redis 获取token
$access_token=$this->check_access_token_is_effective();
//带参数的二维码接收
$scenes = json_decode($postObj->EventKey, true);

$userinfo = $this->getUserinfo($openid, $access_token);

//首次关注
$qr_scene_str = json_decode($userinfo['qr_scene_str'],true);

$payChannel='uuuu';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . Utils::jsonEncode($userinfo) . PHP_EOL,
FILE_APPEND
);


$mtype = $qr_scene_str['mtype'];
//二维码传过来得参数值
$scene_id = $qr_scene_str['scene_id'];


if($userinfo['openid']){

$qresult=DB::connection('mysql_user')->table('user_account')->where('openid',$userinfo['openid'])->value('openid');

$payChannel='ccccc';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . Utils::jsonEncode($qresult) . PHP_EOL,
FILE_APPEND
);

//这里应该这样做,当找到这个opendid 不存的时候就是加,否则的会,就修改,然后就继续改个 刚用的id给他,id 是不停的变化的

if(is_null($qresult)){

$payChannel='kongzhi';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . Utils::jsonEncode(55555) . PHP_EOL,
FILE_APPEND
);

//用户编码 暂且空
$datauser['user_code']='kjzd_' . createUuid(Str::random(5));
$datauser['username']=$userinfo['nickname'];
$datauser['password']='$2a$10$Mss5QtjwNZF0FXuKsTXQ1uQQ6YfvC1diSz5lmSeL0ECvBRs.0rzCu';
$datauser['nickname']=$userinfo['nickname'];
$datauser['avatar']=$userinfo['headimgurl'];
$datauser['sex']=$userinfo['sex'];
$datauser['email']='null';
//不能相同
$datauser['mobile']=$this->getRandomStr();
$datauser['user_type']=0;
$datauser['company_id']=0;
$datauser['register_ip']=$this->get_client_ip();
$usetime2=time();
$datauser['register_time']=date('Y-m-d H:i:s',$usetime2);
$datauser['source']=1;
$datauser['status']=1;
$datauser['user_desc']='2221';
$datauser['invited_code']='221';
$usetime3=time();
$datauser['create_time']=date('Y-m-d H:i:s',$usetime3);
$datauser['update_time']=date('Y-m-d H:i:s',$usetime3);
$datauser['update_flag']=1;
$datauser['country']=$userinfo['country'];
$datauser['province']=$userinfo['province'];
$datauser['city']=$userinfo['city'];
//$datauser['gz_id']=$scene_id;

//成功的话,就给创建另两张表 //userid

$userzhi=DB::connection('mysql_user')->table('user')->insertGetId($datauser);
//var_dump($userzhi);die();

$data['platform']=2;
$data['user_id']=$userzhi;
$data['openid']=$userinfo['openid'];
$data['unionid']=$userinfo['openid'];
$data['avatar']=$userinfo['headimgurl'];
$data['nickname']=$userinfo['nickname'];
$data['gender']=$userinfo['sex'];
$data['language']='zn';
$data['city']=$userinfo['city'];
$data['province']=$userinfo['province'];
$data['country']=$userinfo['country'];
$data['country_code']=0;
$data['mobile']='null';
$usetime1=time();
$data['create_time']=date('Y-m-d H:i:s',$usetime1);
$data['gz_id']=$scene_id;

$whereAry = [];
if(isset($scene_id)){
$whereAry[] = ['account_id', '=', ''.$scene_id.''];
}


$zhiresult=DB::connection('mysql_user')->table('user_account')->insert($data);

}else{

$payChannel='youzhi';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . Utils::jsonEncode(66666) . PHP_EOL,
FILE_APPEND
);

$whereddAry = [];
if(isset($scene_id)){
$whereddAry[] = ['openid', '=', ''.$qresult.''];
}
$usetime4=time();
$datadd['update_time']=date('Y-m-d H:i:s',$usetime4);
$datadd['gz_id']=$scene_id;
$xiugai=DB::connection('mysql_user')->table('user_account')->where($whereddAry)->update($datadd);

}

}
}else{

$access_token=$this->check_access_token_is_effective();
//带参数的二维码接收
$scenes = json_decode($postObj->EventKey, true);
$userinfoed = $this->getUserinfo($openid, $access_token);
$qresult=DB::connection('mysql_user')->table('user_account')->where('openid',$userinfoed['openid'])->value('openid');
//二维码传过来得参数值
$scene_id = $scenes['scene_id'];
$whereudAry = [];
if(isset($scene_id)){
$whereudAry[] = ['openid', '=', ''.$qresult.''];
}
$usetime5=time();
$dataud['update_time']=date('Y-m-d H:i:s',$usetime5);
$dataud['gz_id']=$scene_id;
$xiugaiu=DB::connection('mysql_user')->table('user_account')->where($whereudAry)->update($dataud);

}

// 微信消息类型
/*$RX_TYPE = trim($postObj->MsgType);*/


} else {
echo "null";
exit;
}
}
}



public static function getRandomStr($length = 11) {

//$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
$password = '';
for($i = 0; $i < $length; $i++){
//这里提供两种字符获取方式
//第一种是使用 substr 截取$chars中的任意一位字符;
//第二种是取字符数组 $chars 的任意元素
//$password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
$password .= $chars[mt_rand(0, strlen($chars) - 1)];
}
return $password;
}


//当前ip
function get_client_ip() {
$ip = $_SERVER['REMOTE_ADDR'];
if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
foreach ($matches[0] AS $xip) {
if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
$ip = $xip;
break;
}
}
}
return $ip;
}


//openid 获取用户的信息
private function getUserinfo($openid, $access_token) {

if ($access_token && $openid) {
//$url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";

$userinfo = $this->get_curl($url);

return $userinfo;
} else {
return array("code" => "userinfo_null");
}
}


function get_curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}



////判断存入的token 是否有效
private function check_access_token_is_effective()
{
$access_token = $this->get_access_token_from_t_redis();
$url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$access_token;
$result = $this->https_request($url);
$data = json_decode($result,true);
//当直接返回的是 $data['errcode']
if(isset($data['errcode'])){
$array=array(42001,41001,40001);
$data['errcode'];
if(in_array($data['errcode'],$array)){
//重新生成一个token
$access_token = $this->getToken();
//写入
$access_token=$this->store_access_token_in_t_redis($access_token);

return $access_token;
}

}else{
//取出来token
$access_token = $this->get_access_token_from_t_redis();
return $access_token;
}


//ip 都为空的时候
if($data['ip_list']!==''){
$array=array(42001,41001);
$data['errcode'];
if(in_array($data['errcode'],$array)){
//重新生成一个token
$access_token = $this->getToken($this->appid,$this->secret);
$access_token=$this->store_access_token_in_t_redis($access_token);
return $access_token;
}else{
return $access_token;
}

}else{
//重新生成一个token
$access_token = $this->getToken();
//存入
$access_token=$this->store_access_token_in_t_redis($access_token);
return $access_token;
}

}

/**
* https请求
* @param $url
* @return mixed
*/
private function https_request($url)
{
$ch = curl_init(); // 创建句柄
curl_setopt($ch, CURLOPT_URL, $url); // 通过url获取数据
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 跳过证书验证
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是
$output = curl_exec($ch);
curl_close($ch);
return $output;
}


/**
* redis里获取access_token
* @return string
*/
private function get_access_token_from_t_redis()
{
$redis = app("redis.connection");
$qutoken=$redis->get('t_redis_access_token');
return $qutoken;
}


/**
* access_token存入到 Tredis
* @param $access_token
*/
private function store_access_token_in_t_redis($access_token)
{
$redis = app("redis.connection");
$access_token=$redis->set('t_redis_access_token' , $access_token);
}



/**
* 微信文本消息
* @param $postObj
*/
public function handleText($postObj)
{
$payChannel='tttttuuuuuuu';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . Utils::jsonEncode($postObj) . PHP_EOL,
FILE_APPEND
);

$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
if (!empty($keyword)) {

/*$msgType = "text";
$contentStr = "欢迎您关注";

$payChannel='uuuuuuu';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . Utils::jsonEncode(333) . PHP_EOL,
FILE_APPEND
);

$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;*/

if($keyword=='开店'){

$payChannel='kaidian';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . Utils::jsonEncode(333) . PHP_EOL,
FILE_APPEND
);

//图片消息模板
$imageTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>";

//图片素材ID
$media_id = "k-L04_rfuutMv5lOtTtFg5Pyz7mLCx_lttvkljZxk_qVGgcb2DSLpwt9LDiaI9TG";
$msgType = "image"; //图片类型
$time=time();
$resultStr = sprintf($imageTpl,$fromUsername,$toUsername,$time,$msgType,$media_id);
echo $resultStr;

$payChannel='tttr';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . ($resultStr) . PHP_EOL,
FILE_APPEND
);


}elseif ($keyword=='选品圈'){
//选品圈
$imageTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>";
// 开店 ERHXNTs93zlyJynnFHLq5h6bdH37bP681tx-S7_eZtorNyDxE_xkDbfl6RTXqH5l
// 1 加群 qpYJIzAwlNGh7fftiipSqxwLFa9_xKfx7Fd7DA_bU06oVfJXBQ0sRHjCzVojk4_h
//3 选品圈 qpYJIzAwlNGh7fftiipSq-DP_LvWx4Pu9whDpPS9zB02NehVVPidWN7fyzsw247e

//图片素材ID
$media_id = "k-L04_rfuutMv5lOtTtFg5Pyz7mLCx_lttvkljZxk_qVGgcb2DSLpwt9LDiaI9TG";
$msgType = "image"; //图片类型
$time=time();
$resultStr = sprintf($imageTpl,$fromUsername,$toUsername,$time,$msgType,$media_id);
echo $resultStr;
}elseif ($keyword=='直播'){

$msgType = "text";
$contentStr = "最新直播观看,请戳https://www.ikjzd.com/live";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;

}elseif ($keyword=='weixinma'){
//发送客服的二维码
$imageTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>";
//图片素材ID
$media_id = "k-L04_rfuutMv5lOtTtFg5Pyz7mLCx_lttvkljZxk_qVGgcb2DSLpwt9LDiaI9TG";
$msgType = "image"; //图片类型
$time=time();
$resultStr = sprintf($imageTpl,$fromUsername,$toUsername,$time,$msgType,$media_id);
echo $resultStr;

}else{
//开店
$imageTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>";

//图片素材ID
$media_id = "k-L04_rfuutMv5lOtTtFg5Pyz7mLCx_lttvkljZxk_qVGgcb2DSLpwt9LDiaI9TG";
$msgType = "image"; //图片类型
$time=time();
$resultStr = sprintf($imageTpl,$fromUsername,$toUsername,$time,$msgType,$media_id);
echo $resultStr;
}

} else {
echo "lalala";
}
}

/**
* 获取时间消息并解析相应参数
* 提供数据简单推送(自动回复)
* @param $object
*
* @return string
*/
public function handleEvent($object)
{
$payChannel='hhhahahahah';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . Utils::jsonEncode($object) . PHP_EOL,
FILE_APPEND
);

$fromUsername = $object->FromUserName;
$toUsername = $object->ToUserName;

$EventKeytrim=trim($object->EventKey);//点击自定义菜单click时的key

$time = time();
$textTpl="<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>";
//调用上传素材的方法$this->uploadImg()
//判断点击自定义菜单clickkey值与自定义菜单的key是否相同
if($EventKeytrim=='qrcode001'){
$mediaid='k-L04_rfuutMv5lOtTtFg5Pyz7mLCx_lttvkljZxk_qVGgcb2DSLpwt9LDiaI9TG';
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $mediaid);
return $resultStr;
}
if($EventKeytrim=='qrcode000'){
$mediaid='k-L04_rfuutMv5lOtTtFg5Pyz7mLCx_lttvkljZxk_qVGgcb2DSLpwt9LDiaI9TG';
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $mediaid);
return $resultStr;
}
if($EventKeytrim=='kaidian'){
$mediaid='k-L04_rfuutMv5lOtTtFg5Pyz7mLCx_lttvkljZxk_qVGgcb2DSLpwt9LDiaI9TG';
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $mediaid);
return $resultStr;
}

if($EventKeytrim=='shangwu'){
$mediaid='k-L04_rfuutMv5lOtTtFg5Pyz7mLCx_lttvkljZxk_qVGgcb2DSLpwt9LDiaI9TG';
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $mediaid);
return $resultStr;
}


$contentStr = "";
//事件KEY值,qrscene_为前缀,后面为二维码的参数值
$EventKey = explode('_', $object->EventKey);
//二维码的ticket
$Ticket = $object->Ticket;
switch ($object->Event) {
case "subscribe":
// 关注
if(!empty($EventKey[0]) || !empty($Ticket)){
// 扫描带参数二维码,未关注推送
$toUser = $object->ToUserName;
// 用户openid
$foUser = (string)$object->FromUserName;
$msgType = 'text';
$createTime = time();

$content = "Hi,欢迎关注跨境知道,360万新外贸人的资源平台!\n这里有最新的跨境电商行业资讯、干货、运营工具等等,让跨境更简单!\n最后强调下\n1、加入跨境卖家交流群,请回复加群\n2、开店业务,请回复开店\n3、线上选品,请回复选品圈\n4、优惠购买UPC请戳链接:https://m.ikjzd.com/upc\n5、观看最新直播,请回复直播\n6、商务合作请添加微信:zybigbig\n\n\n好了,不说了,我要去为卖家们寻找出单神器了";
$tempyi = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$tempyi = sprintf($tempyi,$foUser,$toUser,$createTime,$msgType,$content);
echo $tempyi;
break;


$content = '扫描带参数二维码,未关注推送'.$EventKey[0].'++'.$Ticket.'++'.$EventKey[1].'++'.$EventKey[2];
/*$array = array(
array(
"title"=>"XXX",
"description"=>"XXXXXXX",
"picUrl"=>"https://s.yun-live.com/images/20200707/fc3bdd153e6136c058b0214fe8ab05d3.jpg",
"url"=>"httpsXXX.com/",
),
array(
"title"=>"XXX",
"description"=>"XXXXXXX",
"picUrl"=>"https://s.yun-live.com/images/20200707/fc3bdd153e6136c058b0214fe8ab05d3.jpg",
"url"=>"httpsXXX.com/",
),
array(
"title"=>"XXX",
"description"=>"XXXXXXX",
"picUrl"=>"https://s.yun-live.com/images/20200707/fc3bdd153e6136c058b0214fe8ab05d3.jpg",
"url"=>"httpsXXX.com/",
),
);

$template = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>".count($array)."</ArticleCount>
<Articles>";

foreach ($array as $key => $v) {
$template .= "<item>
<Title><![CDATA[".$v['title']."]]></Title>
<Description><![CDATA[".$v['description']."]]></Description>
<PicUrl><![CDATA[".$v['picUrl']."]]></PicUrl>
<Url><![CDATA[".$v['url']."]]></Url>
</item>";
}


$template.= "</Articles></xml>";

$temp = sprintf($template,$foUser,$toUser,$createTime,$msgType,$content);
echo $temp;*/


}else{
// 普通关注
$toUser = $object->ToUserName;
$foUser = (string)$object->FromUserName; // 用户openid
$msgType = 'text';
$createTime = time();
$content = '欢迎关注我的微信公众平台111'.$EventKey[0].'++'.$Ticket.'++'.$EventKey[1].'++'.$EventKey[2].json_encode($object);;
$temp = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$temp = sprintf($temp,$foUser,$toUser,$createTime,$msgType,$content);
echo $temp;
}

break;
case "SCAN":
$toUser = $object->ToUserName;
$foUser = $object->FromUserName; // 用户openid
$msgType = 'text';
$createTime = time();
$content = '欢迎回来,登录成功!';
$huitemp = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$temp = sprintf($huitemp,$foUser,$toUser,$createTime,$msgType,$content);
echo $temp;
break;
case "unsubscribe": //取消订阅
// $contentStr = "您已关注过,谢谢!".json_encode($object);
// $openid = (string)$object->FromUserName; //数据类型转换为字符串,mmp这个问题找了好久
// $refer_id = explode('_', $object->EventKey); //$object->EventKey返回的是qrsence_123这种类型
// $this->createuserinfo($openid, $refer_id[0]);//获取用户信息
$toUser = $object->ToUserName;
$foUser = $object->FromUserName; // 用户openid
$msgType = 'text';
$createTime = time();
$content = '您已关注过2222,谢谢!'.json_encode($object);
$temp = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$temp = sprintf($temp,$foUser,$toUser,$createTime,$msgType,$content);
echo $temp;
break;
}
$resultStr = $this->responseText($object, $contentStr);
return $resultStr;
}


/**
* 消息回复模板
* @param $object
* @param $content
* @param int $flag
*
* @return string
*/
public function responseText($object, $content, $flag = 0)
{
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%d</FuncFlag>
</xml>";
$resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
return $resultStr;
}

/**
* 微信官方提供的验签方法
*
* @param $signature
* @param $timestamp
* @param $nonce
* @return bool
*/
private function checkSignature($signature, $timestamp, $nonce)
{
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);

if ($tmpStr == $signature) {
return true;
} else {
return false;
}
}



/**
* 获取用户详细信息
* @param $openid
* @param $refer_id
*/
/*public function createuserinfo($openid, $refer_id)
{
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->getToken($this->appid, $this->secret) . "&openid=" . $openid;
$user = request_get($url);
$user = json_decode($user, true);
$users = array(
'openid' => $openid,
'nickname' => $user['nickname'],
'avatar' => $user['headimgurl'],
'sex' => $user['sex'],
'unionid' => $user['unionid'],
'status' => 1,
'reg_time' => $user['subscribe_time'],//关注公众号的时间
'bind_user' => $refer_id
);
$user_str = date('Y-m-d H:i:s') . "\t";
foreach ($users as $key => $value) {
$user_str .= $key . '=' . $value . "\t";
}
$user_str .= "\n";
file_put_contents(LOG_PATH . "wx.log", $user_str, FILE_APPEND);
}*/






protected function http_post_data($url, $data_string) {

$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($data_string))
);
ob_start();
curl_exec($ch);
if (curl_errno($ch)) {
$this->ErrorLogger('curl falied. Error Info: '.curl_error($ch));
}
$return_content = ob_get_contents();
ob_end_clean();
$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return array($return_code, $return_content);
}

public function curlGet($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;

}



//https请求(支持GETPOST
public function https_post($url, $post_data = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post数据
curl_setopt($ch, CURLOPT_POST, 1);
// post的变量
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}

//上传图片
public function temporaryUploadFile()
{

$accesstoken = $this->getToken($this->appid,$this->secret);
$url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$accesstoken}&type=image";
$filename =$_SERVER['DOCUMENT_ROOT'].('/gz/maijia.jpg');
$result = $this->httpPost($url, $filename);
echo $result;
}

//新增上传图片
public function httpPost($url, $data)
{
$ch = curl_init();
if (class_exists('\CURLFile')) {
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
$data = array('media' => new \CURLFile($data));//>=5.5
} else {
if (defined('CURLOPT_SAFE_UPLOAD')) {
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
}
$data = array('media' => '@' . realpath($data));//<=5.5
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "TEST");
$result = curl_exec($ch);

curl_close($ch);
return json_encode($result, true);
}


protected function getToken(){
$curl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->secret";
$zhiya=$this->http_post_data($curl,2);
$zhiya=json_decode($zhiya[1],true);
$newzi=array_values($zhiya);
return $newzi[0];
}


//绑定手机号
public function bindmobile(Request $request){
$openid=$request->post('openid');
$user_id=$request->post('user_id');
$nickname=$request->post('nickname');
$mobile=$request->post('mobile');
$captchaType = 'bind_mobile';

//验证码
$captcha=$request->post('yzcode');

$key = CacheService::PREFIX . $captchaType .'_'. CacheService::HASH_CAPTCHA . $mobile;


if (! Redis::exists($key)) {
throw new CaptchaException('无效的验证码', 422);
}

if (Redis::get($key) != $captcha) {
$this->incrementErrorAttempts($mobile);
throw new CaptchaException('验证码错误', 422);
}

if($openid && $user_id && $nickname && $mobile){
$whereAry = [];
if(isset($openid)){
$whereAry[] = ['openid', '=', ''.$openid.''];
}
if(isset($user_id)){
$whereAry[]=['user_id','=',''.$user_id.''];
}

if(isset($nickname)){
$whereAry[]=['nickname','=',''.$nickname.''];
}

$zhiya=DB::connection('mysql_user')->table('user_account')->where($whereAry)->value('account_id');

if($zhiya){
$whereAry = [];
if(isset($openid)){
$whereAry[] = ['openid', '=', ''.$openid.''];
}

DB::connection(config('database.default'))->beginTransaction();

$data['mobile']=$mobile;
$qresult=DB::connection('mysql_user')->table('user_account')->where($whereAry)->update($data);

//新加逻辑当绑定的手机号没有时则视为新注册一个手机用户
$wherephone=array('mobile'=>$mobile);
$mobileresult=DB::connection('mysql_user')->table('user')->where($wherephone)->value('mobile');

if(empty($mobileresult)){

$access_token=$this->check_access_token_is_effective();
$userinfo = $this->getUserinfo($openid, $access_token);
//var_dump($userinfo);die();
$bsd['user_code']='kjzd_' . createUuid(Str::random(5));
$bsd['username']=$userinfo['nickname'];
$bsd['password']='$2a$10$Mss5QtjwNZF0FXuKsTXQ1uQQ6YfvC1diSz5lmSeL0ECvBRs.0rzCu';
$bsd['nickname']=$userinfo['nickname'];
$bsd['avatar']=$userinfo['headimgurl'];
$bsd['sex']=$userinfo['sex'];
$bsd['email']='null';
//不能相同
$bsd['mobile']=$mobile;
$bsd['user_type']=0;
$bsd['company_id']=0;
$bsd['register_ip']=$this->get_client_ip();
$usetime=time();
$bsd['register_time']=date('Y-m-d H:i:s',$usetime);
$bsd['source']=1;
$bsd['status']=1;
$bsd['user_desc']='2221';
$bsd['invited_code']='221';
$usetime3=time();
$bsd['create_time']=date('Y-m-d H:i:s',$usetime3);
$bsd['update_time']=date('Y-m-d H:i:s',$usetime3);
$bsd['update_flag']=1;
$bsd['country']=$userinfo['country'];
$bsd['province']=$userinfo['province'];
$bsd['city']=$userinfo['city'];
$newuser=DB::connection('mysql_user')->table('user')->insertGetId($bsd);
}

$datad['bind_mobile']=$mobile;
$whereuser = array('user_id' => $user_id);
$useredresult=DB::connection('mysql_user')->table('user')->where($whereuser)->update($datad);



$whereusedAry=[];
if(isset($user_id)){
$whereusedAry[]=['user_id','=',''.$user_id.''];
}
$datause['bind_mobile']=$mobile;
$uuresult=DB::table('users')->where($whereusedAry)->update($datause);

if($qresult && $uuresult){
DB::commit();
return response()->json(['code'=>0,'info'=>$qresult,'data'=>'绑定成功']);
}else{
DB::rollBack();
return response()->json(['code'=>-1,'data'=>'绑定失败']);
}

}else{
return response()->json(['code'=>500,'data'=>'不要乱操作']);
}
}else{
return response()->json(['code'=>-1,'data'=>'缺失参数呦']);
}

}


private function incrementErrorAttempts(string $mobile)
{
$errorTimesKey = CacheService::PREFIX . CacheService::ERROR_CAPTCHA_TIMES . $mobile;
if (Redis::exists($errorTimesKey)) {
Redis::incr($errorTimesKey);
} else {
Redis::setex($errorTimesKey, self::EXPIRE_TIME, 1);
}
}

//绑定手机号页面
public function bindphone(){

return view('frontend.auth.bind-mobile');
}



//检查是否扫码登录
public function isloged(Request $request){

$scene_id=$request->input('scene_id');

if ($scene_id > 0) {
//$qresult=DB::table('qrcodeusers')->where('id',$scene_id)->value('openid');

$requested=DB::connection('mysql_user')->table('user_account')->where('gz_id',$scene_id)->value('user_id');

//var_dump($requested);die();
$field=[
'user_account.user_id','user_account.mobile','user.user_code','user.username','user.nickname','user.avatar','user.sex','user.email','user.user_type','user.company_id',
'user.register_time','user.source','user.status','user.user_desc','user.company_id','user.register_time','user.source','user.status','user.user_desc',
'user.invited_code','user.invited_code','user.create_time','user.update_time','user.update_flag','user.country','user.province','user.city','user_account.unionid',
'user_account.openid','user.user_id'
];



$userlist=DB::connection('mysql_user')
->table('user_account')
->select($field)
->leftJoin('user','user_account.user_id','=','user.user_id')
->where('user_account.user_id',$requested)
->get()
->toArray();

$hahah=json_encode($userlist);
$usezhi=json_decode($hahah,true);
//var_dump($usezhi);echo 2222;die();

$payChannel='yam';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . Utils::jsonEncode($usezhi) . PHP_EOL,
FILE_APPEND
);

$usearray=array(
"user_id"=>$usezhi[0]['user_id'],
"user_code"=>$usezhi[0]['user_code'],
"username"=>'',
"nickname"=>$usezhi[0]['nickname'],
"avatar"=>$usezhi[0]['avatar'],
"sex"=>1,
"email"=>'',
"mobile"=>"qk8sn9hr2n4",
"user_type"=>0,
"company_id"=>0,
"register_time"=>$usezhi[0]['create_time'],
"source"=>0,
"status"=>1,
"user_desc"=>"",
"invited_code"=>"",
"create_time"=>$usezhi[0]['create_time'],
"update_time"=>$usezhi[0]['create_time'],
"update_flag"=>0,
"country"=>$usezhi[0]['country'],
"province"=>$usezhi[0]['province'],
"city"=>$usezhi[0]['city'],
"unionid"=>$usezhi[0]['openid'],
"openid"=>$usezhi[0]['openid']
);
$payChannel='yamyyy';
file_put_contents(
storage_path('logs/'. $payChannel .'.log'),
'[' . date('Y-m-d H:i:s') . '] ' . Utils::jsonEncode($usearray) . PHP_EOL,
FILE_APPEND
);
//var_dump($usearray);die();
if($usezhi[0]['user_id']){
(new UserAccountService())->getUserByWeChat($usearray);
return response()->json(['code'=>0,'data'=>$userlist]);
}else{
return response()->json(['code'=>-1,'data'=>'查找失败']);
}
}

}

}