| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- <?php
- namespace App\Servers\WeChat;
- class WeixinServer
- {
- /**
- * 单列对象
- * @var
- */
- private static $server = '';
- public $appid = '';
- public $appsecret = '';
- private function __construct(){
- $this->appid=env('WX_APPID','');
- $this->appsecret=env('WX_APPSECRET','');
- }
- /**
- * 创建对象
- * @return WeixinServer
- */
- static function creatServer()
- {
- if(empty(self::$server)){
- self::$server = new WeixinServer();
- }
- return self::$server;
- }
- /**
- * 网页授权
- * @return mixed
- */
- function authorize()
- {
- $code = request()->input('code', '');
- if (empty($code)) {
- $redirect_url = $this->getServerUrl();
- $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirect_url}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
- $this->redirect($url);
- return false;
- } else {
- $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code";
- $result = $this->sendRequest($url);
- $result = json_decode($result, true);
- if (isset($result['errcode'])) {
- return false;
- } else {
- // $openid = $result['openid'];
- // $access_token = $result['access_token'];
- // $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->appid}&grant_type=refresh_token&refresh_token={$result['refresh_token']} ";
- // $result = $this->sendRequest($url);
- // $result = json_decode($result, true);
- // if (isset($result['access_token'])) {
- // $access_token = $result['access_token'];
- // $openid = $result['openid'];
- // }
- // $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
- // $result = $this->sendRequest($url);
- // $result = json_decode($result, true);
- // if (isset($result['errcode'])) {
- // return false;
- // }
- return $result;
- }
- }
- }
- /**
- * 获取当前连接
- * @return string
- */
- function getServerUrl()
- {
- return urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
- }
- function redirect($uri = '', $method = 'location', $http_response_code = 302)
- {
- if (!preg_match('#^https?://#i', $uri)) {
- $uri = site_url($uri);
- }
- switch ($method) {
- case 'refresh' :
- header("Refresh:0;url=" . $uri);
- break;
- default :
- header("Location: " . $uri, TRUE, $http_response_code);
- break;
- }
- exit();
- }
- }
|