需要引入 GuzzleHttp 包
composer require guzzlehttp/guzzle
核心代码如下:
<?php
require __DIR__ . './vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
/**
* get client
* @return Client
*/
function httpGetClient()
{
static $client ;
if (!$client) {
$client = new Client();
}
return $client;
}
//GET
function httpGet($url)
{
$client = httpGetClient();
$options = [
'verify' => false,
];
$response = $client->get($url,$options);
return $response->getBody()->getContents();
}
// POSTBODY
function httpPostBody($url, $requestData=[], $header=[])
{
$client = httpGetClient();
$options = [
'headers' => $header,
'body' => json_encode($requestData,JSON_UNESCAPED_UNICODE ),
'verify' => false,
];
$response = $client->post($url, $options);
if ($response->getStatusCode()==200) {
return $response->getBody()->getContents();
}else{
return null;
}
}
//postForm
function httpPostForm($url, $requestData, $header)
{
$client = new Client(['verify' => false]);
try {
$response = $client->request('post', $url, ['form_params' => $requestData, 'headers' => $header]);
$response->getStatusCode(); // 200
$response->getHeaderLine('content-type');
if ($response->getStatusCode()==200) {
return [true,$response->getBody()->getContents()];
}else{
return [false,[]];
}
} catch (GuzzleException $e) {
}
return [false,[]];
}
function getAccessToken(){
$appid = '';
$secret = '';
//获取access_token
$access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
$access_token_data = httpGet($access_token_url);
$access_token_data = json_decode($access_token_data,true);
return $access_token_data['access_token'];
}
function getQrcode($access_token){
$url = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token='.$access_token;
$requestData = [
'path'=>'pages/order-status/index?loose_id=1',
'width'=>430,
];
$header = [];
return httpPostBody($url,$requestData,$header);
}
$access_token = getAccessToken();
//$access_token = "";
$data = getQrcode($access_token);
if(is_null(json_decode($data))){
//不是json数据, 有数据流,返回值为null
$jpg = $data;
//创建文件写入
$file = fopen("img/test.jpg",'w');
fwrite($file,$jpg);
fclose($file);
}else{
//不是数据流,则代表有错误发生
$data_array = json_decode($data,true);
print_r($data_array);
}
?>
如果提示你无法写入, 记得新建一个文件夹: img ,并给可写权限
评论 (0)