· 6 years ago · Oct 22, 2019, 04:24 AM
1<?php
2//HOST/midtrans/charge/index.php
3
4// Set your server key (Note: Server key for sandbox and production mode are different)
5$server_key = 'SB-Mid-server';
6// Set true for production, set false for sandbox
7$is_production = false;
8
9$api_url = $is_production ?
10 'https://app.midtrans.com/snap/v1/transactions' :
11 'https://app.sandbox.midtrans.com/snap/v1/transactions';
12
13
14// Check if request doesn't contains `/charge` in the url/path, display 404
15if( !strpos($_SERVER['REQUEST_URI'], '/charge') ) {
16 http_response_code(404);
17 echo "wrong path, make sure it's `/charge`"; exit();
18}
19// Check if method is not HTTP POST, display 404
20if( $_SERVER['REQUEST_METHOD'] !== 'POST'){
21 http_response_code(404);
22 echo "Page not found or wrong HTTP request method is used"; exit();
23}
24
25// get the HTTP POST body of the request
26$request_body = file_get_contents('php://input');
27// set response's content type as JSON
28header('Content-Type: application/json');
29// call charge API using request body passed by mobile SDK
30$charge_result = chargeAPI($api_url, $server_key, $request_body);
31// set the response http status code
32http_response_code($charge_result['http_code']);
33// then print out the response body
34echo $charge_result['body'];
35
36/**
37 * call charge API using Curl
38 * @param string $api_url
39 * @param string $server_key
40 * @param string $request_body
41 */
42function chargeAPI($api_url, $server_key, $request_body){
43 $ch = curl_init();
44 $curl_options = array(
45 CURLOPT_URL => $api_url,
46 CURLOPT_RETURNTRANSFER => 1,
47 CURLOPT_POST => 1,
48 CURLOPT_HEADER => 0,
49 // Add header to the request, including Authorization generated from server key
50 CURLOPT_HTTPHEADER => array(
51 'Content-Type: application/json',
52 'Accept: application/json',
53 'Authorization: Basic ' . base64_encode($server_key . ':')
54 ),
55 CURLOPT_POSTFIELDS => $request_body
56 );
57 curl_setopt_array($ch, $curl_options);
58 $result = array(
59 'body' => curl_exec($ch),
60 'http_code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
61 );
62 return $result;
63}