


Analysis 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('BASEPATH')) exit('No direct script access allowed'); Class Weixin { private $appId; private $appSecret; function __construct() { $this->appId = trim('你的appid'); $this->appSecret = trim('你的appsecret'); } 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['access_token']; $openid = $return['openid']; /*获取微信用户数据*/ $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('Content-Type:text/html;charset=utf-8'); // 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['uid'] = $value['uid']; // $_SESSION['nickname'] = $value['nickname']; // $_SESSION['fullname'] = $value['fullname']; // $_SESSION['status'] = $value['status']; // $_SESSION['groups'] = $value['groups']; $_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('BASEPATH')) exit('No direct script access allowed'); Class Coupon_index extends CI_Controller { function __construct() { parent::__construct(); $this->load->library(array('weixin','session')); $this->load->helper('url'); // $this->load->ldap_mod_del(link_identifier, dn, entry) $this->load->model('Coupon_model'); } /** *优惠券主程序 */ function index() { $this->load->view('/coupon/index.html'); } 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('cou_user',$user); // print_r($user_exists);exit(); // $redirect = 'http://yourwebname.com/coupon/index.php/Coupon/Coupon_index/Coupon_Get/bid/1'; // $return_url = $this->session->return_url; $redirect = 'http://yourwebname.com'.$this->session->return_url; // echo $redirect;exit(); if(empty($user_exists)) { /* 由于微信获取到的用户数据是stdclass对象格式 所以需要进行转换成数组 使用 obj_to_arr方式 */ //加入自定义的字符进入数组 unset($user['privilege']); $user_exists['nickname'] = $user['nickname']; $user_exists['openid'] = $user['openid']; $user_exists['language'] = $user['language']; $user_exists['city'] = $user['city']; $user_exists['country'] = $user['country']; $user_exists['province'] = $user['province']; $user_exists['headimgurl'] = $user['headimgurl']; $user_exists['sex'] = $user['sex']; $user_exists['fullname'] = $user['nickname']; $user_exists['telphone'] = ''; $user_exists['login_ip'] =$this->input->ip_address(); $user_exists['last_ip'] =$this->input->ip_address(); $user_exists['groups'] = REGISTER_GROUP_ID; $user_exists['status'] = 1; $user_exists['login_time'] = date("Y-m-d"); $insert_id = $this->Coupon_model->insert_one('cou_user',$user_exists); $user_exists['uid'] = $insert_id; } else{ $user_exists = $user_exists[0]; } // $return_url = $this->session->back_url; // if(isset($return_url))header('location:'.$return_url); /*由Coupon_idex中的Get_Coupon处理*/ $this->session->set_userdata($user_exists); if(isset($this->session->return_url))header('location:'.$this->session->return_url); // print_r($user_exists);exit(); header('location:'.$redirect); } function Coupon_start() { /*进入领取页面,需要先经过授权*/ $redirect_url = 'Coupon/Coupon_index/User_exists'; $redirect = urlencode('http://yourwebname.com/coupon/index.php/'.$redirect_url); // $redirect = urlencode('http://yourwebname.com/coupon/index.php/Coupon/Coupon_index/Get_code'); $return = $this->weixin->redirect_url($redirect); header('location:'.$return); } public function Get_code() { if(isset($_GET['code'])) { $code = $_GET['code']; // 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 'error'; } } 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['return_url'] = $_SERVER['REQUEST_URI']; // $this->session->set_userdata($return_url); // echo $this->session->return_url;exit(); if(empty($nickname))header('location:'.'http://yourwebname.com/coupon/index.php/Coupon/Coupon_index/Coupon_start'); $bid = $this->uri->segment(5, 0); /*扔进Coupon_model中,读取bid中的商家信息*/ $content = $this->Coupon_model->Coupon_Business('cou_business',$bid); // print_r($content); // echo $bid; // echo $b_name; $data['bname'] = $content['bname']; $data['discount'] = $content['discount']; $data['bimg'] = $content['bimg']; $data['contents'] = $content['contents']; $data['amount'] = $content['amount']; $data['nickname'] = $nickname; $data['status'] = $status; $data['js'] = json_encode(array($content['bname'],$content['discount'],$nickname,$status)); // echo $data['js'];exit(); // print_r($data); $this->load->view('/coupon/index.html',$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:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



DeepSeek: A powerful AI image generation tool! DeepSeek itself is not an image generation tool, but its powerful core technology provides underlying support for many AI painting tools. Want to know how to use DeepSeek to generate images indirectly? Please continue reading! Generate images with DeepSeek-based AI tools: The following steps will guide you to use these tools: Launch the AI Painting Tool: Search and open a DeepSeek-based AI Painting Tool (for example, search "Simple AI"). Select the drawing mode: select "AI Drawing" or similar function, and select the image type according to your needs, such as "Anime Avatar", "Landscape"

Gate.io, a leading cryptocurrency trading platform founded in 2013, provides Chinese users with a complete official Chinese website. The website provides a wide range of services, including spot trading, futures trading and lending, and provides special features such as Chinese interface, rich resources and community support.

The OKX trading platform offers a variety of rates, including transaction fees, withdrawal fees and financing fees. For spot transactions, transaction fees vary according to transaction volume and VIP level, and adopt the "market maker model", that is, the market charges a lower handling fee for each transaction. In addition, OKX also offers a variety of futures contracts, including currency standard contracts, USDT contracts and delivery contracts, and the fee structure of each contract is also different.

Gateio Exchange app download channels for old versions, covering official, third-party application markets, forum communities and other channels. It also provides download precautions to help you easily obtain old versions and solve the problems of discomfort in using new versions or device compatibility.

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

Gate.io (Sesame Open Door) is the world's leading cryptocurrency trading platform. This article provides a complete tutorial on spot trading of Gate.io. The tutorial covers steps such as account registration and login, KYC certification, fiat currency and digital currency recharge, trading pair selection, limit/market transaction orders, and orders and transaction records viewing, helping you quickly get started on the Gate.io platform for cryptocurrency trading. Whether a beginner or a veteran, you can benefit from this tutorial and easily master the Gate.io trading skills.

Learn to easily copy Xiaohongshu copywriting! This tutorial teaches you step by step how to quickly copy Xiaohongshu video copy, saying goodbye to tedious steps. Open the Xiaohongshu APP, find the video you like, and click on the [Copywriting] area below the video. Long press the copy text and select the [Extract Text] function from the pop-up options. The system will automatically extract the text, click the [Copy] button in the lower left corner. Open WeChat or other applications, such as Moments, long press the input box, and select [Paste]. Click Send to complete the copy. It's that simple!

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.
