cdkey 2020-04-17
使用到微信接口是“生成带参数的二维码”,可以生成两种二维码,一种是临时二维码,会过期,生成量大,主要用于帐号绑定等不要求二维码永久保存的业务场景;另一种是永久二维码,没有过期时间,但生成量小(目前为最多10万个),主要用于适用于帐号绑定、用户来源统计等场景。扫码之后,如果用户没关注公众号会提示关注,如果已关注就直接进入公众号对话框。

首先创建二维码ticket,然后凭借ticket到指定URL换取二维码,具体介绍可以看官方文档 https://developers.weixin.qq.com/doc/offiaccount/Account_Management/Generating_a_Parametric_QR_Code.html
示例代码:
<?php
namespace app\index\controller;
use think\Controller;
/**
* 微信类
*/
class Wechat extends Controller
{
protected $APPID = ‘xxxxxxxxxxx‘;
protected $APPSECRET = ‘xxxxxxxxxxxxxx‘;
/**
* curl请求
*/
public function http_curl($url, $type = ‘get‘, $res = ‘json‘, $arr = ‘‘){
$cl = curl_init();
curl_setopt($cl, CURLOPT_URL, $url);
curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, false);
if($type == ‘post‘){
curl_setopt($cl, CURLOPT_POST, 1);
curl_setopt($cl, CURLOPT_POSTFIELDS, $arr);
}
$output = curl_exec($cl);
curl_close($cl);
return json_decode($output, true);
if($res == ‘json‘){
if( curl_error($cl)){
return curl_error($cl);
}else{
return json_decode($output, true);
}
}
}
/**
* 获取 AccessToken
*/
public function getAccessToken()
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->APPID."&secret=".$this->APPSECRET;
// 先判断 access_token 文件里的token是否过期,没过期继续使用,过期就更新
$data = json_decode($this->get_php_file(ROOT_PATH."public".DS."wxtxt".DS."access_token.txt"));
// 过期 更新
if ($data->expire_time < time()) {
$res = $this->http_curl($url);
$access_token = $res[‘access_token‘];
if ($access_token) {
// 在当前时间戳的基础上加7000s (两小时)
$data->expire_time = time() + 7000;
$data->access_token = $res[‘access_token‘];
$this->set_php_file(ROOT_PATH."public".DS."wxtxt".DS."access_token.txt",json_encode($data));
}
}else{
// 未过期 直接使用
$access_token = $data->access_token;
}
return $access_token;
}
// 获取存储文件中的token ticket
private function get_php_file($filename) {
return trim(file_get_contents($filename));
}
// 把token ticket 存储到文件中
private function set_php_file($filename, $content) {
$fp = fopen($filename, "w");
fwrite($fp, $content);
fclose($fp);
}
/**
* 生成二维码
*/
public function getQrcode(){
$token = $this->getAccessToken();
$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$token";
$param = array();
$param[‘action_name‘] = "QR_LIMIT_SCENE";
$param[‘action_info‘] = array( ‘scene‘ => array( ‘scene_id‘=>‘123‘ ) );
$param = json_encode($param);
// 获取二维码的ticket和二维码图片解析地址
$res = $this->http_curl($url, ‘post‘, ‘json‘, $param);
// 通过ticket换取二维码
$qrcode = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$res[‘ticket‘];
//输出二维码图片路径 echo "<center><img src=".$qrcode."></center>";
}
}运行getQrcode()方法,效果如下

<?php. if (!empty($_POST)) {. $data1 = $_POST["data1"];$data2 = $_POST["data2"];$fuhao = $_POST["fuh