search
HomeBackend DevelopmentPHP TutorialWeChat third-party login demo

First:

资料准备:

      水印图片 28*28         png格式        公司logo
      高清图片 108*108     png格式       公司logo

      1.在微信开放平台 https://open.weixin.qq.com/中填写基本信息,
      2.完成邮箱验证,
      3.并完善开发者资料,注册成为开发者。
      4.在“账号中心”完成开发者资质认证。
      5.进入微信开放平台管理中心网站应用,点击“创建应用”按钮。
      6.填写基本信息,完成点击下一步
      7.填写平台信息
        应用签名:可在微信开发平台的资源中心》》资源下载》》中下载“签名生成工具”,用户获取已经安装到手机的第三方应用的签名。输入应用包名,即可获得该应用的签名值。
      8.提交审核后,在7个工作日内腾讯将给出审核结果。(通常较快,几个小时就可反馈结果)

Get AppID, AppSecret, subsequent processing:

需要在你想加的网站登录页给一个链接:<a href="https://open.weixin.qq.com/connect/qrconnect?appid=your appid &redirect_uri=http://www.sunmil.cn/passport-linshi.html&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect">微信登录</a>

Processing WeChat login starts

define appid appsecert

    private $appid = "your appid";
    private $appsecert = "your appsecert";
    private $redirect_uri = "http://www.sunmil.cn/wxGetCode";

