uin-app 小程序订阅消息和发送消息 ,后台语言为php

235 阅读1分钟

1. 订阅消息需要小程序填好类目

2. 创建模板,使用公共模块创建就会快很多,自定义需要审核

代码上场

uin-appp 代码

// 订阅接口 在 小程序里面操作
uni.requestSubscribeMessage({
    tmplIds: [this.tmplIds],
    success: (res) => {
        // 订阅成功
                    console.log(res)
    },
    fail: function(err) {
        uni.showToast({
            title: err,
            duration: 2000,
            icon: 'error'
        });
    }
})

php 代码


/**
 * @ApiTitle    (推送消息)
 * @ApiMethod   (GET)
 * @ApiParams   (name="mobile", type="string", required=true, description="发给谁 填写手机号")
 * @ApiParams   (name="tempids", type="string", required=true, description="模版id: juyLrxRW6r_mNYKGaiaCHt3vBkryd3g4UDthxNBKcis")
 * @ApiRoute    (/api/weixin/pushMsg)
 * @ApiReturn   ({
"code": 1,
"msg": "推送成功",
"time": "1592472641",
"data": "13456789467"
})
 */

public function pushMsg() {
    $data = [];

    $mobile = $this->request->param('mobile');
    $tempid = $this->request->param('tempids');
    $userinfo = \app\admin\model\User::where([ 'mobile'=> $mobile ])->find();
    if ($userinfo) {

        if($userinfo['openid']) {
            $data['touser'] = $userinfo['openid'];
        }else {
            $this->error('推送失败');
        }

    }else {
        $this->error('推送失败');
    }
    $access_token = $this->getToken();
    //请求url
    $urls = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token;
    //发送内容
    //接收者(用户)的 openid
    //所需下发的订阅模板id
    $data['template_id'] = $tempid;
    // page 进入那个页面
    $data['page'] = 'index';
    //模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }
    $data['data'] = [
        "name1" => [
            'value' => '微信用户'
        ],
        "date2" => [
            'value' => date("Y-m-d")
        ],
        "thing3" => [
            'value' => '禁酒'
        ]
    ];
    //跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版
    //$data['miniprogram_state'] = 'trial';
    $result = Http::post($urls, json_encode($data));
    $wxResult = json_decode($result, true);
    if(isset($wxResult['errcode']) && $wxResult['errmsg']== 'ok') {
        $this->success('推送成功');
    }else {
        $this->error('推送失败');
    }



}