zoukankan      html  css  js  c++  java
  • php 微信登录 公众号 获取用户信息 微信网页授权

    php 微信登录 公众号 获取用户信息 微信网页授权

    先自己建立两个文件: index.php  和  getUserInfo.php

    index.php

    <?php
    //scope=snsapi_userinfo实例
    $appid=''; //填写你公众号的appid
    $redirect_uri = urlencode ( 'http://fenlei.sun0758.com/WX/getUserInfo.php' ); //回调页面 getUserInfo.php 不能写错
    $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
    header("Location:".$url);
    

    getUserInfo.php

    <?php
    header("Content-type: text/html; charset=utf-8");
    $appid = "";  //填写你公众号的appid
    $secret = "";  //填写你公众号的secret
    $code = $_GET["code"];
     
    //第一步:取得openid
    $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
    $oauth2 = 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 = getJson($get_user_info_url);
     
    //打印用户信息
      print_r($userinfo);
     
    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);
    }
    

    将网址: http://你的域名/index.php 生成一个二维码!便能制作扫描二维码登录了。

    切记

    1.  https://api.weixin.qq.com/sns/userinfo
    2. https://api.weixin.qq.com/cgi-bin/user/info 
    上面两个api都是获取用户信息的,并且传入的参数也是一样的,第一个是用户网页端,第二个使用公共号关注后获取用户信息,希望以后的小伙伴可以记住。不要跟我犯一样的错误了。
     
     
    出现40001错误!
    Appkey 和 Appstore正确前提下
     
    1. 因为开放平台跟微信公共号不一样,开放平台是不存在用户关注微信公共号的
    2. 请求登录的方式也不同
    a) 开放平台请求方式通过网页端生成二维码用户通过微信客服端进行扫描登录
    网页端扫描的请求为:https://open.weixin.qq.com/connect/qrconnect
    b) 而公共号只要在手机上操作因此登录请求的API也不同
    而公共号的网页请求则为:https://open.weixin.qq.com/connect/oauth2/authorize 
    如果使用此链接为网页端微信登录她会提示你在微信客户端进行访问
    c) 其次他们作用范围也是不相同的scope值(这个可以看微信的开发文档)
    说了这么多那为什么会存在调用错api呢?
    原因很简单因为微信公共号存在用户关注微信公共号,但是微信开放平台是跟网页进行关联就不存在关注公共号这个说法,所以如果在网页端应用调用公共号关注获取用户的api 必然会出现40001的错误就是不存在或者提示你的token有误。
  • 相关阅读:
    python之路_保留原搜索页面条件
    python之路_面向对象相关知识点
    2-SAT习题讲解
    圆方树浅谈
    莫队浅谈&题目讲解
    矩阵树定理浅谈
    动态点分治浅谈
    线性基浅谈
    模板—费用流(最小费用最大流)
    模板—数学—Exgcd
  • 原文地址:https://www.cnblogs.com/fan-bk/p/7700114.html
Copyright © 2011-2022 走看看