21xrx.com
2024-05-20 05:46:40 Monday
登录
文章检索 我的文章 写文章
C++如何发送微信消息?
2023-07-14 01:24:33 深夜i     --     --
C++ 微信 发送 消息 API

要在C++中发送微信消息,需要使用微信开发者工具包提供的API。

首先,需要前往微信开放平台申请开发者账号。完成注册后,创建一个新的应用程序并获取应用程序的AppID和AppSecret。

接下来,需要通过API获取access token。该token是用于访问微信API的全局唯一票据,有效期为2小时。可以使用以下C++代码获取access token:


#include <iostream>

#include <cpprest/http_client.h>

#include <cpprest/json.h>

using namespace web;

using namespace web::http;

using namespace web::http::client;

std::string GetAccessToken()

{

  std::string url = "https://api.weixin.qq.com/cgi-bin/token";

  std::string appid = "your_appid";

  std::string secret = "your_appsecret";

  // 构造请求参数

  http_client client(url.c_str());

  uri_builder builder(U("/cgi-bin/token"));

  builder.append_query(U("appid"), appid.c_str());

  builder.append_query(U("secret"), secret.c_str());

  builder.append_query(U("grant_type"), U("client_credential"));

  http_request request(methods::GET);

  request.set_request_uri(builder.to_string());

  // 发送请求

  http_response response = client.request(request).get();

  // 解析返回值

  if(response.status_code() == status_codes::OK)

  {

    json::value obj = response.extract_json().get();

    std::string access_token = obj[U("access_token")].as_string();

    return access_token;

  }

  else

  

    return "";

  

}

获取成功后,可以使用以下代码发送微信消息:


#include <iostream>

#include <cpprest/http_client.h>

#include <cpprest/json.h>

using namespace web;

using namespace web::http;

using namespace web::http::client;

void SendWechatMessage(const std::string& access_token, const std::string& touser, const std::string& content)

{

  std::string url = "https://api.weixin.qq.com/cgi-bin/message/custom/send";

  // 构造请求参数

  http_client client(url.c_str());

  uri_builder builder(U("/cgi-bin/message/custom/send"));

  builder.append_query(U("access_token"), access_token.c_str());

  http_request request(methods::POST);

  request.set_request_uri(builder.to_string());

  // 构造消息体

  json::value message = json::value::object();

  message[U("touser")] = json::value::string(touser.c_str());

  message[U("msgtype")] = json::value::string("text");

  message[U("text")][U("content")] = json::value::string(content.c_str());

  request.set_body(message.serialize());

  // 发送请求

  http_response response = client.request(request).get();

  // 解析返回值

  if(response.status_code() == status_codes::OK)

  {

    std::cout << response.content_ready().get().extract_utf8string().get();

  }

  else

  {

    std::cerr << "Failed to send message. Reason: " << response.reason_phrase() << std::endl;

  }

}

以上就是在C++中使用微信API发送消息的步骤和示例代码。需要注意的是,在实际使用中需要替换相应的参数,如AppID、AppSecret、touser等。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复