zoukankan      html  css  js  c++  java
  • 微信授权获取个人信息 头像 姓名 地区

    <?php
    namespace HomeController;

    class GetWxUserController extends CommonController {

    protected $appid = "wxe4a16ab6c280178c";
    protected $secret = "363cbcea8acb647f0b6ff8478d55c1d9";

    /**
    * 微信授权入口
    * scope=snsapi_base/snsapi_userinfo
    */
    public function index() {
    $appid = 'wxe4a16ab6c280178c';
    $loc_url = $_SERVER['HTTP_HOST'];
    $redirect_uri = urlencode('http://'.$loc_url.'/GetWxUser/resultCode');
    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
    header("Location:" . $url);

    }

    /*
    * 获取code信息
    */
    public function resultCode() {
    $code = I('request.code');
    if (!empty($code)) {
    return $code;
    } else {
    return NULL;
    }
    }

    /**
    * 获取微信用户信息
    */
    public function getWXUser() {
    $appid = $this->appid;
    $secret = $this->secret;
    $code = I('request.code');

    //第一步:取全局access_token
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
    $token = $this->getJson($url);

    //第二步:取得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 = $token["access_token"];
    $openid = $oauth2['openid'];
    $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
    $userinfo = $this->getJson($get_user_info_url);

    //打印用户信息
    // $userinfo = json_decode($userinfo, true);
    if($userinfo['errcode'] == 40003){
    $return = [
    'status' => 40003,
    'msg' => '获取失败',
    'data' => $userinfo
    ];
    } else {
    $return = [
    'status' => 200,
    'msg' => '获取成功',
    'data' => $userinfo
    ];
    }
    print_r($return);exit;
    return json_encode($return);
    }

    public function Login(){
    $this->display();
    }

    private 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);
    }
    }

  • 相关阅读:
    C#基础知识回顾--C#遍历enum类型、获取enum项个数
    WPF备忘录(3)如何从 Datagrid 中获得单元格的内容与 使用值转换器进行绑定数据的转换IValueConverter
    WPF备忘录(2)WPF获取和设置鼠标位置与progressbar的使用方法
    Eclipse 4.3 Kepler最快汉化方法
    SQLite3创建数据库的方法
    WPF备忘录(1)有笑脸,有Popup
    使用WPF教你一步一步实现连连看(二)
    使用WPF教你一步一步实现连连看(一)
    代码创建 WPF 旋转、翻转动画(汇总)
    导出ORACLE表结构到SQL语句(含CLOB)
  • 原文地址:https://www.cnblogs.com/zhang-bin/p/10768221.html
Copyright © 2011-2022 走看看