tp5 接入微信登陆

/**
 * 获取微信用户信息
 */
public function index()
{
   if(empty($this->data["code"])) $this->result('', -1, 'code不能为空!');
   $appid = config('appid');//微信的appid
   $secret = config('secret');//微信的appsecret
   $code = $this->data["code"];//前端获取到的code
   $token = $this->generate_rand_str('12');//12位随机数
   //第一步:取得openid
   $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
   $oauth2 = $this->getJson($oauth2Url);
   //第二步:根据全局access_token和openid查询用户信息
   $access_token = $oauth2["access_token"];
   $openid = $oauth2['openid'];
   $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
   $userinfo = $this->getJson($get_user_info_url);
   $this->result($userinfo, 1, '微信用户信息');
}

/**
 * 生成随机字符串
 */
function generate_rand_str($length = 8, $type = 0) {
	 $a = 'abcdefghijklmnopqrstuvwxyz';
	 $A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	 $n = '0123456789';
	 switch ($type) {
	     case 1: $chars = $a; break;
	     case 2: $chars = $A; break;
	     case 3: $chars = $n; break;
	     case 4: $chars = $a.$A; break;
	     case 5: $chars = $a.$A.$n; break;
	     default: $chars = $a.$n;
	 }
	 $str = '';
	 for ($i = 0; $i < $length; $i++) {
	     $str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
	 }
	 return $str;
}

/**
 * 发起请求
 */
 function getJson($url){
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     $output = curl_exec($ch);
     curl_close($ch);
     return json_decode($output, true);
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值