小编给大家分享一下yii2中自定义公共类的方法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
霍山ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18980820575(备注:SSL证书合作)期待与您的合作!示例:
1、在YII根目录新建一个文件夹wechat,新建Wechat.php文件
代码如下:
namespace app\wechat; class Wechat { const AGENTID = 3;//应用ID const CORPID = "wx5d0183ad90c95d8b";//ID const CORPSECRET = "KTHAkkVl4mX4Jr_g89d3PXajYupsUcJFvGWQ1K6ZMagTPOh5kiNMfBLFoDr12DVh";//秘钥 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/oauth3/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 = "/tupian/20230522/send $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="/tupian/20230522/gettoken $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;//调用类的常量
以上是“yii2中自定义公共类的方法”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!