PHP WeChat third-party method to implement one-click login and obtain user information (detailed example)

墨辰丷
Release: 2023-03-28 20:14:02
Original
1286 people have browsed it

This article mainly introduces the method for the PHP version of WeChat third-party to realize one-click login and obtain user information. It analyzes the relevant precautions and implementation skills of WeChat third-party login in more detail. Friends in need can refer to the following

Note that if you want to use WeChat to log in to a third-party webpage, you need a "service account", so you must apply for it from the official website.

At the beginning, you need to enter the WeChat public platform to open the development mode, and fill in the callback address of oauth2. Just fill in the domain name of your project. For example: www.baidu.com or zhidao.baidu. com. If your project is in a second-level domain name, write the second-level domain name

as the front-end url authorization address. In the URL, fill in the appid and the oauth address in the method in your project. You can see the details in the code below. Go to.

Copy code The code is as follows:

Authorization

Let’s talk about the background logic, first call SDK for WeChat interface. (Will be available later)

include('./Card/Common/class_weixin_adv.php');
Copy after login

Then fill in the appid and secret provided by WeChat official

$weixin=new class_weixin_adv("appid", "secret");
Copy after login

Initialize the SDK class, get the code, and use the obtained code to get the openid. See the code comments below!

$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&secret=secret&code=".$_GET['code']."&grant_type=authorization_code";
$res = $weixin->https_request($url);//调用SDK方法获取到res 从中可以得到openid
$res=(json_decode($res, true));//转换成array 方便调用openid
Copy after login

Continue to call the SDK method to obtain the user information. At this time, $row has obtained the user information. You can use var_dump to see the key value for easy storage in the database.

$row=$weixin->get_user_info($res['openid']);
Copy after login

Obtaining user information is done, but this is not enough. What we need is no need to register! So we need to use openid. Openid is a unique certificate. Each user has a different openid for different official accounts. It can be understood as a user account. What I use here is the solution of storing openid in cookies, which is similar to the feeling of user login. Some key data verification only needs to be compared with the openid in the database. Some other utilization methods can use your imagination! You can leave a message with me Communication!

Regarding the authorization of the previous a link, you can also determine whether the cookie has openid, so that unauthorized users can jump directly to the address, saving the user one step of operation.

The following is the complete logic code, you can refer to it!

public function oauth2(){
 include('./Card/Common/class_weixin_adv.php');
  $weixin=new class_weixin_adv("appid", "secret");
  if (isset($_GET['code'])){
    $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&secret=secret&code=".$_GET['code']."&grant_type=authorization_code";
    $res = $weixin->https_request($url);
    $res=(json_decode($res, true));
    $row=$weixin->get_user_info($res['openid']);
    if ($row['openid']) {
      //这里写上逻辑,存入cookie,数据库等操作
      cookie('weixin',$row['openid'],25920);
    }else{
      $this->error('授权出错,请重新授权!');
    }
  }else{
    echo "NO CODE";
  }
  $this->display();
}
Copy after login

SDK code: WeChat official manual, I won’t go into more details, you can study it yourself, it’s very simple !

<?php
/**
 * 微信SDK
 * pan041ymail@gmail.com
 */
class class_weixin_adv
{
  var $appid = "";
  var $appsecret = "";
  //构造函数,获取Access Token
  public function __construct($appid = NULL, $appsecret = NULL)
  {
    if($appid){
      $this->appid = $appid;
    }
    if($appsecret){
      $this->appsecret = $appsecret;
    }
    $this->lasttime = 1395049256;
    $this->access_token = "nRZvVpDU7LxcSi7GnG2LrUcmKbAECzRf0NyDBwKlng4nMPf88d34pkzdNcvhqm4clidLGAS18cN1RTSK60p49zIZY4aO13sF-eqsCs0xjlbad-lKVskk8T7gALQ5dIrgXbQQ_TAesSasjJ210vIqTQ";
    if (time() > ($this->lasttime + 7200)){
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
      $res = $this->https_request($url);
      $result = json_decode($res, true);
      $this->access_token = $result["access_token"];
      $this->lasttime = time();
    }
  }
//获取用户基本信息
  public function get_user_info($openid)
  {
    $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->access_token."&openid=".$openid."&lang=zh_CN";
    $res = $this->https_request($url);
    return json_decode($res, true);
  }
//https请求
  public function https_request($url, $data = null)
  {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
      curl_setopt($curl, CURLOPT_POST, 1);
      curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
  }
}
Copy after login

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

phpHow to insert mysql data and return id

php Method to intercept mixed Chinese and English strings

Specific use of ThinkPHP5 validator

JSON PHP In, the method of deserializing Json string into object/array

The above is the detailed content of PHP WeChat third-party method to implement one-click login and obtain user information (detailed example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template