获取access_token
$appId = $this->appId;
$appSecret = $this->appSecret;
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$json_info = json_decode($output, true);
$access_token = $json_info["access_token"];
生成二维码
// 生成二维码参数
$id = "";
$postData = [
'action_name' => 'QR_LIMIT_STR_SCENE', // 二维码类型,QR_SCENE为临时的整型参数值,QR_STR_SCENE为临时的字符串参数值,QR_LIMIT_SCENE为永久的整型参数值,QR_LIMIT_STR_SCENE为永久的字符串参数值
'action_info' => [
'scene' => [
'scene_str' => $id // 场景值
]
]
];
$postData = json_encode($postData);
$qrcodeUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$access_token}";
$ch = curl_init($qrcodeUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($ch);
curl_close($ch);
$responseData = json_decode($response, true);
$ticket = $responseData['ticket'];
// 获取二维码图片
$qrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={$ticket}";
$qrcodeResponse = file_get_contents($qrcodeUrl);
// 保存二维码图片
$qrcodeFile = $id . '.png';
file_put_contents($qrcodeFile, $qrcodeResponse);
扫描二维码
扫描二维码之后,微信会将二维码的场景值回调到,填写的服务器地址URL中
服务端代码
// 微信回调的场景XML数据
$wechat_xml = file_get_contents('php://input');
// 服务器配置中的 令牌(Token)
$token = '';
$data = $this->request->get();
$data['signature'] = $data['signature'];
$data['timestamp'] = $data['timestamp'];
$data['nonce'] = $data['nonce'];
$data['echostr'] = $data['echostr'];
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
// 。。。。。。
/**
* 可以选择在这里,对接收到的二维码参数,进行处理
*/
// 。。。。。。。
if ($tmpStr == $signature) {
return $data['echostr'];
} else {
return false;
}
如果扫描二维码在公众号聊天记录中出现【该公众号提供的服务出故障,请稍后再试】,请检查是否开启debug模式,关掉后等待片刻再试。仅针对ThinkPHP,其他框架请自行测试