From 2acbbcd9b7d9aa41f50ee74830e8d911a62ba380 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=A6=8C=EA=A6=AB=EA=A6=B6=EA=A6=8F=EA=A7=80=EA=A6=A6?= =?UTF-8?q?=EA=A6=BF=EA=A6=A7=EA=A6=AE=EA=A6=91=EA=A6=A9=EA=A6=AD=EA=A7=80?= Date: Wed, 5 Oct 2022 13:45:21 +0800 Subject: Request for Status API --- midtrans.c | 45 +++++++++++++++++++++++++++++++++++++-------- midtrans.h | 3 ++- 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/midtrans.c b/midtrans.c index 932820d..7fce842 100644 --- a/midtrans.c +++ b/midtrans.c @@ -8,26 +8,55 @@ #include #include "midtrans.h" +#define ORDER_ID "SANDBOX-G710367688-806" + +static _Bool sandbox; +static char *base_url; #ifndef __EMSCRIPTEN__ -static char *cainfo = NULL; +static CURL *curl; #endif -void midtrans_init(const char *certificate) +void midtrans_init(_Bool production, const char *api_key, const char *cainfo) { + sandbox = !production; + static const char *url_tmpl = "https://api.%smidtrans.com/v2/"; + static const char *infix = "sandbox."; + base_url = malloc(strlen(url_tmpl) - strlen ("%s") + + sandbox * strlen(infix) + 1); + sprintf(base_url, url_tmpl, production ? "" : infix); #ifndef __EMSCRIPTEN__ curl_global_init(CURL_GLOBAL_SSL); - if (certificate) { - cainfo = malloc(strlen(certificate) + 1); - strcpy(cainfo, certificate); - } + curl = curl_easy_init(); + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + struct curl_slist *list + = curl_slist_append(NULL, "Accept: application/json"); + list = curl_slist_append(list, "Content-Type: application/json"); + static const char *hdr_tmpl = "Authorization: %s"; + char auth[strlen(hdr_tmpl) - strlen("%s") + strlen(api_key) + 1]; + sprintf(auth, hdr_tmpl, api_key); + list = curl_slist_append(list, auth); + if (cainfo) + curl_easy_setopt(curl, CURLOPT_CAINFO, cainfo); +#endif +} + +void midtrans_status(const char *order_id) +{ + static const char *tmpl = "%s%s/status"; + char url[strlen(tmpl) - strlen("%s") * 2 + strlen(base_url) + + (sandbox ? strlen(ORDER_ID) : strlen(order_id)) + 1]; + sprintf(url, tmpl, base_url, sandbox ? ORDER_ID : order_id); +#ifndef __EMSCRIPTEN__ + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_perform(curl); #endif } void midtrans_cleanup() { + free(base_url); #ifndef __EMSCRIPTEN__ - if (cainfo) - free(cainfo); + curl_easy_cleanup(curl); curl_global_cleanup(); #endif } diff --git a/midtrans.h b/midtrans.h index 4c8fbde..bc73ec0 100644 --- a/midtrans.h +++ b/midtrans.h @@ -5,7 +5,8 @@ extern "C" { #endif -void midtrans_init(const char *certificate); +void midtrans_init(_Bool production, const char *api_key, const char *cainfo); +void midtrans_status(const char *order_id); void midtrans_cleanup(); #ifdef __cplusplus -- cgit v1.2.3