首页 > 代码库 > 一个最简单的微信授权demo

一个最简单的微信授权demo

index.php 是准备授权的页面 ,我在这打印了下获取到的用户数据

require_once("./function.php");$url = ‘http://‘.$_SERVER[‘HTTP_HOST‘].$_SERVER[‘REQUEST_URI‘].‘?pid=x‘;$getuserinfo = getuserinfo($url);print_r($getuserinfo);

 function.php代码如下

function getuserinfo($url){		require_once("./oauth.php");		$wechat = new Wechat();				if(isset($_GET[‘param‘]) && isset($_GET[‘code‘])){			$get = $_GET[‘param‘];			$code = $_GET[‘code‘];			if($get==‘access_token‘ && !empty($code)){				$json = $wechat->get_access_token($code);				return $json;			}						}else{			$wechat->get_authorize_url($url.‘&param=access_token‘,‘STATE‘);		}		}

  auth.php代码如下

<?phpclass Wechat {        //高级功能-》开发者模式-》获取    private $app_id = ‘xxxxx‘;//appid    private $app_secret = ‘xxxxx‘;//app密匙      /**     * 获取微信授权链接     *      * @param string $redirect_uri 跳转地址     * @param mixed $state 参数     */    public function get_authorize_url($redirect_uri = ‘‘, $state = ‘‘)    {        $redirect_uri = urlencode($redirect_uri);        $url =  "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_base&state={$state}#wechat_redirect";		echo "<script language=‘javascript‘ type=‘text/javascript‘>";          echo "window.location.href=http://www.mamicode.com/‘$url‘";          echo "</script>";      }        /**     * 获取授权token     *      * @param string $code 通过get_authorize_url获取到的code     */    public function get_access_token($code)    {        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->app_id}&secret={$this->app_secret}&code={$code}&grant_type=authorization_code";        $token_data = http://www.mamicode.com/$this->http($token_url);"https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$open_id}&lang=zh_CN";            $info_data = http://www.mamicode.com/$this->http($info_url);"=====post data=http://www.mamicode.com/=====/r/n";            var_dump($postfields);             echo ‘=====info=====‘ . "\r\n";            print_r(curl_getinfo($ci));             echo ‘=====$response=====‘ . "\r\n";            print_r($response);        }        curl_close($ci);        return array($http_code, $response);    } }?>

  注意需要网页授权域名

一个最简单的微信授权demo