微信網頁授權是開發微信公眾號應用的基礎功能,本文將詳細介紹如何在 CodeIgniter (CI) 框架中封裝並使用微信網頁授權庫,實現靜默授權與用戶信息獲取的完整流程。
首先在 application/libraries 目錄下建立 Weixin.php,封裝授權跳轉、Access Token 換取、用戶信息獲取等核心邏輯:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Weixin {
private $appId;
private $appSecret;
public function __construct() {
$this->appId = trim('你的 AppID');
$this->appSecret = trim('你的 AppSecret');
}
/** 生成授權跳轉 URL */
public 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 並獲取用戶信息 */
public function access_token($code) {
$token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appId}&secret={$this->appSecret}&code={$code}&grant_type=authorization_code";
$result = $this->postdata($token_url);
$access_token = $result['access_token'];
$openid = $result['openid'];
$user_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
$userinfo = json_decode(file_get_contents($user_url));
return $userinfo;
}
/** 檢測 access_token 有效性 */
public function eff($access_token, $openid) {
$url = "https://api.weixin.qq.com/sns/auth?access_token={$access_token}&openid={$openid}";
return json_decode(file_get_contents($url));
}
/** CURL 獲取遠程數據 */
private function postdata($url) {
$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_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return json_decode($output, true);
}
/** 將對象轉為數組 */
public function obj_to_arr($data) {
$data = is_object($data) ? get_object_vars($data) : $data;
foreach ($data as $key => $value) {
$arr[$key] = $value;
}
return $arr;
}
/** 寫入 Session */
public function save_session($data) {
foreach ($data as $key => $value) {
$_SESSION[$key] = $value;
}
return $_SESSION;
}
}
在 Coupon_index 控制器中串聯授權流程:
<?php
class Coupon_index extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library(array('weixin', 'session'));
$this->load->helper('url');
$this->load->model('Coupon_model');
}
/** 入口:發起授權 */
public function Coupon_start() {
$redirect_url = 'Coupon/Coupon_index/User_exists';
$redirect = urlencode('https://yourdomain.com/coupon/index.php/' . $redirect_url);
header('Location: ' . $this->weixin->redirect_url($redirect));
}
/** 微信回調:獲取 code 並換取用戶信息 */
public function Get_code() {
if (isset($_GET['code'])) {
$code = $_GET['code'];
return $this->weixin->access_token($code);
}
echo 'error';
}
/** 用戶存在性檢測與 Session 寫入 */
public function User_exists() {
$user_arr = $this->Get_code();
$user = $this->weixin->obj_to_arr($user_arr);
$user_exists = $this->Coupon_model->CheckUser('cou_user', $user);
if (empty($user_exists)) {
// 新用戶入庫
unset($user['privilege']);
$user['fullname'] = $user['nickname'];
$user['telphone'] = '';
$user['login_ip'] = $this->input->ip_address();
$user['last_ip'] = $this->input->ip_address();
$user['groups'] = REGISTER_GROUP_ID;
$user['status'] = 1;
$user['login_time'] = date("Y-m-d");
$insert_id = $this->Coupon_model->insert_one('cou_user', $user);
$user['uid'] = $insert_id;
} else {
$user = $user_exists[0];
}
$this->session->set_userdata($user);
$redirect = $this->session->return_url ?? 'https://yourdomain.com/coupon/index.php/Coupon/Coupon_index/index';
header('Location: ' . $redirect);
}
/** 優惠券領取頁面 */
public function Coupon_Get() {
$nickname = $this->session->nickname;
if (empty($nickname)) {
header('Location: ' . site_url('Coupon/Coupon_index/Coupon_start'));
return;
}
$bid = $this->uri->segment(5, 0);
$content = $this->Coupon_model->Coupon_Business('cou_business', $bid);
$data = array_merge($content, [
'nickname' => $nickname,
'status' => $this->session->status,
'js' => json_encode([$content['bname'], $content['discount'], $nickname, $this->session->status])
]);
$this->load->view('/coupon/index.html', $data);
}
}
snsapi_userinfo 可獲取用戶詳細信息(需用戶確認授權)。更多 CodeIgniter 實戰技巧請參考專題:《CodeIgniter 入門教程》、《CI 框架進階教程》、《PHP 優秀開發框架總結》。