Home Backend Development PHP Tutorial PHP example-WeChat third-party login

PHP example-WeChat third-party login

Jun 28, 2017 pm 01:02 PM
php Example third party

The following editor will bring you a WeChat third-party login (native) demo [must read]. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

I have been working in an ecstore company for a while. The company hopes to develop its own products and has been cultivating new people.

Recently I have to log in to WeChat myself. I wrote the native WeChat third-party login based on the ectore framework to get familiar with WeChat third-party login and write it on ecstore.

A simple demo, not very good, I want to share it with you, hoping it can bring ideas to friends who want to do third-party login on WeChat...

First of all:

资料准备:

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

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

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" rel="external nofollow" >微信登录</a>
<br><br>
Copy after login

Process WeChat login Start

Define appid appsecert

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

Bind account 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");
 
 }
Copy after login

When you log in to WeChat for the first time, Processing the 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(&#39;数据库连接失败3&#39;);
      mysqli_set_charset($link,&#39;utf8&#39;);

      $post = utils::_filter_input($_POST);

    $userData = array(
      &#39;login_account&#39; => $post[&#39;uname&#39;],
      &#39;login_password&#39; => $post[&#39;password&#39;]
    );

    $member_id = kernel::single(&#39;pam_passport_site_basic&#39;)->login($userData,$post[&#39;verifycode&#39;],$msg);


    $b2c_members_model = $this->app->model(&#39;members&#39;);
    $member_point_model = $this->app->model(&#39;member_point&#39;);

    $member_data = $b2c_members_model->getList( &#39;member_lv_id,experience,point&#39;, array(&#39;member_id&#39;=>$member_id) );
    
    $member_data = $member_data[0];
    $member_data[&#39;order_num&#39;] = $this->app->model(&#39;orders&#39;)->count( array(&#39;member_id&#39;=>$member_id) ); 

    $b2c_members_model->update($member_data,array(&#39;member_id&#39;=>$member_id));
    $this->userObject->set_member_session($member_id);
    $this->bind_member($member_id);
    $this->set_cookie(&#39;loginName&#39;,$post[&#39;uname&#39;],time()+31536000);//用于记住密码
    // setCartNum()需要传入一个参数
    $aCart = array();
    $this->app->model(&#39;cart_objects&#39;)->setCartNum($aCart);
    $url = $this->userPassport->get_next_page(&#39;pc&#39;);
    if( !$url ){
      $url = kernel::single(&#39;b2c_frontpage&#39;)->gen_url(array(&#39;app&#39;=>&#39;b2c&#39;,&#39;ctl&#39;=>&#39;site_member&#39;,&#39;act&#39;=>&#39;index&#39;));
    }

    //查询数据库
    $uname = $_POST[&#39;uname&#39;];
    $sql = "select * from sdb_pam_members where password_account = &#39;$uname&#39; ";
    $res = mysqli_query($link, $sql);
    $row = mysqli_fetch_assoc($res);
    $member_id = $row[&#39;member_id&#39;];
    //链接数据库,插入数据
    $openid = $_COOKIE[&#39;openid&#39;];
    $sql = "update sdb_trustlogin_trustinfo set member_id = (&#39;{$member_id}&#39;) where openid = &#39;{$openid}&#39;";
    $res = mysqli_query($link, $sql); 

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

Processing the binding registration page

public function weixin1(){
     //链接数据库
    $link = mysqli_connect(DB_HOST, DB_USER,DB_PASSWORD,DB_NAME ) or die(&#39;数据库连接失败2&#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/weixin1.html");

  }
Copy after login

Binding registration page

public function handle1($url=null){
    //链接数据库
    $link = mysqli_connect(DB_HOST, DB_USER,DB_PASSWORD,DB_NAME ) or die(&#39;数据库连接失败1&#39;);
    mysqli_set_charset($link,&#39;utf8&#39;);

    $_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(&#39;b2c_save_post_om&#39;) as $object) {
        $object->set_arr($member_id, &#39;member&#39;);
        $refer_url = $object->get_arr($member_id, &#39;member&#39;);
      }

      /*注册完成后做某些操作! begin*/
      foreach(kernel::servicelist(&#39;b2c_register_after&#39;) as $object) {
        $object->registerActive($member_id);
      }
      /*end*/
      $data[&#39;member_id&#39;] = $member_id;
      $data[&#39;uname&#39;] = $saveData[&#39;pam_account&#39;][&#39;login_account&#39;];
      $data[&#39;passwd&#39;] = $_POST[&#39;pam_account&#39;][&#39;psw_confirm&#39;];
      $data[&#39;email&#39;] = $_POST[&#39;contact&#39;][&#39;email&#39;];
      $data[&#39;refer_url&#39;] = $refer_url ? $refer_url : &#39;&#39;;
      $data[&#39;is_frontend&#39;] = true;
      $obj_account=$this->app->model(&#39;member_account&#39;);
      $obj_account->fireEvent(&#39;register&#39;,$data,$member_id);
      if(!strpos($_SESSION[&#39;pc_next_page&#39;],&#39;cart&#39;)){
        $url = $this->gen_url(array(&#39;app&#39;=>&#39;b2c&#39;,&#39;ctl&#39;=>&#39;site_passport&#39;,&#39;act&#39;=>&#39;sign_tips&#39;));
      }else{
        $url = $_SESSION[&#39;pc_next_page&#39;];
      }

      //会员注册成功,处理member_id 开始
      $login_name = $_POST["pam_account"]["login_name"];
      $sql = "select member_id from sdb_pam_members where password_account = &#39;{$login_name}&#39;";
      // echo $sql;
      $res = mysqli_query($link, $sql);
      $row = mysqli_fetch_assoc($res);
      $member_id = $row[&#39;member_id&#39;];

      //链接数据库,插入数据
      $openid = $_COOKIE[&#39;openid&#39;];
      $sql = "update sdb_trustlogin_trustinfo set member_id = (&#39;{$member_id}&#39;) where openid = &#39;{$openid}&#39;";
      $res = mysqli_query($link, $sql); 

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

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

Temporary page

public function linshi(){

    $code = $_GET[&#39;code&#39;];
    $state = $_GET[&#39;state&#39;];

    if($state === &#39;STATE&#39;){
      $this->loginWeixin($code);
    }elseif($state === &#39;wxBind&#39;){
      $this->bindWeixin($code);
    }else{
      return redirect("http://www.sunmil.cn");
    }
  }
Copy after login

loginWeixin

private function loginWeixin($code){

    //链接数据库
    $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;);

    $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[&#39;openid&#39;];

    //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 = &#39;{$openid}&#39;";
        //查出member_id
        $res = mysqli_query($link, $sql);
        $row = mysqli_fetch_assoc($res);

        $member_id = $row[&#39;member_id&#39;];
        //查出会员信息
        $sql = "select * from sdb_pam_members where member_id = &#39;{$member_id}&#39;";
        $res = mysqli_query($link, $sql);
        $row = mysqli_fetch_assoc($res);

        $login_name = $row[&#39;login_account&#39;];

        //存入cookie 
        setcookie(&#39;UNAME&#39;,$login_name, time()+360000);
        echo "<script>window.location.href=&#39;http://www.sunmil.cn&#39;</script>";
        exit;
      }
    }

    $access_token = $result[&#39;access_token&#39;];
    //获取用户基本信息
    $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 = &#39;trustlogin_plugin_weixin&#39;;
    //连接数据库,插入数据
    $sql = "insert into sdb_trustlogin_trustinfo (openid,realname,avatar,gender,province,city,trust_source) values (&#39;{$openid}&#39;,&#39;{$nickname}&#39;,&#39;{$avatar}&#39;,&#39;{$sex}&#39;,&#39;{$province}&#39;,&#39;{$city}&#39;,&#39;{$trust_source}&#39;)";
    $res = mysqli_query($link, $sql); 

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

curl simulated 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;
  }
Copy after login

End of processing WeChat login

You can implement WeChat login. Of course, a demo that is simple and familiar with the third login of WeChat, there is an opportunity to use the TP framework to sub-package and complete one Complete WeChat third-party login.

Welcome to leave a message and discuss it together.

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

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles