微信商戶 API 發紅包!

wavebossy6666發表於2019-01-15

程式碼備份錄——微信發紅包

程式碼

$url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";

$mch_billno = strtoupper(Date("YmdHis").str_random(10).rand(1111,9999)); // 商戶訂單號
$nonce_str = substr(md5(time().rand(1,9999)),1,32);
$openid = "";//
$amount = 100; // 單位為分,紅包金額
$data = [
    "nonce_str"=>$nonce_str,
    "mch_billno"=>$mch_billno,
    "mch_id"=>___wx_mch_id,
    "wxappid"=>___wx_appid,
    "send_name"=>___wap_name,
    "re_openid"=>$openid,
    "total_amount"=>$amount,
    "total_num"=>1,
    "wishing"=>"獎勵紅包",
    "client_ip"=>$request->getClientIp(),
    "act_name"=>"完成獎勵",
    "remark"=>"感謝您的支援!",
];
ksort($data);
$sign = strtoupper(md5(ToUrlParams($data)."&key=".___wx_pay_key));
$data = array_merge($data,array("sign"=>$sign));
$data = ToXml($data);
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,"{$url}");
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($curl,CURLOPT_SSLCERT,app_path('Cert/apiclient_cert.pem'));
curl_setopt($curl,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($curl,CURLOPT_SSLKEY,app_path('Cert/apiclient_key.pem'));
$string = curl_exec($curl);
curl_close($curl);
$strpostData = simplexml_load_string($string);
$stringData = [];
Log::info($strpostData);
foreach ($strpostData->children() as $child){
    $stringData = array_merge($stringData,array($child->getName()=>(string)$child));
}
Log::info($stringData);
if($stringData["return_code"] == "SUCCESS" && $stringData["result_code"] == "SUCCESS") {
    // 發紅包成功...
}
return;

輔助函式需要提前載入,載入方式
建立檔案 app/Common/BladeGeneral.php,新增下方2個函式
並在index.php 內引入

index.php

require __DIR__.'/../vendor/autoload.php';
// 在這新增即可,其他程式碼不動
require __DIR__ . '/../app/Common/BladeGeneral.php';  // 引入

輔助函式

/**
 * 格式化引數格式化成url引數
 */
function ToXml($data){
    if(is_array($data) && count($data) > 0) {
        $xml = "<xml>";
        foreach ($data as $key=>$val) {
            $xml.="<".$key.">".$val."</".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }
    return "";
}

function ToUrlParams($data){
    $buff = "";
    foreach ($data as $k => $v)
    {
        if($k != "sign" && $v != "" && !is_array($v)){
            $buff .= $k . "=" . $v . "&";
        }
    }
    $buff = trim($buff, "&");
    return $buff;
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

朝著夢,踏平坎坷

相關文章