search
HomeBackend DevelopmentPHP TutorialAnalysis of WeChat web page authorization library based on CI framework

This article mainly introduces the WeChat webpage authorization library based on the CI framework, and analyzes the related implementation techniques of the CI framework integrating WeChat authorization functions and controller calls in the form of examples. Friends in need can refer to the following

This article describes the WeChat web page authorization library based on the CI framework. Share it with everyone for your reference, the details are as follows:

Here is a demonstration of the WeChat web page authorization function based on the CI framework.

1. WeChat small class library, web page authorization is placed in the libraries folder

<?php
if ( ! defined(&#39;BASEPATH&#39;)) exit(&#39;No direct script access allowed&#39;);
Class Weixin
{
    private $appId;
    private $appSecret;
    function __construct()
    {
      $this->appId = trim(&#39;你的appid&#39;);
      $this->appSecret = trim(&#39;你的appsecret&#39;);
    }
    function redirect_url($redirect)
    {
      /*授权页面*/
      $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$this->appId&redirect_uri=$redirect&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
      return $url;
    }
    /* 通过code换取access_token*/
    function access_token($code)
    {
      /*获取到的code换取access_token和openid*/
      $post_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appId&secret=$this->appSecret&code=$code&grant_type=authorization_code";
             // echo $post_url;exit();
      $return = $this->postdata($post_url);
      // print_r($return);exit();
      $access_token = $return[&#39;access_token&#39;];
      $openid = $return[&#39;openid&#39;];
      /*获取微信用户数据*/
      $get_userinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
      $userinfo = json_decode(file_get_contents($get_userinfo));
      return $userinfo;
    }
    function eff($access_token,$openid)
    {
      /*检测access_token是否正确,errcode=0 为正确*/
      $eff_url = "https://api.weixin.qq.com/sns/auth?access_token=$access_token&openid=$openid";
      $get_eff =json_decode(file_get_contents($eff_url));
      return $get_eff;
    }
    //通过curl方式提交code换取access_token数据
    function postdata($url)
    {
       header(&#39;Content-Type:text/html;charset=utf-8&#39;);
       // echo $url;exit();
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
      curl_setopt($curl, CURLOPT_SSLVERSION, 1);
      // 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);
      // var_dump($output);exit();
      // print_r($output);exit();
      $access = json_decode($output,true);
      return $access;
    }
    /*
      这个位置开始是控制器index()传入的微信用户资料处理
    */
      function save_session($data)
      {
        foreach ($data as $key => $value) {
          // $_SESSION[&#39;uid&#39;] = $value[&#39;uid&#39;];
          // $_SESSION[&#39;nickname&#39;] = $value[&#39;nickname&#39;];
          // $_SESSION[&#39;fullname&#39;] = $value[&#39;fullname&#39;];
          // $_SESSION[&#39;status&#39;] = $value[&#39;status&#39;];
          // $_SESSION[&#39;groups&#39;] = $value[&#39;groups&#39;];
          $_SESSION[$key] = $value;
        }
        return $_SESSION;
        // print_r($_SESSION);exit();
        // unset($_SESSION[0]);
      }
    function obj_to_arr($data)
    {
      // 进行转换成数组 使用 obj_to_arr方式
      $data = is_object($data)?get_object_vars($data):$data;
        foreach ($data as $key => $value)
        {
          $arr[$key] = $value;
        }
        return $arr;
    }
}

2. Obtain user information by exchanging code for access_token, controller File

<?php
if ( ! defined(&#39;BASEPATH&#39;)) exit(&#39;No direct script access allowed&#39;);
Class Coupon_index extends CI_Controller
{
    function __construct()
    {
      parent::__construct();
      $this->load->library(array(&#39;weixin&#39;,&#39;session&#39;));
      $this->load->helper(&#39;url&#39;);
      // $this->load->ldap_mod_del(link_identifier, dn, entry)
      $this->load->model(&#39;Coupon_model&#39;);
    }
    /**
     *优惠券主程序
     */
    function index()
    {
      $this->load->view(&#39;/coupon/index.html&#39;);
    }
    function User_exists()
    {
      /*
        检测改微信用户是否存在
        $user_arr 获取的是通过get_code返回的微信用户信息,此时的信息是通过微信服务器返回的,不能记录session
        $user std_obj模式,转换为数组
        $user_exists 扔入model中,检测数据表中是否存在该用户
        $redirect 走完流程后,跳转到首页
        if语句的作用,是 判断通过model返回数据表的信息,如果为空则把微信用户信息录入到表中,再读取出来,存进session。
        else 则数据表已经存在该用户,直接读取,存进session
        需要注意的是,使用foreach的原因,是二维数组转一维数组
      */
        $user_arr = $this->Get_code();
        // var_dump($user_arr);exit();
        $user = $this->weixin->obj_to_arr($user_arr);
        // var_dump($user);exit();
        // print_r($user);exit();
        $user_exists = $this->Coupon_model->CheckUser(&#39;cou_user&#39;,$user);
        // print_r($user_exists);exit();
        // $redirect = &#39;http://yourwebname.com/coupon/index.php/Coupon/Coupon_index/Coupon_Get/bid/1&#39;;
        // $return_url = $this->session->return_url;
        $redirect = &#39;http://yourwebname.com&#39;.$this->session->return_url;
        // echo $redirect;exit();
        if(empty($user_exists))
        {
           /*
         由于微信获取到的用户数据是stdclass对象格式
         所以需要进行转换成数组 使用 obj_to_arr方式
         */
        //加入自定义的字符进入数组
        unset($user[&#39;privilege&#39;]);
        $user_exists[&#39;nickname&#39;]   = $user[&#39;nickname&#39;];
        $user_exists[&#39;openid&#39;]    = $user[&#39;openid&#39;];
        $user_exists[&#39;language&#39;]   = $user[&#39;language&#39;];
        $user_exists[&#39;city&#39;]     = $user[&#39;city&#39;];
        $user_exists[&#39;country&#39;]    = $user[&#39;country&#39;];
        $user_exists[&#39;province&#39;]   = $user[&#39;province&#39;];
        $user_exists[&#39;headimgurl&#39;]  = $user[&#39;headimgurl&#39;];
        $user_exists[&#39;sex&#39;]      = $user[&#39;sex&#39;];
        $user_exists[&#39;fullname&#39;]   = $user[&#39;nickname&#39;];
        $user_exists[&#39;telphone&#39;]   = &#39;&#39;;
        $user_exists[&#39;login_ip&#39;]   =$this->input->ip_address();
        $user_exists[&#39;last_ip&#39;]    =$this->input->ip_address();
        $user_exists[&#39;groups&#39;]    = REGISTER_GROUP_ID;
        $user_exists[&#39;status&#39;]    = 1;
        $user_exists[&#39;login_time&#39;]  = date("Y-m-d");
         $insert_id = $this->Coupon_model->insert_one(&#39;cou_user&#39;,$user_exists);
        $user_exists[&#39;uid&#39;] = $insert_id;
        }
        else{
         $user_exists = $user_exists[0];
        }
        // $return_url = $this->session->back_url;
        // if(isset($return_url))header(&#39;location:&#39;.$return_url);
        /*由Coupon_idex中的Get_Coupon处理*/
        $this->session->set_userdata($user_exists);
        if(isset($this->session->return_url))header(&#39;location:&#39;.$this->session->return_url);
        // print_r($user_exists);exit();
        header(&#39;location:&#39;.$redirect);
    }
    function Coupon_start()
    {
      /*进入领取页面,需要先经过授权*/
      $redirect_url = &#39;Coupon/Coupon_index/User_exists&#39;;
      $redirect = urlencode(&#39;http://yourwebname.com/coupon/index.php/&#39;.$redirect_url);
      // $redirect = urlencode(&#39;http://yourwebname.com/coupon/index.php/Coupon/Coupon_index/Get_code&#39;);
      $return = $this->weixin->redirect_url($redirect);
       header(&#39;location:&#39;.$return);
    }
    public function Get_code()
    {
      if(isset($_GET[&#39;code&#39;]))
      {
        $code = $_GET[&#39;code&#39;];
        // echo $code;exit();
        $user_arr = $this->weixin->access_token($code);
        //跳转到用户检测中check_exists()去
        // echo $user_arr;exit();
        // var_dump($user_arr);
        return $user_arr;
      }else{
        //否则检测cookie中是否存在该用户,如果有,则return回首页
          echo &#39;error&#39;;
      }
     }
     public function Coupon_Get()
     {
      /*获取商家bid,读取相关信息*/
      // $b_name = $this->uri->segment(4, 0);
      $nickname = $this->session->nickname;
      $openid = $this->session->openid;
      $status = $this->session->status;
      $_SESSION[&#39;return_url&#39;] = $_SERVER[&#39;REQUEST_URI&#39;];
      // $this->session->set_userdata($return_url);
      // echo $this->session->return_url;exit();
      if(empty($nickname))header(&#39;location:&#39;.&#39;http://yourwebname.com/coupon/index.php/Coupon/Coupon_index/Coupon_start&#39;);
      $bid = $this->uri->segment(5, 0);
      /*扔进Coupon_model中,读取bid中的商家信息*/
      $content = $this->Coupon_model->Coupon_Business(&#39;cou_business&#39;,$bid);
      // print_r($content);
      // echo $bid;
      // echo $b_name;
      $data[&#39;bname&#39;]   = $content[&#39;bname&#39;];
      $data[&#39;discount&#39;]  = $content[&#39;discount&#39;];
      $data[&#39;bimg&#39;]    = $content[&#39;bimg&#39;];
      $data[&#39;contents&#39;]  = $content[&#39;contents&#39;];
      $data[&#39;amount&#39;]   = $content[&#39;amount&#39;];
      $data[&#39;nickname&#39;]  = $nickname;
      $data[&#39;status&#39;]   = $status;
      $data[&#39;js&#39;] = json_encode(array($content[&#39;bname&#39;],$content[&#39;discount&#39;],$nickname,$status));
      // echo $data[&#39;js&#39;];exit();
      // print_r($data);
      $this->load->view(&#39;/coupon/index.html&#39;,$data);
      // echo $nickname;
      // echo $status;
    }
}

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to PHP Chinese net!

Related recommendations:

About the CI framework to implement ajax paging and all selection, inverse selection, no selection and batch deletion code

How to use CI framework to achieve front-end and back-end separation of the framework

The above is the detailed content of Analysis of WeChat web page authorization library based on CI framework. 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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)