抖音小程序生成內部訂單微擎代碼示例

                        抖音小程序生成內部訂單微擎代碼示例

最近公司要把微信小程序轉抖音小程序。抖音小程序支持支付寶支付。已測試,可以使用,有問題大家可以交流

代碼:

//請求參數
$requestConfigs = array(
    'out_order_no' => $outTradeNo,
    'uid' => $openid,
    'merchant_id' => $this->merchant_id,//
    'total_amount' => $totalFee*100, //單位 元
    'currency' => 'CNY',
    'subject' => $orderName, //訂單標題
    'body' => $bodyName,//訂單內容
    'trade_time' => time(),
    'valid_time' => '60',
    'notify_url' => $this->root . 'payment/alipay/notify.php',//異步回調地址
    'risk_info' => json_encode(['ip' => $this->getRealIp()]),
);
$dataList = array(
    //公共參數
    'app_id' => $this->appId,
    'method' => 'tp.trade.create',
    'format' => 'json',
    'charset' => 'utf-8',
    'sign_type' => 'MD5',
    'timestamp' => time(),
    'version' => '1.0',
    'biz_content' => json_encode($requestConfigs)
);
$url = 'https://tp-pay.snssdk.com/gateway';
$dataList["sign"]=md5($this->getSignContent($dataList , $dataList['charset'] ,$this->Key));    //這裏寫了一個簽名的方法
$resp= $this->ihttp_post($url, $dataList);
if (is_error($resp)) {
    return $resp['message'];
}
if (empty($resp['content']))
{
    return $resp['網絡錯誤'];
}
$res=json_decode($resp['content'],true);
if(!empty($res['response']['code'])&&$res['response']['code']!=10000){
    return error(-2,$res['response']['sub_msg']);
}else{
    $out_order_no=$res['response']['trade_no'];
    // $params['sign']=$res['sign'];
}

//獲取IP方法
public function getRealIp() {
    $ip = false;
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
        if ($ip) {
            array_unshift($ips, $ip);
            $ip = FALSE;}
        for ($i = 0; $i < count($ips); $i++) {
            if (!eregi("^(10│172.16│192.168).", $ips[$i])) {
                $ip = $ips[$i];
                break;
            }
        }
    }
    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}
/**
 * 簽名處理
 * @param $params
 * @param $charset
 * @return string
 */
public function getSignContent($params , $charset,$app_secret) {
    ksort($params);
    $stringToBeSigned = "";
    $i = 0;
    foreach ($params as $k => $v) {
        if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
            // 轉換成目標字符集
            $v = $this->characet($v, $charset);
            if ($i == 0) {
                $stringToBeSigned .= "$k" . "=" . "$v";
            } else {
                $stringToBeSigned .= "&" . "$k" . "=" . "$v";
            }
            $i++;
        }
    }
    $stringToBeSigned = $stringToBeSigned.$app_secret;
    unset ($k, $v);
    return $stringToBeSigned;
}

/**
 * 校驗$value是否非空
 * @param $value
 * @return  boolean;
 *  if not set ,return true;
 *  if is null , return true;
 **/
public function checkEmpty($value) {
    if (!isset($value))
        return true;
    if ($value === null)
        return true;
    if (trim($value) === "")
        return true;
    return false;
}

/**
 * 轉換字符集編碼
 * @param $data
 * @param $targetCharset
 * @return string
 */
public function characet($data, $targetCharset) {
    if (!empty($data)) {
        $fileType = "UTF-8";
        if (strcasecmp($fileType, $targetCharset) != 0) {
            $data = mb_convert_encoding($data, $targetCharset, $fileType);
        }
    }
    return $data;
}

public function ihttp_post($url, $data) {
    $headers = array('Content-Type' => 'application/x-www-form-urlencoded');
    return $this->ihttp_request($url, $data, $headers);
}

