微信小程序通过公众号(服务号)推送通知或提醒步骤及代码(二,推送通知或提醒)

推动公众号通知或提醒!
关于推送前所需要获取的数据请移步:https://blog.csdn.net/weixin_44467567/article/details/112304488
第一步: 登录公众号后台创建模板消息
在这里插入图片描述
创建完成后点击详情
在这里插入图片描述
第二步 :代码实现

接口传参格式

 {
       "touser":"OPENID",
       "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
       "url":"http://weixin.qq.com/download",  
       "miniprogram":{
         "appid":"xiaochengxuappid12345",
         "pagepath":"index?foo=bar"
       },          
       "data":{
               "first": {
                   "value":"恭喜你购买成功!",
                   "color":"#173177"
               },
               "keyword1":{
                   "value":"巧克力",
                   "color":"#173177"
               },
               "keyword2": {
                   "value":"39.8元",
                   "color":"#173177"
               },
               "keyword3": {
                   "value":"2014年9月22日",
                   "color":"#173177"
               },
               "remark":{
                   "value":"欢迎再次购买!",
                   "color":"#173177"
               }
       }
   }

在这里插入图片描述

代码如下:

传输实体类

import lombok.Data;

import java.io.Serializable;

/**
 * @Description: 消息模板Data类
 * @Param:
 * @return:
 * @Author: XQD
 * @Date:2021/1/5 11:02
 */
@Data
public class DataEntityDto implements Serializable {

    //内容
    private String value;
    //字体颜色
    private String color;

    public DataEntityDto(String value ,String color){
        this.value = value;
        this.color = color;
    }

}

在此之前已经通过用户关注公众号的时候获取到了用户的openId

/**
     * @Description: 发送模板消息
     * @Param: [openId]
     * @return: boolean
     * @Author: XQD
     * @Date:2021/1/5 10:02
     */
     // param参数格式  {"keyword1":"张三","keyword2","项目名称"}
    @Override
    public boolean sendTemplateMsg(String openId, JSONObject param) {
    		// 发送模板消息的URL
            String sendMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken();
            // 整体参数map
            Map<String, Object> paramMap = new HashMap<String, Object>();
            // 跳转小程序参数map   如不需跳转小程序,该map不用创建
            Map<String, Object> miniprogramMap = new HashMap<String, Object>();
            // 消息主题显示相关map
            Map<String, Object> dataMap = new HashMap<String, Object>();
            paramMap.put("touser", openId);
            // 收藏客户访问
            paramMap.put("template_id", "这里写公众后台申请的模板I的");
            miniprogramMap.put("appid", "需要跳转的小程序appId,必须为关联的小程序");
            miniprogramMap.put("pagepath","需要跳转的页面");
            paramMap.put("miniprogram",miniprogramMap);
            //根据自己的模板定义内容和颜色
            // 前面的first,keyword1,keyword2,keyword3,remark 要模板消息中的参数一致
            // 后面的(String) param.get("keyword1")中的keyword1是我自己传参时自定义写的,为了和前面保持一致
            dataMap.put("first",new DataEntityDto("收藏客户访问小程序通知!","#173177"));
            dataMap.put("keyword1",new DataEntityDto((String) param.get("keyword1"),"#173177"));
            dataMap.put("keyword2",new DataEntityDto((String) param.get("keyword2") ,"#173177"));
            dataMap.put("keyword3",new DataEntityDto("访问项目小程序首页内容" ,"#173177"));
            dataMap.put("remark",new DataEntityDto("及时与收藏客户保持良好联系","#173177"));
       		paramMap.put("data", dataMap);
            String post = HttpClientUtil.post(sendMsgUrl, JSON.toJSONString(paramMap));
            Map<String,Object> map = null;
            try {
                map = objectMapper.readValue(post, Map.class);
            } catch (IOException e) {
                log.error("公众号模板消息异常通知-转化异常",e);
            }
            String errcode = String.valueOf(map.get("errcode"));
            String errmsg = String.valueOf(map.get("errmsg"));
            if (!errcode.equals("0")){
                log.error("消息发送失败:code="+errcode+"msg="+errmsg);
                return false;
            }
        return true;
    }
### 实现C#应用向微信公众号发送推送通知 为了通过C#应用程序实现向微信公众号发送推送通知,需遵循特定流程来配置并调用相应的API接口。首先,要获得用于访问微信公众平台API的`access_token`,这是所有API请求的关键凭证。 #### 获取Access Token 全局唯一的`access_token`可以通过HTTP GET方法从官方服务器获取。具体来说,应构建如下URL并向其发起GET请求: ```plaintext https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET[^1] ``` 其中`APPID`和`APPSECRET`代表开发者账号下的小程序服务号的身份标识符及其密钥。成功响应会返回JSON格式的数据包,内含所需的`access_token`字符串及过期时间戳。 #### 发送模板消息 一旦拥有了有效的`access_token`,就可以准备发送模板消息了。这一步骤涉及设置好接收者openid、模板ID以及其他必要的字段信息。以下是利用HttpClient库编的简单示例代码片段展示如何执行此操作: ```csharp using System; using System.Net.Http; using Newtonsoft.Json.Linq; public class WeChatPushNotificationService { private static readonly string AccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token"; private static readonly string SendMessageUrlFormat = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}"; public async Task SendTemplateMessageAsync(string appId, string appSecret, JObject messageData) { using (var client = new HttpClient()) { // Step 1: Get access token. var accessTokenResponse = await client.GetStringAsync($"{AccessTokenUrl}?grant_type=client_credential&appid={appId}&secret={appSecret}"); dynamic jsonResult = JObject.Parse(accessTokenResponse); string accessToken = jsonResult.access_token; // Step 2: Post template message with the obtained access token. var sendMessageUrl = String.Format(SendMessageUrlFormat, accessToken); HttpResponseMessage response = await client.PostAsync(sendMessageUrl, new StringContent(messageData.ToString(), Encoding.UTF8, "application/json")); if (!response.IsSuccessStatusCode) { throw new Exception($"Failed to send wechat push notification. Status code {response.StatusCode}, Reason phrase '{response.ReasonPhrase}'."); } } } } ``` 上述代码展示了怎样创建一个异步函数`SendTemplateMessageAsync()`,它接受三个参数:`appId`, `appSecret` 和待发送的消息体(作为JObject对象传递),并通过两次网络请求完成整个过程——先是取得临时令牌,接着使用该令牌提交实际的通知内容给定的目标用户。
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值