200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > 微信小程序发送微信公众号模板消息

微信小程序发送微信公众号模板消息

时间:2019-09-22 19:44:51

相关推荐

微信小程序发送微信公众号模板消息

具体思路:

一、打通微信小程序和微信公众号

1、利用不同平台下,相同的unionid来判断是发送到那个用户

2、获取微信小程序openid和unionid >>官方文档

3、获取微信公众号openid和unionid (触发条件是,用户的关注公众号和不在关注)。详情见下面代码

需开启服务器配置的前提下

二、开通开发者账户官方链接,需要另外再付300元

1、保证公众号是服务号

2、保证公众号、小程序绑定在同一开发者账户下

3、保证公众号、小程序相互关联

4、公众号后台开通服务器配置(开通后公众号底部板块需要自定义)公众号自定义导航文档

5、开发者平台是不同于公众号和小程序独立的平台

文件一:url.php

<?php$loadingTimeStart = microtime(true);?><?php/*** wechat php test*/define("TOKEN", "cuangxian");//把这里的weixin 改成你的TOKEN$access_token_mp = $access_token_mp ? $access_token_mp : access_token_mp(); //这里是利用微信appid和secret换取access_token$wechatObj = new wechatCallbackapiTest();$wechatObj->valid();$wechatObj->responseMsg();class wechatCallbackapiTest{public function valid(){$echoStr = $_GET["echostr"];if($this->checkSignature()){echo $echoStr;//服务器配置验证成功//exit;}else{//服务器配置验证失败}}public function responseMsg(){global $conn;$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];if($_GET["debug"]=="true"){$postStr = "<xml><ToUserName><![CDATA[gh_aef7f2518443]]></ToUserName><FromUserName><![CDATA[oLT1Z6GFAZYXWO-s0bhqfyMk46n0]]></FromUserName><CreateTime>1555988221</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[user_get_card]]></Event><CardId><![CDATA[pLT1Z6KjXab7hYXSco39gKD8LeCc]]></CardId><IsGiveByFriend>0</IsGiveByFriend><UserCardCode><![CDATA[146787302551]]></UserCardCode><FriendUserName><![CDATA[]]></FriendUserName><OuterId>0</OuterId><OldUserCardCode><![CDATA[]]></OldUserCardCode><IsRestoreMemberCard>0</IsRestoreMemberCard><IsRecommendByFriend>0</IsRecommendByFriend><SourceScene><![CDATA[SOURCE_SCENE_UNKNOW]]></SourceScene><UnionId><![CDATA[oddqd1ViNaH0RgXH-6BcuNbd6hyU]]></UnionId></xml>";}if (!empty($postStr)){//引用global $access_token_mp;//主体/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,the best way is to check the validity of xml by yourself */libxml_disable_entity_loader(true);$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);/*转换xml*//*前后加双引号,转成字符串*/$ToUserName = trim($postObj->ToUserName); //起始ID$FromUserName = trim($postObj->FromUserName); //触发事件的用户 openid$CreateTime = $postObj->CreateTime; //时间截$MsgType = trim($postObj->MsgType); //Msg类型 event[事件]、text[文本]$Event = trim($postObj->Event); //事件名$EventKey = trim($postObj->EventKey); //事件里包含的内容//$EventKey = str_replace("qrscene_","", $EventKey); //清楚字符//$content = trim($postObj->Content); //微信里面发送的内容$UnionId = trim($postObj->UnionId);//领券用户的UnionId$CardId = trim($postObj->CardId);//卡券ID。$UserCardCode = trim($postObj->UserCardCode);//code序列号。if($MsgType == "event"){if($Event == "subscribe"){//订阅$contentStr = "欢迎关注我们啊啊啊!";kefu_send($FromUserName, "text", $contentStr);/** 【客服接口-发消息】* https://mp./wiki?t=resource/res_main&id=mp1421140547* msgtype文本text 图片image 图文mpnews*/function kefu_send($openid, $msgtype ,$content) {//引用global $access_token_mp;//主体$data = array();$data["touser"] = $openid;$data["msgtype"] = $msgtype;if($msgtype=="text"){$data["text"] = array();$data["text"]["content"] = $content;}elseif($msgtype=="image"){$data["image"] = array();$data["image"]["media_id"] = $content;}elseif($msgtype=="mpnews"){$data["mpnews"] = array();$data["mpnews"]["media_id"] = $content;}elseif($msgtype=="wxcard"){$data["wxcard"] = array();$data["wxcard"]["card_id"] = $content;}$url="https://api./cgi-bin/message/custom/send?access_token=".$access_token_mp.""; $dataRes = curl_post($url, json_encode($data,JSON_UNESCAPED_UNICODE));//传输的内容里面有汉字 需要添加(JSON_UNESCAPED_UNICODE)$res = json_decode($dataRes,true);//**********************************************************************************return $res;}//获取用户信息$userInfo_url = "https://api./cgi-bin/user/info?access_token=".$access_token_mp."&openid=".$FromUserName."&lang=zh_CN";$json_info = curl_get($userInfo_url);$info = json_decode($json_info, true);$openid = $info["openid"];$unionid = $info["unionid"];//获取微信公众号unionidif($unionid){$rmu = _get_one('a_member_unionid',$unionid,'unionid');//利用unionid查看当前用户是否存在//数据整合$dataArr=array();$dataArr["openid_mp"]=$openid;//获取微信公众号openid$dataArr["is_subscribe"]=1;//表示用户已关注公众号if ($rmu){//存在_update('a_member_unionid',$dataArr,$rmu["id"]);//修改为用户已关注公众号}else{$dataArr["unionid"]=$unionid;$dataArr["addTime"]=time();$dataArr["addip"]=formip();_insert('a_member_unionid',$dataArr);//新增一条记录为用户已关注公众号}////更新会员信息//$rm = _get_one('a_member',$unionid,'WXunionid');//if($rm){//_query("update a_member set WXopenid_mp='{$FromUserName}' where id='{$rm["id"]}'");//}}}elseif($Event == "unsubscribe"){//退订//修改为用户已取消关注公众号_query("update a_member_unionid set is_subscribe='0' where openid_mp='{$FromUserName}'");}elseif($Event == "CLICK"){//点击}}elseif($MsgType == "text"){$contentStr = "联系方式:".mainConfig("web_1"); kefu_send($FromUserName, "text", $contentStr);//$content = trim($postObj->Content);//jiLuRiZhi("0006【咨询的内容】\r\n".$content."",$FromUserName);//回复//$contentStr = "联系方式:0551-63520015\r\n服务时间:8:30-18:00";//$this->return_text($postObj,$contentStr);}//记录结束时间global $loadingTimeStart;$loadingTimeEnd = microtime(true);$loadingTimeTotal = $loadingTimeEnd - $loadingTimeStart;}else {echo '';exit;}}//回复文本信息private function return_text($postObj,$contentStr){$textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>";$time = time();$resultStr = sprintf($textTpl, $postObj->FromUserName, $postObj->ToUserName, $time, $contentStr);echo $resultStr;//exit;}//验证身份private function checkSignature(){// you must define TOKEN by yourselfif (!defined("TOKEN")) {throw new Exception('TOKEN is not defined!');}$signature = $_GET["signature"];$timestamp = $_GET["timestamp"];$nonce = $_GET["nonce"];$token = TOKEN;$tmpArr = array($token, $timestamp, $nonce);// use SORT_STRING rulesort($tmpArr, SORT_STRING);$tmpStr = implode( $tmpArr );$tmpStr = sha1( $tmpStr );if( $tmpStr == $signature ){return true;}else{return false;}}}?>