public function ihttp_request($url, $post = '', $extra = array(), $timeout = 60) {
    if (function_exists('curl_init') && function_exists('curl_exec') && $timeout > 0) {
        $ch = $this->ihttp_build_curl($url, $post, $extra, $timeout);
        if (is_error($ch)) {
            return $ch;
        }
        $data = curl_exec($ch);
        $status = curl_getinfo($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if ($errno || empty($data)) {
            return error($errno, $error);
        } else {
            return $this->ihttp_response_parse($data);
        }
    }
    $urlset = $this->ihttp_parse_url($url, true);
    if (!empty($urlset['ip'])) {
        $urlset['host'] = $urlset['ip'];
    }

    $body = $this->ihttp_build_httpbody($url, $post, $extra);

    if ($urlset['scheme'] == 'https') {
        $fp = $this->ihttp_socketopen('ssl://' . $urlset['host'], $urlset['port'], $errno, $error);
    } else {
        $fp = $this->ihttp_socketopen($urlset['host'], $urlset['port'], $errno, $error);
    }
    stream_set_blocking($fp, $timeout > 0 ? true : false);
    stream_set_timeout($fp, ini_get('default_socket_timeout'));
    if (!$fp) {
        return error(1, $error);
    } else {
        fwrite($fp, $body);
        $content = '';
        if($timeout > 0) {
            while (!feof($fp)) {
                $content .= fgets($fp, 512);
            }
        }
        fclose($fp);
        return ihttp_response_parse($content, true);
    }
}

public function ihttp_build_curl($url, $post, $extra, $timeout) {
    if (!function_exists('curl_init') || !function_exists('curl_exec')) {
        return error(1, 'curl擴展未開啓');
    }
    $urlset = $this->ihttp_parse_url($url);
    if (is_error($urlset)) {
        return $urlset;
    }
    if (!empty($urlset['ip'])) {
        $extra['ip'] = $urlset['ip'];
    }
    $ch = curl_init();
    if (!empty($extra['ip'])) {
        $extra['Host'] = $urlset['host'];
        $urlset['host'] = $extra['ip'];
        unset($extra['ip']);
    }
    curl_setopt($ch, CURLOPT_URL, $urlset['scheme'] . '://' . $urlset['host'] . ($urlset['port'] == '80' || empty($urlset['port']) ? '' : ':' . $urlset['port']) . $urlset['path'] . $urlset['query']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    @curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    if ($post) {
        if (is_array($post)) {
            $filepost = false;
            foreach ($post as $name => &$value) {
                if (version_compare(phpversion(), '5.5') >= 0 && is_string($value) && substr($value, 0, 1) == '@') {
                    $post[$name] = new CURLFile(ltrim($value, '@'));
                }
                if ((is_string($value) && substr($value, 0, 1) == '@') || (class_exists('CURLFile') && $value instanceof CURLFile)) {
                    $filepost = true;
                }
            }
            if (!$filepost) {
                $post = http_build_query($post);
            }
        }
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }

    if (!empty($GLOBALS['_W']['config']['setting']['proxy'])) {
        $urls = parse_url($GLOBALS['_W']['config']['setting']['proxy']['host']);
        if (!empty($urls['host'])) {
            curl_setopt($ch, CURLOPT_PROXY, "{$urls['host']}:{$urls['port']}");
            $proxytype = 'CURLPROXY_' . strtoupper($urls['scheme']);
            if (!empty($urls['scheme']) && defined($proxytype)) {
                curl_setopt($ch, CURLOPT_PROXYTYPE, constant($proxytype));
            } else {
                curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
                curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
            }
            if (!empty($GLOBALS['_W']['config']['setting']['proxy']['auth'])) {
                curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['_W']['config']['setting']['proxy']['auth']);
            }
        }
    }
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSLVERSION, 1);
    if (defined('CURL_SSLVERSION_TLSv1')) {
        curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
    }
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');
    if (!empty($extra) && is_array($extra)) {
        $headers = array();
        foreach ($extra as $opt => $value) {
            if (strexists($opt, 'CURLOPT_')) {
                curl_setopt($ch, constant($opt), $value);
            } elseif (is_numeric($opt)) {
                curl_setopt($ch, $opt, $value);
            } else {
                $headers[] = "{$opt}: {$value}";
            }
        }
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
    }
    return $ch;
}

