/**生成小程序二维码**/
public function actionGetWxcode()
{
/*获取参数*/
$path = Yii::$app->request->get('path');
$width = Yii::$app->request->get('width');
/*获取access_token*/
$access_token = $this->getToken();
/*拼接地址*/
$url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $access_token;
/*请求参数*/
$post_data = [
'path' => $path,
'width' => $width,
];
$post_data = json_encode($post_data);
$data = $this->send_post($url, $post_data);
$data = 'image/png;base64,' . base64_encode($data);
$imageName = rand(100000, 999999) . '.png';
if (strstr($data, ",")) {
$image = explode(',', $data);
$image = $image[1];
}
$dir = "uploads/img/" . date("Y-m-d", time());
if (!is_dir($dir)) { //判断目录是否存在 不存在就创建
mkdir($dir, 0777, true);
$re = [
'data' => null,
"code" => 200,
"msg" => "创建目录失败",
];
return json_encode($re, JSON_UNESCAPED_UNICODE);
}
$imageSrc = $dir . "/" . $imageName; //图片名字
$r = file_put_contents($imageSrc, base64_decode($image));//返回的是字节数
if (!$r) {
$re = [
'data' => null,
"code" => 200,
"msg" => "图片生成失败",
];
return json_encode($re, JSON_UNESCAPED_UNICODE);
} else {
$re = [
'code' => 100,
'msg' => '图片生成成功',
'path' => 'https://' . $_SERVER['HTTP_HOST'] . "/" . $imageSrc
];
return json_encode($re, JSON_UNESCAPED_UNICODE);
}
}
/**
* 消息推送http
* @param $url
* @param $post_data
* @return bool|string
*/
protected function send_post($url, $post_data)
{
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/json',
//header 需要设置为 JSON
'content' => $post_data,
'timeout' => 60
//超时时间
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}