生成二维码

<?php

/**

* @Author 焦

* @DateTime 2020-08-19

*/


namespace Home\Controller;

use Think\Controller;


class QrcodeController extends Controller {

//生成二维码
public function my_ewm()
{

$appid = '';
$appsecret = '';//appid对应的appsecret
header('content-type:text/html; charset=utf-8');
//$_POST=$_REQUEST;
$openid =$_POST['openid'];
$user = M("user")->where(["openid" => $openid])->find();
if (!$openid) {
$data = array("result" => '2', "message" => "参数有误!"); //组装JSON
echo json_encode($data); //返回
die;
}
$goodsid = $user['id'];
if (!$goodsid) {
echo "空的id!";
die;
}
$filename = $goodsid . '.jpg';
$file = './Public/qrcode/' . $filename;
$scene = "?scene=" . $goodsid;
if (file_exists($file)) {
$arr="http://yuqiangkt.com/Public/qrcode/" . $filename . "" . $scene;
$data = array("result" => '1', "message" => "成功", "list" => $arr); //组装JSON
echo json_encode($data); //返回
die;
// echo "<script>location.href='http://zgmm.a40.com.cn/Public/qrcode/" . $filename . "" . $scene . "'</script>";
} else {
//请求accesstoken接口
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
$https = true;
$method = 'get';
$data = null;
//get curl传值
$str = $this->get_curl($url, $data, $method);
//获取请求到的结果讲上面获取的accresstoken进行解码成数组,然后获取accesstoken值
$arr = json_decode($str, true);
// dump($arr);die;
$access_token = $arr['access_token'];
//获取二维码,但是切记这里accesstoken不能用通过post传值,只能用get传值
$width = 430;
$url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token=' . $access_token;
//$data['scene']=$goodsid;//"t_id=".$userinfo['id'];
//$data['path']='pages/home/homedetail';
//$data['width']=$width;
$data['path'] = 'pages/saoma/saoma?id=' . $goodsid;
$data['width'] = $width;
$post_data = json_encode($data);
$https = true;
$method = 'post';
//post curl传值
$str = $this->get_curl($url, $post_data, $method);
//进行保存
$res = file_put_contents($file, $str);
//如果保存成功返回路径
if ($res != 0) {
$arr="http://yuqiangkt.com/Public/qrcode/" . $filename . "" . $scene;
$data = array("result" => '1', "message" => "成功", "list" => $arr); //组装JSON
echo json_encode($data); //返回
die;

} else {
echo "生成小程序码出错!";
}
}

}
public function get_curl($url, $data = null, $headers = array())
{
$curl = curl_init();
if (count($headers) >= 1) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($curl, CURLOPT_URL, $url);

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

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);
return $output;
}
}

posted @ 2020-10-21 16:42  php毛宏历的博客  阅读(134)  评论(0编辑  收藏  举报