微信授权登陆

1.微信授权登陆会传一个code值到后台,通过code取得微信用户信息


use think\Loader;   //使用thinkPHP的Loader类
Loader::import('Curl.Curl');    //引入Curl文件
//目录结构
public function login(){

$Curl = new \Curl();  //自己封装的发送请求的方法
$code = input('code','');//小程序传来的code值
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.get_wx_config('appid').'&secret='.get_wx_config('secret').'&js_code='.$code.'&grant_type=authorization_code&connect_redirect=1';
$info = $Curl::send($url,'get');
$json = (array)json_decode($info);
return $json;

}

/**
* Curl 类详解
*/
class Curl {
private static $url = ''; // 访问的url
private static $oriUrl = ''; // referer url
private static $data = array(); // 可能发出的数据 post,put
private static $method; // 访问方式,默认是GET请求

public static function send($url, $method = 'get', $data = array()) {
if (!$url) exit('url can not be null');
self::$url = $url;//请求的URL
self::$method = $method;//请求方式post or get
$urlArr = parse_url($url);
self::$oriUrl = $urlArr['scheme'] .'://'. $urlArr['host'];
self::$data = $data;//参数 数组格式
if ( !in_array(
self::$method,
array('get', 'post', 'put', 'delete')
)
) {
exit('error request method type!');
}

$func = self::$method . 'Request';
return self::$func(self::$url);
}

private static function doRequest($is_post = 0) {

$ch = curl_init();//初始化curl
curl_setopt($ch, CURLOPT_URL, self::$url);//抓取指定网页
// 来源一定要设置成来自本站
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
     if($is_post == 1) curl_setopt($ch, CURLOPT_POST, $is_post);//post提交方式
     if (!empty(self::$data)) {
       self::$data = self::dealPostData(self::$data);
       curl_setopt($ch, CURLOPT_POSTFIELDS, self::$data);
     }
     curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
     $data = curl_exec($ch);//运行curl
     curl_close($ch);
     return $data;
  }

    /** * 发起get请求 */

  public static function getRequest() {
    return self::doRequest(0);
  }

    /** * 发起post请求 */
  public static function postRequest() {
    return self::doRequest(1);
  }
 
posted @ 2018-10-18 16:38  没有感情的机器  阅读(...)  评论(...编辑  收藏