惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
T
Threatpost
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
Recorded Future
Recorded Future
小众软件
小众软件
N
Netflix TechBlog - Medium
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
LangChain Blog
博客园 - 聂微东
美团技术团队
F
Fortinet All Blogs
I
InfoQ
U
Unit 42
酷 壳 – CoolShell
酷 壳 – CoolShell
阮一峰的网络日志
阮一峰的网络日志
The Cloudflare Blog
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
J
Java Code Geeks
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
Vercel News
Vercel News
GbyAI
GbyAI
有赞技术团队
有赞技术团队
博客园 - 【当耐特】
H
Help Net Security
B
Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
aimingoo的专栏
aimingoo的专栏
C
Check Point Blog
Jina AI
Jina AI
The Register - Security
The Register - Security
Hugging Face - Blog
Hugging Face - Blog
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 叶小钗
Recent Announcements
Recent Announcements
D
DataBreaches.Net
IT之家
IT之家
雷峰网
雷峰网
Y
Y Combinator Blog
W
WeLiveSecurity
P
Proofpoint News Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
量子位
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 司徒正美
月光博客
月光博客
The Hacker News
The Hacker News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Why Your wp_remote_post Isn't Sending CF7 Data to Your API (And How to Fix It)
Rahul Sharma · 2026-05-20 · via DEV Community

Why Your wp_remote_post Isn't Sending CF7 Data to Your API (And How to Fix It)<br>
A developer posted this exact problem on the WordPress support forums: they followed a YouTube tutorial step-by-step, hooked into wpcf7_before_send_mail, built a wp_remote_post call and nothing arrived at the external API. No errors, no data, just silence.
This is more common than you'd think. Let's dissect exactly what went wrong in that code and how to fix it with a no-code alternative at the end if you'd rather skip the debugging rabbit hole.

