微信第三方登录授权

首先第三方应用要跟微信帐号合作,然后按照下面的方法操作:

第一步:注册应用。

可以通过卫微信的开放平台去注册一个应用。之后你会得到一个App Key和一个App Secret。拥有它们,你才可以申请权限。

假设你的App Key是“1234567890”,App Secret是“abcdefghijklmnopqrstuvwxyz"

第二步:写代码。

将获取到的OAuth的php版本的SDK加入你的project中。将你申请到的Key和Secret做为两个变量定义并赋值。

对于OAuth来说,很多细节不需要我们去关注的,只要知道几个重要的步骤即可:

 1. 第三方发起微信授权登录请求,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;

 2. 通过code参数加上AppID和AppSecret等,通过API换取access_token;

 3. 通过access_token进行接口调用,获取用户基本数据资源或帮助用户实现基本操作。获取access_token时

  4. 获得未授权的access_token这个获得未授权的 access_token就相当于放行条,也就是微信允许你开始获取用户的权限。

  5. 根据这个access_token的内容,获得一个url地址,这个地址页面就是想登录你应用的用户输入用户名和密码的地方。注意的是,这个url是属于微信为你的这个应用创建的回调地址。

  6. 用户在上述登录界面输入自己的用户名和密码,成功登录之后,你可以获得已授权的 Access KEY。这个Access Key就包含了用户多登录信息(包括昵称、用户openID等等,这里的昵称是指用户显示在微信上的名字,而不是用户的登录名)。

代码:

fn_system.php 判断微信登录是否已经授权

<?php  
  
    if(empty($_SESSION['user'])){  
      
       header("Location:fn_wx_login.php");  
    }else{  
       print_r($_SESSION['user']);  
   }  
  
?>  

wx_sample.php 微信授权文件

<?php
/**
  * wechat php test
  */

//define your token
/* token 一定要和微信开发平台上填写的保持一致*/
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

          //extract post data
        if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
                  $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
                $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            <FuncFlag>0</FuncFlag>
                            </xml>";             
                if(!empty( $keyword ))
                {
                      $msgType = "text";
                    $contentStr = "Welcome to wechat world!";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                }else{
                    echo "Input something...";
                }

        }else {
            echo "";
            exit;
        }
    }
        
    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
                
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}

?>

fn_callback.php 微信回调文件,通过token获取用户的基本资料

<?php  
 /*设置appid和secret以及回调地址*/
$appid = "123456789";  
$secret = "abcdefghijklmnopqrstuvwxyz";  
$code = $_GET["code"];  
$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';  
  
$ch = curl_init();  
curl_setopt($ch,CURLOPT_URL,$get_token_url);  
curl_setopt($ch,CURLOPT_HEADER,0);  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );  
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);  
$res = curl_exec($ch);  
curl_close($ch);  
$json_obj = json_decode($res,true);  
  
//根据openid和access_token查询用户信息  
$access_token = $json_obj['access_token'];  
$openid = $json_obj['openid'];  
$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';  
  
$ch = curl_init();  
curl_setopt($ch,CURLOPT_URL,$get_user_info_url);  
curl_setopt($ch,CURLOPT_HEADER,0);  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );  
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);  
$res = curl_exec($ch);  
curl_close($ch);  
  
//解析json  
$user_obj = json_decode($res,true);  
if($user_obj){
    // 处理第三方登录信息
    $sql = "select * from `ub01` where ub01004 = '".$user_obj['openid']."'";
    $chek = _selectone($sql) ? _selectone($sql) : array();
    if(!empty($chek)){
        $_SESSION['uid']=$res['ua01001'];
        header("Location:?"); 
    }else{
        $arr['ua01998'] = time();
        $arr['ua01005'] = 2;
        $arr['guid'] = UUID();
        $id = _inserttable('ua01',$arr,true);
        if($id){
            $brr['ua01001'] = $id;
            $brr['ub01003'] = 2;
            $brr['ub01004'] = $user_obj['openid'];
            $arr['ub01998'] = time();
            $brr['guid'] = UUID();
            $sid = _inserttable('ua01',$arr,true);
            if($sid){
                $sql = "select * from `ub01` where ub01001 = '$sid'";
                $cheks = _selectone($sql) ? _selectone($sql) : array();
                if(!empty($cheks)){
                  $_SESSION['uid']=$res['ua01001'];
                  
                  header("Location:?"); 
                }
            }
            
        }
        
    }
    // $_SESSION['user'] = $user_obj;  
}

// print_r($user_obj);  
  
?>  

 

posted @ 2016-04-19 16:03  楓羽靈~  阅读(5716)  评论(0编辑  收藏  举报