评论

图片上传(营销)demo_PHP版本

如果还有任何疑问可以私聊我或者评论区留言

将图片路径,商户号,证书编号,证书私钥改为您们自己的信息直接可以测试使用

<?php


//生成signature

//HTTP请求方法\r\n

//URI\r\n

//请求时间戳\r\n

//请求随机串\r\n

//请求报文\r\n


//这里设置您的图片文件名,要绝对路径

$file_name = "20191118194045.jpg";

$file_content = file_get_contents($file_name);


$HTTP_METHOD = "POST";

$URI="/v3/marketing/favor/media/image-upload";

$TIMESTAMP = time();//保证最新

$NONSTR = "LXKE2XSYGXJWYNHO";

$sp_mchid = '商户号';

$serial_no = '证书编号';

$MCHPRIKEYSTR = "证书私钥";


//生成图片meta信息

$meta = str_replace(array("FILENAME", "SHA256"), array($file_name, hash("sha256", $file_content)), "{\"filename\":\"FILENAME\",\"sha256\":\"SHA256\"}");


$raw_str = $HTTP_METHOD."\n".$URI."\n".$TIMESTAMP."\n".$NONSTR."\n".$meta."\n";

$prikey = openssl_pkey_get_private($MCHPRIKEYSTR);

$algo = "sha256WithRSAEncryption";


openssl_sign($raw_str, $signature, $prikey, $algo);


openssl_free_key($prikey);


//拼接请求body

$final_sign = base64_encode($signature);

$post_body = "--eklfile\r\nContent-Disposition:form-data;name=\"meta\"\r\nContent-Type:application/json\r\n\r\n".$meta."\r\n--eklfile\r\nContent-Disposition:form-data;name=\"file\";filename=\"".$file_name."\"\r\nContent-Type:image/jpg\r\n\r\n". $file_content."\r\n--eklfile--\r\n";




$authorization = 'WECHATPAY2-SHA256-RSA2048 mchid="SPMCHID",nonce_str="NONSTR",signature="SIGNATURE",timestamp="TIMESTAMP",serial_no="SERIAL_NO"';


$authorization = str_replace(array("SPMCHID", "NONSTR", "SIGNATURE", "TIMESTAMP", "SERIAL_NO"), array($sp_mchid, $NONSTR, $final_sign, $TIMESTAMP, $serial_no), $authorization);


$URL = "https://api.mch.weixin.qq.com".$URI;


function curl_post($url, $body, $headers)

{


    $ch = curl_init();

    $timeout = 300;

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_POST, true);

//注意,使用curl方法,必须制定content内容为二进制转化

    curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $handles = curl_exec($ch);

    curl_close($ch);

    return $handles;

}


$headers = [

    'Accept:application/json',

    'Authorization:'.$authorization,

    'Content-Type:multipart/form-data;boundary=eklfile',

    'User-Agent:CURL/7.54.0'

];


$res = curl_post($URL, $post_body, $headers);

var_dump($res);

exit;

最后一次编辑于  2021-03-22  
点赞 1
收藏
评论

1 个评论

  • Memory
    Memory
    2021-03-22

    上github地址吧

    2021-03-22
    赞同
    回复 1
    • 陈久胜
      陈久胜
      2021-03-23
      可以
      2021-03-23
      回复
登录 后发表内容