三、发送公众号模板通知

发送的前提是:微信小程序和微信公众号的openid以及unionid不为空

<?php//发送模板信息_mpfunction send_template_mp($template){$url= "https://api./cgi-bin/message/template/send?access_token=" . access_token_mp() . "";$res = curl_post($url,urldecode($template));//登记日志$logStr = "【发送模板消息-提交数据】:\r\n".json_encode($res, true);log_result($logStr,"log_wxmp",date("Ymd")."_template.txt");return $res;}//整合模板数据_mp//$wxapp_template_mp["open"] true//$wxapp_template_mp["open"] 消息模板ID//$rum["WXopenid_mp"] 微信公众号openidif(formip()!="127.0.0.1" && $wxapp_template_mp["open"] && $wxapp_template_mp["template_id"]["order_admin51"]){$sqlxm="select * from a_member_unionid where is_subscribe=1";$arrxm=_get_all($sqlxm);foreach ($arrxm as $rsxm) :$rum = _get_one("a_member",$rsxm["openid"],"WXopenid");if($rum && $rum["WXopenid_mp"]){$contex = "您有待支付订单已经取消";$template = '{"touser":"'.$rum["WXopenid_mp"].'","template_id":"'.$wxapp_template_mp["template_id"]["order_admin51"].'","url":"", "data":{"first": {"value":"'.$contex.'","color":"#173177"},"keyword1":{"value":"'.$rsDG["danhao"].'","color":"#173177"},"keyword2": {"value":"用户手动取消", "color":"#173177"},"remark":{"value":"请注意查看!","color":"#173177"}}}';$template = json_decode($template, true);$template = json_encode($template);$res = send_template_mp($template);}endforeach ;}?>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。