mail-chimp-rest.php
70 lines
| 1 | <?php |
| 2 | if(!function_exists('ekit_mail_chimp_rest')){ |
| 3 | |
| 4 | function ekit_mail_chimp_rest(WP_REST_Request $request ){ |
| 5 | $return = ['success' => [], 'error' => [] ]; |
| 6 | |
| 7 | $token = $request['token']; |
| 8 | $list = $request['list']; |
| 9 | $email = $request['email']; |
| 10 | $firstname = $request['firstname']; |
| 11 | $lastname = $request['lastname']; |
| 12 | $phone = $request['phone']; |
| 13 | |
| 14 | $url = 'https://us20.api.mailchimp.com/3.0/lists/'.$list.'/members/'; |
| 15 | |
| 16 | $margeFiled = []; |
| 17 | if(strlen($firstname) > 1): |
| 18 | $margeFiled['FNAME'] = $firstname; |
| 19 | endif; |
| 20 | if(strlen($lastname) > 1): |
| 21 | $margeFiled['LNAME'] = $lastname; |
| 22 | endif; |
| 23 | if(strlen($phone) > 1): |
| 24 | $margeFiled['PHONE'] = $phone; |
| 25 | endif; |
| 26 | |
| 27 | $postData = []; |
| 28 | $postData['email_address'] = $email; |
| 29 | $postData['status'] = 'subscribed'; |
| 30 | if(sizeof($margeFiled) > 0): |
| 31 | $postData['merge_fields'] = $margeFiled; |
| 32 | endif; |
| 33 | $postData['status_if_new'] = 'subscribed'; |
| 34 | |
| 35 | $response = wp_remote_post( $url, [ |
| 36 | 'method' => 'POST', |
| 37 | 'data_format' => 'body', |
| 38 | 'timeout' => 45, |
| 39 | 'headers' => [ |
| 40 | |
| 41 | 'Authorization' => 'apikey '.$token, |
| 42 | 'Content-Type' => 'application/json; charset=utf-8' |
| 43 | ], |
| 44 | 'body' => wp_json_encode($postData ) |
| 45 | ] |
| 46 | ); |
| 47 | |
| 48 | if ( is_wp_error( $response ) ) { |
| 49 | $error_message = $response->get_error_message(); |
| 50 | $return['error'] = "Something went wrong: $error_message"; |
| 51 | } else { |
| 52 | $return['success'] = $response; |
| 53 | } |
| 54 | |
| 55 | return $return; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * wp rest api add action |
| 61 | */ |
| 62 | add_action( 'rest_api_init', function () { |
| 63 | register_rest_route( 'elementskit-lite', '/mailchimp/', |
| 64 | array( |
| 65 | 'methods' => 'GET', |
| 66 | 'callback' => 'ekit_mail_chimp_rest', |
| 67 | 'permission_callback' => '__return_true', |
| 68 | ) |
| 69 | ); |
| 70 | }); |