6
头图

need

Self-developed small programs, such as community, e-commerce, news, blog and other types of small programs, will need to store a lot of pictures, picture resources will bring a lot of costs to individual developers, in case of heavy traffic, website bandwidth, The traffic will also be overwhelmed, so the image resources must not be stored in their own servers, and the elastic storage provided by many manufacturers is also paid on demand.

idea

The WeChat public platform provides a material management, which can upload pictures, videos, audios and other types of materials, so is it possible to upload the picture materials and get the url as the picture server for your own applet project? No problem at all!

According to the development document: After the permanent image material is added, it will be returned to the developer with a URL, and the developer can use it within the Tencent domain name (if it is used outside the Tencent domain name, the image will be blocked). To put it simply, you can only use the URL of this image material on Tencent's platform, otherwise it cannot be displayed because there is an anti-theft chain.

develop

According to the [Add permanent material] interface provided by the development documentation of the WeChat public platform, the following steps are used to upload image materials to the WeChat server.

  1. get access_token
  2. Call the new permanent material interface to upload material
  3. Get the permanent URL of the material

code show as below:

 <?php

// 返回JSON
header("Content-type:application/json");
// 允许上传的图片后缀
$allowedExts = array("jpeg", "jpg", "png");
// 后缀名
if ($allowedExts[0] == 'jpeg') {
    $hzm = 'jpg';
}else{
    $hzm = $allowedExts[0];
}
// 获取选择的文件
$temp = explode(".", $_FILES["file"]["name"]);
// 获取文件后缀名
$extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 10485760)
&& in_array($extension, $allowedExts)){
    if ($_FILES["file"]["error"] > 0){
        $result = array(
            'code' => 201,
            'msg' => '上传失败'.$_FILES["file"]["error"]
        );
    }else{
        // 重命名
           $new_file = date("Y-m-d")."-".rand(10000,99999).".".$hzm;
           // 上传到自己的服务器
        move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$new_file);
        // 获取真实地址
        $filepath = realpath(dirname(__FILE__));
        $upload_filepath = $filepath."/upload/".$new_file;
        // 上传到微信服务器
        $imgurl = upload_img($upload_filepath);
        // 验证上传结果
        if(strpos($imgurl,'http') !== false){

            // 上传成功
            $result = array(
                'code' => 200,
                'msg' => '上传成功',
                'url' => $imgurl
            );
            // 删除本地素材
            unlink($upload_filepath);
        }else{

            // 上传失败
            $result = array(
                'code' => 202,
                'msg' => '上传失败'
            );
        }
    }
}

// 获取access_token
function getToken(){
    // appid和secret
    $appid='填写你公众号的appid';
    $appsecret='填写你公众号的appsecret';
    // 读取access_token
    include './access_token.php';
    // 判断是否过期
    if (time() > $access_token['expires']){
        // 如果已经过期就得重新获取并缓存
        $access_token = array();
        $access_token['access_token'] = getNewToken($appid,$appsecret);
        $access_token['expires']=time()+7000;
        // 将数组写入php文件
        $arr = '<?php'.PHP_EOL.'$access_token = '.var_export($access_token,true).';'.PHP_EOL.'?>';
        $arrfile = fopen("./access_token.php","w");
        fwrite($arrfile,$arr);
        fclose($arrfile);
        // 返回当前的access_token
        return $access_token['access_token'];
    }else{
        // 如果没有过期就直接读取缓存文件
        return $access_token['access_token'];
    }
}
// 获取新的access_token
function getNewToken($appid,$appsecret){
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
    $access_token_Arr =  https_request($url);
    return $access_token_Arr['access_token'];
}
// curl请求函数
function https_request ($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $out = curl_exec($ch);
    curl_close($ch);
    return  json_decode($out,true);
}
// 上传图片素材到微信服务器
function upload_img($realpath){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token='.getToken().'&type=image');
    $data = array(
        'media' => new CURLFile($realpath)
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $upimg = curl_exec($ch);
    return json_decode($upimg)->url;
    curl_close($ch);
}

// 返回JSON对象
echo json_encode($result,JSON_UNESCAPED_UNICODE);
?>

request return

 {"media_id":"8IZhZUPXxsG_omeA5giO5By8VyHnjk7_oy0Co9jVWwxpgm-sqhx_Hkz_9rLVF9Ws","url":"http:\/\/mmbiz.qpic.cn\/mmbiz_png\/5zLSKyuEW2Kt5ZGZg7XUx05QyGOVFCpHqKic74qQP4gxzQJYXjwN4aGEiadtfUXax4fCXXV5ia1UnvSwdqxuqLCqA\/0?wx_fmt=png","item":[]}

code explanation

  1. First upload the image from the client (mini program) to the upload directory of your own server
  2. Then call the new permanent material interface to upload from the upload directory to the WeChat server
  3. You need to configure the appid and appsecret of the official account to obtain access_token
  4. The new permanent material interface needs to pass in the access_token before it can be called
  5. The validity period of the access_token is 2 hours. You can obtain access_token up to 2000 times a day. If you exceed the number of times, you will not be able to obtain it. In order to ensure that you can always obtain a new token, you cannot obtain a new access_token every time you upload it. 2000 times used up. The access_token can be used as long as it is within 2 hours, so the access_token needs to be cached. getToken() This function is the step of caching the access_token (if the access_token has exceeded 2 hours, get a new access_token and cache it locally, if the access_token has not exceeded 2 hours, directly read the locally cached access_token)
  6. To obtain the access_token interface, you need to configure the whitelist ip address in the security center of the official account background

Notice

The picture link can only be used on the platform of Tencent domain name, and cannot be displayed on the self-built website. This article mainly uses the applet to call the permanent picture material, which can be used!

Tips

If you need to use the URL of the permanent image material under the non-Tencent domain name, you need to match the anti-leech protection picture springboard, similar to http://xxx.com/?imgurl=永久图片素材URL to bypass the anti-leech protection. In short, it is an image server proxy.

author

TANKING


TANKING
4.8k 声望493 粉丝

热爱分享,热爱创作,热爱研究。