The Original Code (And What's Broken In It)
Here's the code from the forum post, cleaned up for readability:

add_action( 'wpcf7_before_send_mail', 'blog_cf7_api_sender' );

function blog_cf7_api_sender( $contact_form ) {
    $form_id = ( $contact_form )->id();

    if ( $form_id == '02d6ca7' ) {
        $submission = WPCF7_Submission::get_instance();

        if ( $submission ) {
            $posted_data = $submission->get_current();

            $name        = $posted_data['client-name'];
            $phone       = $posted_data['client-phone'];
            $stream_code = [4yv1];   // ← syntax error
            $token       = [12345];  // ← this is an array, not a string

            $url = 'https://coolapi.com';

            $args = array(
                'body' => json_encode(array(
                    'name'        => $name,
                    'phone'       => $phone,
                    'stream_code' => $stream_code,
                    'token'       => $token,
                )                    // ← missing closing parenthesis for json_encode
                'headers' => array(
                    'Authorization' => 'Bearer $token',  // ← single quotes = literal string
                    'Content-Type'  => 'application/json',
                )
            );

            $response = wp_remote_post( $url, $args );
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

There are five bugs in this snippet. Let's go through each one.

Bug 1: [4yv1] Is Not Valid PHP

$stream_code = [4yv1];

Enter fullscreen mode Exit fullscreen mode

PHP's short array syntax [] expects valid expressions inside. 4yv1 is neither a string, integer, nor a variable it's a bare word starting with a digit, which is a parse error. This would cause a fatal PHP error before wp_remote_post ever gets called.

Fix:

$stream_code = '4yv1'; // string
// or if it's meant to be a variable: $stream_code = $some_variable;

Enter fullscreen mode Exit fullscreen mode

Bug 2: $token Is an Array, Not a String

$token = [12345];

Enter fullscreen mode Exit fullscreen mode

This creates a PHP array [12345], not the integer or string 12345. When you later try to interpolate it into a Bearer header, it won't behave as expected.

Fix:

$token = '12345'; // string token

Enter fullscreen mode Exit fullscreen mode

Bug 3: Missing Closing Parenthesis for json_encode()

$args = array(
    'body' => json_encode(array(
        'name'  => $name,
        'phone' => $phone,
    )              // ← closes the inner array(), but json_encode() is never closed
    'headers' => ...

Enter fullscreen mode Exit fullscreen mode

The json_encode() call is never closed with ) before the comma. This is another parse error.

Fix:

'body' => json_encode(array(
    'name'  => $name,
    'phone' => $phone,
)),  // ← closes json_encode() AND the 'body' key

Enter fullscreen mode Exit fullscreen mode

Bug 4: 'Bearer $token' in Single Quotes

'Authorization' => 'Bearer $token',

Enter fullscreen mode Exit fullscreen mode

In PHP, single-quoted strings do not interpolate variables. This sends the literal string Bearer $token to the API not the token value.

Fix:

'Authorization' => 'Bearer ' . $token,
// or with double quotes:
'Authorization' => "Bearer $token",

Enter fullscreen mode Exit fullscreen mode

Bug 5: The Hook Only Fires When Email Sending Is Active

This was the only hint from the WordPress forum moderator, but it's worth expanding on. wpcf7_before_send_mail is triggered as part of the mail-sending pipeline. If your CF7 form has email sending disabled (or the form tag doesn't have a mail configuration), this hook never fires silently.

You can verify this quickly:

add_action( 'wpcf7_before_send_mail', function( $contact_form ) {
    error_log( 'Hook fired for form: ' . $contact_form->id() );
});

Enter fullscreen mode Exit fullscreen mode

Check your server logs. If nothing appears, email sending isn't active for that form.

Alternative hook that always fires regardless of mail settings:

add_action( 'wpcf7_submit', 'blog_cf7_api_sender', 10, 2 );

Enter fullscreen mode Exit fullscreen mode

The Corrected Code
Here's the full corrected version:

add_action( 'wpcf7_before_send_mail', 'blog_cf7_api_sender' );

function blog_cf7_api_sender( $contact_form ) {
    $form_id = $contact_form->id();

    if ( $form_id == 123 ) { // use integer form ID, not a string with quotes
        $submission = WPCF7_Submission::get_instance();

        if ( $submission ) {
            $posted_data = $submission->get_posted_data(); // correct method name

            $name        = sanitize_text_field( $posted_data['client-name'] );
            $phone       = sanitize_text_field( $posted_data['client-phone'] );
            $stream_code = '4yv1';
            $token       = 'your-actual-token-here';

            $url = 'https://coolapi.com/endpoint';

            $args = array(
                'body'    => json_encode( array(
                    'name'        => $name,
                    'phone'       => $phone,
                    'stream_code' => $stream_code,
                    'token'       => $token,
                ) ),
                'headers' => array(
                    'Authorization' => 'Bearer ' . $token,
                    'Content-Type'  => 'application/json',
                ),
                'timeout' => 15,
            );

            $response = wp_remote_post( $url, $args );

            // Debug: log the response
            if ( is_wp_error( $response ) ) {
                error_log( 'CF7 API Error: ' . $response->get_error_message() );
            } else {
                error_log( 'CF7 API Response: ' . wp_remote_retrieve_body( $response ) );
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Two additional improvements in this version:

sanitize_text_field() on user inputs before sending them out
Error logging so you can actually see what's happening in wp-content/debug.log

A Note on get_current() vs get_posted_data()
The original code calls $submission->get_current(). This method doesn't exist in recent CF7 versions. The correct method is:

$posted_data = $submission->get_posted_data();

Enter fullscreen mode Exit fullscreen mode

If you're on an older CF7 version, get_posted_data() was introduced around CF7 5.x. Check your CF7 version before relying on either.

Skip the Code Entirely: Use Contact Form to API Plugin
If you're maintaining multiple forms, the custom PHP approach gets messy fast especially when tokens rotate, API endpoints change, or you need to add new forms. Every change requires a code deployment.
Contact Form to API is a WordPress plugin that handles all of this through a UI: you configure the endpoint URL, map CF7 fields to JSON keys, set auth headers (Bearer, Basic Auth, OAuth 2.0), and test the connection without writing a line of PHP.
It handles the wpcf7_before_send_mail hook internally, manages JSON encoding properly, and gives you response logs out of the box. Worth considering if you're building for clients or managing more than one integration.

Debugging Checklist
If your wp_remote_post is still silent after fixing the above:

Enable WP_DEBUG in wp-config.php: define('WP_DEBUG', true); define('WP_DEBUG_LOG', true);
Check the form ID — it should be an integer, not a string like '02d6ca7'
Verify the hook fires with a simple error_log() call
Test your API endpoint in Postman first with a hardcoded payload
Check for SSL issues — some servers can't verify external SSL certs; add 'sslverify' => false temporarily during testing (not in production)
Check wp_remote_retrieve_response_code() — a 200 with no effect usually means the payload structure is wrong, not the connection