public function ihttp_socketopen($hostname, $port = 80, &$errno, &$errstr, $timeout = 15) {
    $fp = '';
    if(function_exists('fsockopen')) {
        $fp = @fsockopen($hostname, $port, $errno, $errstr, $timeout);
    } elseif(function_exists('pfsockopen')) {
        $fp = @pfsockopen($hostname, $port, $errno, $errstr, $timeout);
    } elseif(function_exists('stream_socket_client')) {
        $fp = @stream_socket_client($hostname.':'.$port, $errno, $errstr, $timeout);
    }
    return $fp;
}

public function ihttp_response_parse($data, $chunked = false) {
    $rlt = array();
    $headermeta = explode('HTTP/', $data);
    if (count($headermeta) > 2) {
        $data = 'HTTP/' . array_pop($headermeta);
    }
    $pos = strpos($data, "\r\n\r\n");
    $split1[0] = substr($data, 0, $pos);
    $split1[1] = substr($data, $pos + 4, strlen($data));

    $split2 = explode("\r\n", $split1[0], 2);
    preg_match('/^(\S+) (\S+) (.*)$/', $split2[0], $matches);
    $rlt['code'] = $matches[2];
    $rlt['status'] = $matches[3];
    $rlt['responseline'] = $split2[0];
    $header = explode("\r\n", $split2[1]);
    $isgzip = false;
    $ischunk = false;
    foreach ($header as $v) {
        $pos = strpos($v, ':');
        $key = substr($v, 0, $pos);
        $value = trim(substr($v, $pos + 1));
        if (is_array($rlt['headers'][$key])) {
            $rlt['headers'][$key][] = $value;
        } elseif (!empty($rlt['headers'][$key])) {
            $temp = $rlt['headers'][$key];
            unset($rlt['headers'][$key]);
            $rlt['headers'][$key][] = $temp;
            $rlt['headers'][$key][] = $value;
        } else {
            $rlt['headers'][$key] = $value;
        }
        if(!$isgzip && strtolower($key) == 'content-encoding' && strtolower($value) == 'gzip') {
            $isgzip = true;
        }
        if(!$ischunk && strtolower($key) == 'transfer-encoding' && strtolower($value) == 'chunked') {
            $ischunk = true;
        }
    }
    if($chunked && $ischunk) {
        $rlt['content'] = $this->ihttp_response_parse_unchunk($split1[1]);
    } else {
        $rlt['content'] = $split1[1];
    }
    if($isgzip && function_exists('gzdecode')) {
        $rlt['content'] = gzdecode($rlt['content']);
    }

    $rlt['meta'] = $data;
    if($rlt['code'] == '100') {
        return ihttp_response_parse($rlt['content']);
    }
    return $rlt;
}

public function ihttp_response_parse_unchunk($str = null) {
    if(!is_string($str) or strlen($str) < 1) {
        return false;
    }
    $eol = "\r\n";
    $add = strlen($eol);
    $tmp = $str;
    $str = '';
    do {
        $tmp = ltrim($tmp);
        $pos = strpos($tmp, $eol);
        if($pos === false) {
            return false;
        }
        $len = hexdec(substr($tmp, 0, $pos));
        if(!is_numeric($len) or $len < 0) {
            return false;
        }
        $str .= substr($tmp, ($pos + $add), $len);
        $tmp  = substr($tmp, ($len + $pos + $add));
        $check = trim($tmp);
    } while(!empty($check));
    unset($tmp);
    return $str;
}

