旗下导航:搜·么
当前位置:网站首页 > PHP框架 > YII > 正文

yii2中怎样自定义大众类【yii框架教程】,yii2,自定义,公共类

作者:搜搜PHP网发布时间:2019-12-25分类:YII浏览:95


导读:以微信企业号为例:1、在YII根目录新建一个文件夹wechat,新建Wechat.php文件代码以下:<?namespaceapp\wechat;c...

以微信企业号为例:

1、在YII根目录新建一个文件夹wechat,新建Wechat.php文件

代码以下:

<? 
namespace app\wechat;
class Wechat
{
	const AGENTID = 3;//运用ID
	const CORPID = "wx5d0183ad90c95d8b";//ID
	const CORPSECRET = "KTHAkkVl4mX4Jr_g89d3PXajYupsUcJFvGWQ1K6ZMagTPOh4kiNMfBLFoDr12DVh";//秘钥
	const SCOPE = "snsapi_base"; 
	const STATE = "123"; 	
 
	//自动登录跳转
	public function wxauto($jumpurl){	
		$corpid = self::CORPID; 
		$scope = self::SCOPE; 
		$state = self::STATE;  
		$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$corpid.'
		&redirect_uri='.urlencode($jumpurl).'
		&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
		header("Location:".$url);
		exit;
	}
	
	//推送信息
	public function getPush($userid , $agentid , $message){
			$userinfo = $this->getToken();//猎取access_token
			$access_token = $userinfo['access_token'];
			$sendmsg_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".
			$access_token;
			$data="{\"touser\":\"$userid\",\"msgtype\":\"text\",\"agentid\":$agentid,\"text\":
			{\"content\":\"$message\"},\"safe\":0}";
			$res = $this->curlPost($sendmsg_url,$data);
			$errmsg=json_decode($res)->errmsg;
	}
	
	//猎取token
	public function getToken(){		
		$corpid = self::CORPID; 
		$corpsecret = self::CORPSECRET; 
		$Url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$corpid."&corpsecret=".$corpsecret;
		$res = $this->curlPost($Url);
		$access_token=json_decode($res)->access_token;
		$userinfo = array();
		$userinfo['access_token']=$access_token;
		return $userinfo;
	}
	
	//定义curl要领
	public function curlPost($url,$data=""){
		$ch = curl_init();
		$opt = array(
				CURLOPT_URL     => $url,
				CURLOPT_HEADER  => 0,
				CURLOPT_POST    => 1,
				CURLOPT_POSTFIELDS      => $data,
				CURLOPT_RETURNTRANSFER  => 1,
				CURLOPT_TIMEOUT         => 20
		);
		$ssl = substr($url,0,8) == "https://" ? TRUE : FALSE;
		if ($ssl){
			$opt[CURLOPT_SSL_VERIFYHOST] = 2; //注重1已弃用
			$opt[CURLOPT_SSL_VERIFYPEER] = FALSE;
		}
		curl_setopt_array($ch,$opt);
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}
###########**********增添猎取微信openid***********#########################
}
?>

2、控制器的挪用:

引入 use app\wechat\Wechat;

	$chat = new Wechat();  //实例化类
	$REDIRECT_URI= $_SERVER['HTTP_HOST'].'/test/back';//定义跳转URL
	$chat->wxauto($REDIRECT_URI);//挪用类的要领
        $chat->getToken();//挪用类的要领
 
	$corpid = Wechat::CORPID;//挪用类的常量
	$corpsecret = Wechat::CORPSECRET;//挪用类的常量
	$agentid=Wechat::AGENTID;//挪用类的常量

相干文章教程引荐:yii教程

以上就是yii2中怎样自定义大众类的细致内容,更多请关注ki4网别的相干文章!

标签:yii2自定义公共类