微信授权登陆
程序员文章站
2022-03-26 09:26:43
1.微信授权登陆会传一个code值到后台,通过code取得微信用户信息 ......
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);
}
上一篇: C语言实现之比较两数有多少位不同