public function ihttp_parse_url($url, $set_default_port = false) {
    if (empty($url)) {
        return error(1);
    }
    $urlset = parse_url($url);
    if (!empty($urlset['scheme']) && !in_array($urlset['scheme'], array('http', 'https'))) {
        return error(1, '只能使用 http 及 https 協議');
    }

    if (empty($urlset['path'])) {
        $urlset['path'] = '/';
    }
    if (!empty($urlset['query'])) {
        $urlset['query'] = "?{$urlset['query']}";
    }
    if (strexists($url, 'https://') && !extension_loaded('openssl')) {
        if (!extension_loaded("openssl")) {
            return error(1,'請開啓您PHP環境的openssl', '');
        }
    }

    if (empty($urlset['host'])) {
        $current_url = parse_url($GLOBALS['_W']['siteroot']);
        $urlset['host'] = $current_url['host'];
        $urlset['scheme'] = $current_url['scheme'];
        $urlset['path'] = $current_url['path'] . 'web/' . str_replace('./', '', $urlset['path']);
        $urlset['ip'] = '127.0.0.1';
    } else if (! $this->ihttp_allow_host($urlset['host'])){
        return error(1, 'host 非法');
    }
    if ($set_default_port && empty($urlset['port'])) {
        $urlset['port'] = $urlset['scheme'] == 'https' ? '443' : '80';
    }
    return $urlset;
}

public function ihttp_allow_host($host) {
    global $_W;
    if (strexists($host, '@')) {
        return false;
    }
    $pattern = "/^(10|172|192|127)/";
    if (preg_match($pattern, $host) && isset($_W['setting']['ip_white_list'])) {
        $ip_white_list = $_W['setting']['ip_white_list'];
        if ($ip_white_list && isset($ip_white_list[$host]) && !$ip_white_list[$host]['status']) {
            return false;
        }
    }
    return true;
}

public function ihttp_build_httpbody($url, $post, $extra) {
    $urlset = $this->ihttp_parse_url($url, true);
    if (is_error($urlset)) {
        return $urlset;
    }

    if (!empty($urlset['ip'])) {
        $extra['ip'] = $urlset['ip'];
    }

    $body = '';
    if (!empty($post) && is_array($post)) {
        $filepost = false;
        $boundary = random(40);
        foreach ($post as $name => &$value) {
            if ((is_string($value) && substr($value, 0, 1) == '@') && file_exists(ltrim($value, '@'))) {
                $filepost = true;
                $file = ltrim($value, '@');

                $body .= "--$boundary\r\n";
                $body .= 'Content-Disposition: form-data; name="'.$name.'"; filename="'.basename($file).'"; Content-Type: application/octet-stream'."\r\n\r\n";
                $body .= file_get_contents($file)."\r\n";
            } else {
                $body .= "--$boundary\r\n";
                $body .= 'Content-Disposition: form-data; name="'.$name.'"'."\r\n\r\n";
                $body .= $value."\r\n";
            }
        }
        if (!$filepost) {
            $body = http_build_query($post, '', '&');
        } else {
            $body .= "--$boundary\r\n";
        }
    }

    $method = empty($post) ? 'GET' : 'POST';
    $fdata = "{$method} {$urlset['path']}{$urlset['query']} HTTP/1.1\r\n";
    $fdata .= "Accept: */*\r\n";
    $fdata .= "Accept-Language: zh-cn\r\n";
    if ($method == 'POST') {
        $fdata .= empty($filepost) ? "Content-Type: application/x-www-form-urlencoded\r\n" : "Content-Type: multipart/form-data; boundary=$boundary\r\n";
    }
    $fdata .= "Host: {$urlset['host']}\r\n";
    $fdata .= "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1\r\n";
    if (function_exists('gzdecode')) {
        $fdata .= "Accept-Encoding: gzip, deflate\r\n";
    }
    $fdata .= "Connection: close\r\n";
    if (!empty($extra) && is_array($extra)) {
        foreach ($extra as $opt => $value) {
            if (!strexists($opt, 'CURLOPT_')) {
                $fdata .= "{$opt}: {$value}\r\n";
            }
        }
    }
    if ($body) {
        $fdata .= 'Content-Length: ' . strlen($body) . "\r\n\r\n{$body}";
    } else {
        $fdata .= "\r\n";
    }
    return $fdata;
}

歡迎大家交流,可以把查詢方式改成TP5,一樣的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章