Bind Account setting page

  public function weixin(){
        //链接数据库
        $link = mysqli_connect(DB_HOST, DB_USER,DB_PASSWORD,DB_NAME ) or die(&#39;数据库连接失败4&#39;);
        $link = mysqli_connect(&#39;127.0.0.1&#39;, &#39;root&#39;,&#39;root&#39;, &#39;ec&#39;) or die(&#39;数据库连接失败&#39;);
        mysqli_set_charset($link,&#39;utf8&#39;);

        //接收openid
        $openid = $_COOKIE[&#39;openid&#39;];

        $sql = "select * from sdb_trustlogin_trustinfo where openid = &#39;$openid&#39; ";
        $res = mysqli_query($link, $sql);
        $row = mysqli_fetch_assoc($res);

        $this->pagedata[&#39;realname&#39;] = $row[&#39;realname&#39;];
        $this->pagedata[&#39;avatar&#39;] =  $row[&#39;avatar&#39;];

        $this->page("site/passport/weixin.html");

    }

When you log in to WeChat for the first time, process binding account page

    public function handle($url=null){       
    // $url = "http://www.sunmil.cn";
         //链接数据库
        $link = mysqli_connect(DB_HOST, DB_USER,DB_PASSWORD,DB_NAME ) or die('数据库连接失败3');
            mysqli_set_charset($link,'utf8');            $post = utils::_filter_input($_POST);        
            $userData = array(            'login_account' => $post['uname'],'login_password' => $post['password']
        );        
        $member_id = kernel::single('pam_passport_site_basic')->login($userData,$post['verifycode'],$msg);        
        $b2c_members_model = $this->app->model('members');       
        $member_point_model = $this->app->model('member_point');        
        $member_data = $b2c_members_model->getList( 'member_lv_id,experience,point', array('member_id'=>$member_id) );        
        $member_data = $member_data[0];        
        $member_data['order_num'] = $this->app->model('orders')->count( array('member_id'=>$member_id) );  

        $b2c_members_model->update($member_data,array('member_id'=>$member_id));        
        $this->userObject->set_member_session($member_id);        
        $this->bind_member($member_id);        
        $this->set_cookie('loginName',$post['uname'],time()+31536000);//用于记住密码
        // setCartNum()需要传入一个参数
        $aCart = array();        
        $this->app->model('cart_objects')->setCartNum($aCart);        
        $url = $this->userPassport->get_next_page('pc');        
        if( !$url ){            
        $url = kernel::single('b2c_frontpage')->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'index'));
        }        
        //查询数据库
        $uname = $_POST['uname'];        
        $sql = "select * from sdb_pam_members where password_account = '$uname' ";        
        $res = mysqli_query($link, $sql);        
        $row = mysqli_fetch_assoc($res);        
        $member_id = $row['member_id'];        
        //链接数据库,插入数据
        $openid =  $_COOKIE['openid'];        
        $sql = "update sdb_trustlogin_trustinfo set member_id = ('{$member_id}')  where openid = '{$openid}'";        
        $res = mysqli_query($link, $sql); 

        if($res && mysqli_affected_rows($link) > 0){ 
            //删除cookie
            setcookie("openid", $openid, time()-3600);
            kernel::single('pam_lock')->flush_lock($member_id);            
            $this->splash('success',$url,app::get('b2c')->_('登录成功'),true); 
        }else{            
        echo '失败了';
        }
    }

Process binding Registration page

public function weixin1(){          
//链接数据库
        $link = mysqli_connect(DB_HOST, DB_USER,DB_PASSWORD,DB_NAME ) or die('数据库连接失败2');
        mysqli_set_charset($link,'utf8');        
        //接收openid
        $openid = $_COOKIE['openid'];        
        $sql = "select * from sdb_trustlogin_trustinfo where openid = '$openid' ";        
        $res = mysqli_query($link, $sql);        
        $row = mysqli_fetch_assoc($res);        
        $this->pagedata['realname'] = $row['realname'];        
        $this->pagedata['avatar'] =  $row['avatar'];        
        $this->page("site/passport/weixin1.html");

    }

Binding registration page

 public function handle1($url=null){        
 //链接数据库
        $link = mysqli_connect(DB_HOST, DB_USER,DB_PASSWORD,DB_NAME ) or die('数据库连接失败1');
        mysqli_set_charset($link,'utf8');        
        $_POST = utils::_filter_input($_POST);        
        $saveData = $this->userPassport->pre_signup_process($_POST);        
        if( $member_id = $this->userPassport->save_members($saveData,$msg) ){            
        $this->userObject->set_member_session($member_id);            
        $this->bind_member($member_id);            
        foreach(kernel::servicelist('b2c_save_post_om') as $object) {                
        $object->set_arr($member_id, 'member');                
        $refer_url = $object->get_arr($member_id, 'member');
            }            
            /*注册完成后做某些操作! begin*/
            foreach(kernel::servicelist('b2c_register_after') as $object) {                
            $object->registerActive($member_id);
            }            
            /*end*/
            $data['member_id'] = $member_id;            
            $data['uname'] = $saveData['pam_account']['login_account'];            
            $data['passwd'] = $_POST['pam_account']['psw_confirm'];            
            $data['email'] = $_POST['contact']['email'];            
            $data['refer_url'] = $refer_url ? $refer_url : '';            
            $data['is_frontend'] = true;            
            $obj_account=$this->app->model('member_account');            
            $obj_account->fireEvent('register',$data,$member_id);            
            if(!strpos($_SESSION['pc_next_page'],'cart')){         
            $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_passport','act'=>'sign_tips'));
            }else{                
            $url = $_SESSION['pc_next_page'];
            }            
            //会员注册成功,处理member_id 开始
            $login_name = $_POST["pam_account"]["login_name"];            
            $sql = "select member_id from sdb_pam_members where password_account = '{$login_name}'";            
            // echo $sql;
            $res = mysqli_query($link, $sql);            
            $row = mysqli_fetch_assoc($res);            
            $member_id = $row['member_id'];            
            //链接数据库,插入数据
            $openid =  $_COOKIE['openid'];            
            $sql = "update sdb_trustlogin_trustinfo set member_id = ('{$member_id}')  where openid = '{$openid}'";            
            $res = mysqli_query($link, $sql); 

            if($res && mysqli_affected_rows($link) > 0){ 

                 //删除cookie
                setcookie("openid", $openid, time()-3600);                
                $this->splash('success',$url,app::get('b2c')->_('注册成功'),$ajax_request);
                }     
        //会员注册成功,处理member_id 结束
            $this->splash('failed',$back_url,app::get('b2c')->_('注册失败'),$ajax_request);
        }
    }

Temporary page

 public function linshi(){        
 $code =  $_GET['code'];        
 $state =  $_GET['state'];        
 if($state === 'STATE'){            
 $this->loginWeixin($code);
        }elseif($state === 'wxBind'){            
        $this->bindWeixin($code);
        }else{           
         return redirect("http://www.sunmil.cn");
        }
    }

loginWeixin

  private function loginWeixin($code){        
  //链接数据库
        $link = mysqli_connect('127.0.0.1', 'root','root', 'ec') or die('数据库连接失败');
        mysqli_set_charset($link,'utf8');        
        $appid = $this->appid;        
        $appsecert = $this->appsecert;        
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecert."&code=".$code."&grant_type=authorization_code";        
        //curl模拟get请求,获取结果
        $res = $this->http_curl($url);        
        //转化为数组
        $result = json_decode($res,true);        
        $openid = $result['openid'];        
        //openid存在,直接登录,openid不存在,先注册再登录
        $sql = "select openid from sdb_trustlogin_trustinfo";        
        $res = mysqli_query($link, $sql);        
        $row = mysqli_fetch_all($res);            
        //foreach 判断
        foreach ($row As  $v) {            
        if(in_array($openid,$v,true)){                
        //缺少登录信息

                $sql = "select member_id from sdb_trustlogin_trustinfo where openid = '{$openid}'";                
                //查出member_id
                $res = mysqli_query($link, $sql);                
                $row = mysqli_fetch_assoc($res);                
                $member_id = $row['member_id'];                
                //查出会员信息
                $sql = "select * from sdb_pam_members where member_id = '{$member_id}'";                
                $res = mysqli_query($link, $sql);    
                $row = mysqli_fetch_assoc($res);                
                $login_name = $row['login_account'];                
                //存入cookie  
                setcookie('UNAME',$login_name, time()+360000);                
                echo "<script>window.location.href=&#39;http://www.sunmil.cn&#39;</script>";                
                exit;
            }
        }        
        $access_token = $result['access_token'];        
        //获取用户基本信息
        $getInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";        
        $userInfo = $this->http_curl($getInfoUrl);        
        $trustinfo = json_decode($userInfo);        
        //判断trustinfo表里面是否存在该条数据
        $openid     =   $trustinfo->openid;        
        $nickname   =   $trustinfo->nickname; 
        $sex        =   $trustinfo->sex; 
        $city       =   $trustinfo->city; 
        $province   =   $trustinfo->province; 
        $country    =   $trustinfo->country; 
        $avatar     =   $trustinfo->headimgurl;        
        $trust_source = 'trustlogin_plugin_weixin';        
        //连接数据库,插入数据
        $sql = "insert into sdb_trustlogin_trustinfo  (openid,realname,avatar,gender,province,city,trust_source) values ('{$openid}','{$nickname}','{$avatar}','{$sex}','{$province}','{$city}','{$trust_source}')";        
        $res = mysqli_query($link, $sql); 

        if($res && mysqli_affected_rows($link) > 0){ 
             //存入cookie 
            setcookie('openid',$openid, time()+3600);            
            header("Location:http://www.sunmil.cn/passport-weixin.html");
        }else{            echo '失败了';
        }   
    }

curl simulates get request

 private function http_curl($url){        $curlobj = curl_init();
        curl_setopt($curlobj, CURLOPT_URL, $url);
        curl_setopt($curlobj, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curlobj, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curlobj, CURLOPT_SSL_VERIFYHOST, FALSE);        $output = curl_exec($curlobj);
        curl_close($curlobj);        return $output;
    }

Processing WeChat login is completed

You can realize WeChat login , of course, a demo that is simple and familiar with WeChat third-party login, and there is an opportunity to use tpframework to package and complete a complete WeChat third-party login.

Welcome to leave a message and discuss it together.

The above is the detailed content of WeChat third-party login demo. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

How to Register and Use Laravel Service ProvidersHow to Register and Use Laravel Service ProvidersMar 07, 2025 am 01:18 AM

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version