转自:https://www.jianshu.com/p/e079ef8043fc?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation
看文档,能知道!
第一步是要拿到Access Token
第二步才是发送推送
- 第一步新建公用方法Curl
function request($url, $postData = [], $header = [], $formUrlencoded = false) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if ($header) { curl_setopt($ch, CURLOPT_HTTPHEADER, $header); } if ($postData) { curl_setopt($ch, CURLOPT_POST, true); //如果不用http_build_query你就会踩到坑的,你可以试试 if($formUrlencoded){ curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); }else{ curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); } } $response = curl_exec($ch); if ($errno = curl_errno($ch)) { $error = curl_error($ch); $this->errmsg = $error; $this->errno = $errno; curl_close($ch); return false; } curl_close($ch); return $response ; }
- 第二步得到access token 以及发送推送
//reids 缓存不用特别说明了吧初始化 $redis = new redis(); $huaweiToken = $redis->get('HUAWEI:TOKEN'); if(!$huaweiToken){ $res = $this->request( 'https://login.vmall.com/oauth2/token', [ 'grant_type' => 'client_credentials', 'client_secret' => '华为推送AppSecret', 'client_id' => '华为推送AppID' ], ['Content-Type: application/x-www-form-urlencoded; charset=utf-8'], true ); $resArray = json_decode($res, true); if(isset($resArray['access_token']) && isset($resArray['expires_in'])){ $redis->setEx('HUAWEI:TOKEN',$resArray['expires_in'],$resArray['access_token']); $huaweiToken = $resArray['access_token']; } } //字段来自http://blog.csdn.net/angjbyszsh/article/details/78231709 参考 $body = array();//仅通知栏消息需要设置标题和内容,透传消息key和value为用户自定义 $body['title'] = 'Push message title';//消息标题 $body['content'] = 'Push message content';//消息标题 $param = array(); $param['appPkgName'] = '你的包名';//定义需要打开的appPkgName $action = array(); $action['param'] = $param;//消息点击动作参数 $action['type'] = 3;//类型3为打开APP,其他行为请参考接口文档设置 $msg = array(); $msg['action'] = $action;//消息点击动作 $msg['type'] = 3;//3: 通知栏消息,异步透传消息请根据接口文档设置 $msg['body'] = $body;//通知栏消息body内容 $ext = array();//扩展信息,含BI消息统计,特定展示风格,消息折叠。 $ext['biTag'] = 'Trump';//设置消息标签,如果带了这个标签,会在回执中推送给CP用于检测某种类型消息的到达率和状态 $ext['icon'] = "";//自定义推送消息在通知栏的图标,value为一个公网可以访问的URL $hps = array();//华为PUSH消息总结构体 $hps['msg'] = $msg; $hps['ext'] = $ext; $payload = array(); $payload['hps'] = $hps; $res = $this->request( 'https://api.push.hicloud.com/pushsend.do?nsp_ctx=' . urlencode('{"ver":"1", "appId":"华为推送AppID"}'), [ 'access_token' => $huaweiToken, 'nsp_svc' => 'openpush.message.api.send', 'nsp_ts' => (int)time(), 'device_token_list' => json_encode(['12345678901234561234567890123456','22345678901234561234567890123456']), 'payload' => json_encode($payload), ], ['Content-Type: application/x-www-form-urlencoded; charset=utf-8'], true ); var_dump($res);//查看结果