在CodeIgniter框架中实现微信小程序码生成,核心是通过框架封装HTTP请求调用微信官方提供的小程序码生成接口,整个过程需要处理好配置管理、access_token获取、请求参数构造和结果处理四个环节。

前期准备工作
首先需要准备两个必要的参数,这两个参数可以在微信公众平台的小程序管理后台获取:
- 小程序的appid,是小程序唯一的身份标识
- 小程序的appsecret,是接口调用的重要密钥,注意不要泄露
配置参数管理
在CodeIgniter中建议将微信相关的配置放到配置文件里,方便后续维护。可以在application/config目录下新建wechat.php配置文件:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['wechat_appid'] = '你的小程序appid';
$config['wechat_appsecret'] = '你的小程序appsecret';
$config['wechat_access_token_url'] = 'https://api.weixin.qq.com/cgi-bin/token';
$config['wechat_qrcode_url'] = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit';
获取access_token
微信所有的接口调用都需要使用access_token,这个凭证有效期是7200秒,建议做缓存处理避免频繁请求。下面封装获取access_token的方法:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Wechat_lib {
protected $CI;
protected $appid;
protected $appsecret;
protected $token_url;
protected $cache_time = 7000; // 缓存时间,小于7200秒避免过期
public function __construct() {
$this->CI =& get_instance();
$this->CI->config->load('wechat');
$this->appid = $this->CI->config->item('wechat_appid');
$this->appsecret = $this->CI->config->item('wechat_appsecret');
$this->token_url = $this->CI->config->item('wechat_access_token_url');
}
/**
* 获取access_token,优先从缓存读取
*/
public function get_access_token() {
$cache_key = 'wechat_access_token_' . $this->appid;
$token = $this->CI->cache->get($cache_key);
if ($token) {
return $token;
}
// 缓存不存在则请求接口获取
$url = $this->token_url . '?grant_type=client_credential&appid=' . $this->appid . '&secret=' . $this->appsecret;
$result = $this->http_request($url);
$data = json_decode($result, true);
if (isset($data['access_token'])) {
// 存入缓存
$this->CI->cache->save($cache_key, $data['access_token'], $this->cache_time);
return $data['access_token'];
}
// 获取失败抛出异常
throw new Exception('获取access_token失败:' . (isset($data['errmsg']) ? $data['errmsg'] : '未知错误'));
}
/**
* 封装HTTP请求方法
*/
private function http_request($url, $data = null) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
if ($data) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
}
实现小程序码生成接口
微信提供了多个小程序码生成接口,这里以getwxacodeunlimit接口为例,这个接口支持生成数量无限制的小程序码,适合大部分业务场景。下面在控制器中编写生成小程序码的方法:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Qrcode extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('wechat_lib');
$this->load->config('wechat');
}
/**
* 生成小程序码接口
*/
public function generate() {
try {
// 获取请求参数,scene是小程序码携带的自定义参数
$scene = $this->input->post('scene', true);
$page = $this->input->post('page', true); // 小程序页面路径
if (empty($scene)) {
json_output(['code' => 400, 'msg' => 'scene参数不能为空']);
return;
}
// 获取access_token
$access_token = $this->wechat_lib->get_access_token();
$qrcode_url = $this->config->item('wechat_qrcode_url') . '?access_token=' . $access_token;
// 构造请求参数
$post_data = [
'scene' => $scene,
'page' => $page ?: 'pages/index/index', // 默认首页
'width' => 430, // 小程序码宽度
'auto_color' => false,
'line_color' => ['r' => '0', 'g' => '0', 'b' => '0']
];
// 发送请求
$result = $this->wechat_lib->http_request($qrcode_url, json_encode($post_data));
// 判断返回结果是否是图片
$content_type = curl_getinfo($this->wechat_lib->get_last_curl(), CURLINFO_CONTENT_TYPE);
if (strpos($content_type, 'image') !== false) {
// 直接输出图片
header('Content-Type: image/png');
echo $result;
exit;
} else {
// 返回错误信息
$err_data = json_decode($result, true);
json_output(['code' => 500, 'msg' => '生成小程序码失败:' . $err_data['errmsg']]);
}
} catch (Exception $e) {
json_output(['code' => 500, 'msg' => $e->getMessage()]);
}
}
}
请求示例与结果处理
前端调用该接口时,可以传递对应的参数,示例请求如下:
// 前端请求示例
fetch('/qrcode/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'scene=uid_123&page=pages/user/index'
})
.then(res => {
if (res.headers.get('content-type').indexOf('image') !== -1) {
// 处理返回的图片,比如转成base64或者直接展示
return res.blob();
} else {
return res.json();
}
})
.then(data => {
if (data instanceof Blob) {
const imgUrl = URL.createObjectURL(data);
console.log('小程序码地址:', imgUrl);
} else {
console.error('生成失败:', data.msg);
}
});
注意事项
- 小程序码的page参数必须是已经发布的小程序存在的页面,否则会生成失败
- scene参数的长度不能超过32个字符,且只能是数字、大小写字母以及部分特殊字符
- 如果生成的小程序码需要长期保存,建议将生成的图片存储到服务器或者对象存储中,避免重复调用接口
- 生产环境建议对接口做权限校验,避免被恶意调用消耗接口配额
以上就是CodeIgniter框架实现微信小程序码生成的完整流程,按照步骤配置后就可以快速对接微信接口生成对应的小程序码,满足业务中的分享、推广等需求。
CodeIgniter微信小程序码接口调用小程序开发修改时间:2026-06-16 20:30:54