php使用curl新增微信临时素材(上传图片)

<?php

$APPID = '';
$APPSECRET = '';
$info = json_decode(file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET"));
//获取token
$access_token = $info->access_token;

/* 使用curl函数 */
$url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=image";;
$data = array(
    'media' => '@./gm1.png',
);

$response = request($url, 'post', $data);
$params = array();
$params = json_decode($response, true);
if (isset($params['errcode'])) {
    echo "error:" . $params['errcode'];
    echo "msg :" . $params['errmsg'];
    exit;
}
var_dump($params);
/**
 * http请求方式: 默认GET
 */

function request($url, $method = 'get', $data = null)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
    if ($ssl) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    }
    switch ($method) {
        case 'post':
            $hadFile = false;
            curl_setopt($ch, CURLOPT_POST, 1);
            if (is_array($data)) {
                if (class_exists('\CURLFile')) {
                    foreach ($data as $key => $value) {
                        if (is_string($value) && strpos($value, '@') === 0 && is_file(realpath(ltrim($value, '@')))) {
                            $data[$key] = new \CURLFile(realpath(ltrim($value, '@')));
                            $hadFile = true;
                        }
                    }
                } elseif (defined('CURLOPT_SAFE_UPLOAD')) {
                    $hadFile = true;
                }
        }
$datastr = (!$hadFile && is_array($data)) ? http_build_query($data) : $data; curl_setopt($ch, CURLOPT_POSTFIELDS, $datastr); break; } $result = curl_exec($ch); curl_close($ch); if (empty($result)) { exit("错误请求"); } return $result; } //命令不会返回错误 如果返回空 2>&1 输出报错信息 如果乱码就是用 header("content-type:text/html;charset=gbk"); curl下载地址 https://curl.haxx.se/download.html $filepath = './gm1.png'; /* 使用exec函数 */ $command = 'curl -F media=@' . $filepath . ' "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $access_token . '&type=image"'; $retval = array(); exec($command, $retval, $status); $params = array(); $params = json_decode($retval[0], true); if ($status != 0) { $params = array( 'errcode' => '-100', 'errmsg' => '公众号服务出错,请联系管理员', ); } return $params; /* 使用system函数 */ $command = 'curl -F media=@' . $filepath . ' "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $access_token . '&type=image" 2>&1'; $retval = 1; $last_line = system($command, $retval); $params = array(); $params = json_decode($last_line, true); if ($retval != 0) { if (isset($params['errcode'])) { $params = array( 'errcode' => '-100', 'errmsg' => '公众号服务出错,请联系管理员', ); } } return $command;

 

posted @ 2018-07-27 18:38  za_szybko  阅读(2528)  评论(0编辑  收藏  举报