微信现金红包接口实现红包发放
微信現金紅包接口實現紅包發放:
一:流程:【
流程:微信用戶訪問紅包活動頁面--》后端判斷是否是微信訪問的
【否:提示用微信打開連接,是:提示用戶是否授權允許,獲取其的用戶信息【openID等信息】】--》
進入紅包活動頁面---》用戶點擊領取紅包【判斷是否領取過紅包】是:【提示已領取過紅包】否?
--》后端程序調用接口發放紅包
--》微信用戶在微信中收到紅包
--》打開紅包
--》紅包金額會添加到錢包零錢里
--》完成紅包發放。
】
二:要實現微信現金紅包接口實現紅包發放,首先要符合以下條件:
1.用于發放紅包的微信公眾號要是服務類型
2.登錄微信公眾平臺官網后,在公眾平臺后臺管理頁面 - 開發者中心頁,
點擊“修改配置”按鈕,填寫服務器地址(URL)、Token和EncodingAESKey,
其中URL是開發者用來接收微信消息和事件的接口URL。Token可由開發者可以任意填寫,
用作生成簽名(該Token會和接口URL中包含的Token進行比對,從而驗證安全性)。
EncodingAESKey由開發者手動填寫或隨機生成,將用作消息體加解密密鑰。
3.獲取access_token:公眾號可以使用AppID和AppSecret調用本接口來獲取access_token。
【AppID和AppSecret可在微信公眾平臺官網-開發者中心頁中獲得(需要已經成為開發者,且帳號沒有異常狀態)。】
4.微信公眾號要開通 “網頁授權接口” 用戶獲取用戶基本信息【特別是openID ,發紅包時用到】
5.微信公眾號的 “微信支付“ ?中的 ?”商戶號” 要開通微信支付【發紅包的金額是該支付賬戶扣款】,開通“現金紅包”接口【調用該接口發放紅包】。
6. 登陸 ”商戶號”【微信公眾號分配的商戶號。第5 中有說明】 在 “API安全” 中 下載PHP版的 證書 【.pem格式】
以上如描述不清楚,請查看 微信開發者文檔 里面有詳細的秒殺。
部分代碼如下【其余的請查看附件】:
<?php namespace?RedClient\Controller; use?Think\Controller; use?RedClient\Redpack\WeiXinInfo; use?RedClient\Redpack\Oauth; use?RedClient\Redpack\SendRedPack; use?RedClient\Redpack\CreateRedPack; class?IndexController?extends?Controller?{public?function?index(){$this->isWeixin();//是否是微信打開if($this->access){$this->display();}else{$class=new?Oauth();$class->index('http://www.myweb.com/index.php/Index/oauth');}}//獲取用戶信息?openIDpublic?function?oauth(){$code=isset($_GET['code'])?strip_tags(trim($_GET['code'])):'';$state=isset($_GET['state'])?strip_tags(trim($_GET['state'])):'';$class=new?Oauth();$userInfo=$class->getCode($code,$state);//獲取用戶信息if(!empty($userInfo['data'])){//$model=M('wxuser');//$result=$model->where('openid?=?"'.$userInfo['data']->openid.'"')->field('openid')->select();if(empty($result)){$userInfo['data']=$this->object2array($userInfo['data']);$model->data($userInfo['data'])->add();}}$userInfo['data']=$this->object2array($userInfo['data']);//創建紅包$class=new?CreateRedPack();$red=$class->redval();//發紅包$class=new?SendRedPack();$configs=array('send_name'=>'紅包發送者名稱',//紅包發送者名稱're_openid'=>$userInfo['data']['openid'],//接受紅包的用戶,用戶在wxappid下的openid'total_amount'=>$red,//付款金額,單位分'total_num'=>'1',//紅包發放總人數'wishing'=>'紅包祝福語',//紅包祝福語'client_ip'=>$_SERVER['SERVER_ADDR'],//調用接口的機器Ip地址'act_name'=>'活動名稱',//活動名稱'remark'=>'備注信息',// 備注信息);$class->setFields($configs);$result=$class->requestXml();//微信返回信息處理if(strtoupper($result['return_code'])=='SUCCESS'){if(strtoupper($result['result_code'])=='SUCCESS'){//紅包發送成功!$datas['flag']=1;echo?$result['err_code_des'];}else{//紅包發送失敗$datas['flag']=0;$datas['msg']=$result['err_code_des'];echo?$result['err_code_des'];}}else{//紅包發送失敗$datas['flag']=0;$datas['msg']=$result['err_code_des'];echo?$result['err_code_des'];}}public?function?isWeixin(){if?(strpos($_SERVER['HTTP_USER_AGENT'],?'MicroMessenger')?!==?false)?{?$this->access=true;?}?return?false;?}//類轉換成數組public?function?object2array($object)?{if?(is_object($object))?{foreach?($object?as?$key?=>?$value)?{$array[$key]?=?$value;}}else?{$array?=?$object;}return?$array;}}?><?php namespace?RedClient\Redpack; /**簡單紅包算法類 **/ class?CreateRedPack{private?$rid=0;//當前紅包隨機數private?$rand_arr=array();//35%是1.0到1.1?紅包隨機數private?$rand_arr1=array();//35%是1.1到1.2?紅包隨機數private?$rand_arr2=array();//30%是1.2到1.95?紅包隨機數private?$red=0;//紅包金額private?$simplered=0;private?$red_config=array(array('min'=>1.0,'max'=>1.1),array('min'=>1.1,'max'=>1.2),array('min'=>1.2,'max'=>1.95));public?function?__construct(){$this->rid=mt_rand(1,10000);//當前紅包隨機數$this->rand_arr=range(1,3500);//35%是1.0到1.1$this->rand_arr1=range(3501,7000);//35%是1.1到1.2$this->rand_arr2=range(7001,10000);//30%是1.2到1.95$this->simplered=666;}public?function?redval(){$maxrp=$this->maxred();//隨機最大紅包金額if($maxrp!=$this->simplered){if(in_array($this->rid,$this->rand_arr)){$red_val=$this->red_config[0];$min=$red_val['min']*100;$max=$red_val['max']*100;$this->red=mt_rand($min,$max);$this->red=$this->red/100;}elseif(in_array($this->rid,$this->rand_arr1)){$red_val=$this->red_config[1];$min=$red_val['min']*100;$max=$red_val['max']*100;$red=mt_rand($min,$max);$this->red=$this->red/100;}elseif(in_array($this->rid,$this->rand_arr2)){$red_val=$this->red_config[2];$min=$red_val['min']*100;$max=$red_val['max']*100;$this->red=mt_rand($min,$max);$this->red=$this->red/100;}}else{$this->red=$maxrp;}return?$this->red?$this->red:1;}protected?function?maxred(){$rid=mt_rand(1,100000);$rid1=mt_rand(1,100000);$red=0;$dff=$rid-$rid1;if($dff?>?0){if(($rid1%$rid1)==$this->simplered){$red=$this->simplered;}}else{if(($rid1%$rid)==$this->simplered){$red=$this->simplered;}}return?$red;}}?><?php namespace?RedClient\Redpack; /*********先在公共平臺配置授權的域名;然后才能通過,網頁授權方式獲取微信用戶基本信息網頁授權流程分為四步:?1.引導用戶進入授權頁面同意授權,獲取code?2.通過code換取網頁授權access_token(與基礎支持中的access_token不同)?3.如果需要,開發者可以刷新網頁授權access_token,避免過期?4.通過網頁授權access_token和openid獲取用戶基本信息?**********/ class?Oauth{protected?$appid='';protected?$redirect_uri='';protected?$state='';//mt_rand(100,999);protected?$appsecret='';protected?$data=array('flag'=>0,'msg'=>'','data'=>'');public?function?__construct(){$this->appid='appid';//$this->appsecret='secret';//;$this->state=mt_rand(100,999);}//引導用戶訪問鏈接處理函數 public?function?index($redirect_uri){$this->redirect_uri=urlencode($redirect_uri);//微信自動跳轉到$redirect_uriheader('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.$this->redirect_uri.'/oauth.php&response_type=code&scope=snsapi_userinfo&state='.$this->state.'&connect_redirect=1#wechat_redirect');}public?function?getCode($code='',$state='',$token='',$webToken=''){$data=array('errorno'=>'','errormsg'=>'','data'=>'');if(empty($code)){$this->data['flag']=0;$this->data['msg']='授權失敗!';}else{ /*?1獲取webtoken2獲取reflash_token3獲取用戶信息?*/$token_url?=?'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code';$token?=?json_decode(file_get_contents($token_url));if?(isset($token->errcode))?{$data['errorno']=$token->errcode;$data['errormsg']=$token->errmsg;}else{$access_token_url?=?'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;//轉成對象$accessToken?=?json_decode(file_get_contents($access_token_url));if?(isset($accessToken->errcode))?{$data['errorno']=$token->errcode;$data['errormsg']=$token->errmsg;}else{$user_info_url?=?'https://api.weixin.qq.com/sns/userinfo?access_token='.$accessToken->access_token.'&openid='.$accessToken->openid.'&lang=zh_CN';//轉成對象$userInfo?=?json_decode(file_get_contents($user_info_url));if?(isset($userInfo->errcode))?{$data['errorno']=$token->errcode;$data['errormsg']=$token->errmsg;}else{$data['data']=$userInfo;}}}}return?$data;}}?><?php /******用于企業向微信用戶個人發現金紅包目前支持向指定微信用戶的openid發放指定金額紅包。(獲取openid參見微信公眾平臺開發者文檔:網頁授權獲取用戶基本信息)****/ namespace?RedClient\Redpack;class?SendRedPack{private?$config=array('nonce_str'=>'',//隨機字符串,不長于32位'sign'=>'',//簽名'mch_billno'=>'',//商戶訂單號'mch_id'=>'1111sdfsafsaddf',//微信支付分配的商戶號'wxappid'=>'sddafdsadfdsafdsdd',//微信分配的公眾賬號ID'send_name'=>'',//紅包發送者名稱're_openid'=>'',//接受紅包的用戶,用戶在wxappid下的openid'total_amount'=>'',//付款金額,單位分'total_num'=>'',//紅包發放總人數'wishing'=>'',//紅包祝福語'client_ip'=>'',//調用接口的機器Ip地址'act_name'=>'',//活動名稱'remark'=>'',// 備注信息);protected?$key='';protected?$url='https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';protected?$requestXml='';//設置必要參數public?function?setFields($conf=array()){foreach($conf?as?$k=>$v){if(isset($this->config[$k])?&&?!empty($v)){$this->config[$k]=$v;}}$this->config['mch_billno']=$this->billno();$this->config['nonce_str']=$this->createNonceStr();$this->createSign($conf);$this->createXml();//echo?$this->requestXml;}protected?function?billno(){return?$this->config['mch_id'].time().md5(mt_rand(1000,9999));}/*?//檢查必要參數是否為空!public?function?checkConfig(){$flag=true;foreach($this->config?as?$k=>$v){if(empty($v)){$flag=false;break;}}}?*///隨機字符串,不長于32位public?function?createNonceStr(?$len=32?){$strs?=?"abcdefghijklmnopqrstuvwxyz0123456789";$str?="";$len=$len<=32?$len:32;for?(?$i?=?0;?$i?<?$len;?$i++?){$str.=?substr($strs,?mt_rand(0,?strlen($strs)-1),?1);}return?$str;}//格式化參數public?function?formatParam($config=array(),$flag=1){$format='';if(!empty($config)){ksort($config);foreach($config?as?$k=>$v){if($flag){$v=urlencode($v);}if($flag==0?&&?strtolower($k)=='sign'){continue;}$format.=$k.'='.$v.'&';}$format=trim($format,'&');}return?$format;}//創建SIGNATURE protected?function?createSign($config){$format=$this->formatParam($config,0);$format.='&key='.$this->key;$signature=strtoupper(md5($format));$this->config['sign']=$signature;return?true;//$signature;}//創建xml格式數據protected?function?createXml(){$xml='<xml>';foreach($this->config?as?$k=>$v){if(!empty($v)){$xml.='<'.$k.'><![CDATA['.$v.']]></'.$k.'>';}}$xml.='</xml>';$this->requestXml=$xml;}//XML格式數據轉換為數組public?function?createArray($xml=''){$arr?=?json_decode(json_encode(simplexml_load_string($xml,?'SimpleXMLElement',?LIBXML_NOCDATA)),?true);return?$arr;}//發送紅包public?function?requestXml($timeout=30,$header=array()){$ch?=?curl_init();//超時時間curl_setopt($ch,CURLOPT_TIMEOUT,$timeout);curl_setopt($ch,CURLOPT_RETURNTRANSFER,?1);curl_setopt($ch,CURLOPT_URL,$this->url);curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//默認格式為PEM,可以注釋curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');curl_setopt($ch,CURLOPT_SSLCERT,dirname(__FILE__).'/apiclient_cert.pem');//pem證書地址//默認格式為PEM,可以注釋curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');curl_setopt($ch,CURLOPT_SSLKEY,dirname(__FILE__).'/apiclient_key.pem');//key證書地址curl_setopt($ch,CURLOPT_CAINFO,'PEM');curl_setopt($ch,CURLOPT_CAINFO,dirname(__FILE__).'/rootca.pem');//CA證書地址//兩個文件合成一個.pem文件//curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');if(?count($header)?>=?1?){curl_setopt($ch,?CURLOPT_HTTPHEADER,?$header);}curl_setopt($ch,CURLOPT_POST,?1);curl_setopt($ch,CURLOPT_POSTFIELDS,$this->requestXml);$data?=?curl_exec($ch);var_dump($data);if($data){curl_close($ch);var_dump($data);return?$data;}else?{$error?=?curl_errno($ch);echo?'ERROR:'.$error;curl_close($ch);return?false;}}//返回非空值,非NULLpublic?function?notEmpty($val=''){$return='';if(null?!=$val?&&?strlen($val)?!=?0){$return=$val;}return?$return?$return:false;}}?><?php namespace?RedClient\Redpack; class?WeiXinInfo{private?$AppID='appid';private?$AppSecret='secret';private?$grant_type='client_credential';private?$url='https://api.weixin.qq.com/cgi-bin/token';public?function?__construct(){//$arr=array('access_token'=>'1','expires'=>'7200');}//設置獲取ACCESSTOKEN?的URLpublic?function?setUrl(){return?$this->url=$this->url.'?grant_type='.$this->grant_type.'&appid='.$this->AppID.'&secret='.$this->AppSecret;}//獲取APPID,SECRETpublic?function?getAppid(){$sql='select?appid,secret?from?ly_appid?where?flag=1';$model=M();$result=$model->query($sql);if(!empty($result)){$this->AppID=$result[0]['appid'];$this->AppSecret=$result[0]['secret'];return?$result[0];}}public?function?object2array($object)?{if?(is_object($object))?{foreach?($object?as?$key?=>?$value)?{$array[$key]?=?$value;}}else?{$array?=?$object;}return?$array;}//檢驗URL有效public?function?checkUrl(){$signature=isset($_GET['signature'])?strip_tags(trim($_GET['signature'])):'';$timestamp=isset($_GET['timestamp'])?strip_tags(trim($_GET['timestamp'])):'';$nonce=isset($_GET['nonce'])?strip_tags(trim($_GET['nonce'])):'';$echostr=isset($_GET['echostr'])?$_GET['echostr']:'';if(!empty($signature)?&&?!empty($timestamp)?&&?!empty($nonce)){if($this->checkSign($signature,$timestamp,$nonce)){echo?$echostr;return?true;}else{return?false;}}} //驗證SIGNATURE是否有效private?function?checkSign($sign,$timestamp,$nonce){$token=$this->getAccessToken();//$token=$this->object2array($token);$sign_arr=array($token,$timstamp,$nonce);sort($sign_arr,SORT_STRING);$signStr=implode($sign_arr);$signStr=sha1($signStr);if(strtoupper($signStr)==strtoupper($sign)){return?true;}return?false;}//通過微信接口獲取微信Access_Token public?function?getAccessToken(){$token='';$this->setUrl();$check=$this->checkToken();if(session('?'.md5('getaccesstoken'))?&&?$check){$tokens=session(md5('getaccesstoken'));$token=$tokens->access_token;}else{$result=file_get_contents($this->url);$result=json_decode($result);$token=$result->access_token;$result->expires_in=$result->expires_in+time();session(md5('getaccesstoken'),$result);}return?$token;}//檢查微信ACCESS_TOKEN是否有效public?function?checkToken(){if(session('?'.md5('getaccesstoken'))?&&?session(md5('getaccesstoken'))){$time=time();$token=session(md5('getaccesstoken'));if($token->expires_in-$time?>?30){return?true;}else{session(md5('getaccesstoken'),null);}}return?false;}//保存微信ACCESSTOKEN到數據庫 public?function?saveAccessToken(){$token=$this->getAccessToken();$sql='select?`id`,`rate`,token,ex_time,createtime?from?ly_token?where?token="'.$token.'"?where?appid="'.$this->AppID.'"?AND?secret="'.$this->AppSecret.'"';$model=M();$result=$model->query($sql);if(!empty($result)){$time=time();$expires=$time-$result[0]['createtime'];if($result[0]['ex_time']-$expires?>?0){return?$result[0]['token']; }else{$token=$this->getAccessToken();if(!empty($token)){$token=json_decode($token);if(!isset($token['errcode'])?or?!$token['errcode']){if(isset($token['access_token'])?&&?$token['access_token']){$data['access_token']=$token['access_token'];$data['createtime']=$time;$data['ex_time']=$token['expires_in'];$data['rate']=$result[0]['rate']+1;//$sql='update?ly_token?set?token="'.$token['access_token'].'"?,createtime='.$time.',ex_time='.$token['expires_in'].'?where?`id`='.$result[0]['id'];$model=M('token');$update=$model->where('`id`='.$result[0]['id'])->save($data);if($update){return?$token['access_token'];}}}else{//微信返回的錯誤信息$data['errcode']=$token['errcode'];$data['errmsg']=$token['errmsg'];$data['appid']=$this->AppID;$data['secret']=$this->AppSecret;$data['createtime']=time();$data['rate']=$result[0]['rate']+1;$ein=$model->where('`id`='.$result[0]['id'])->save($data);if($ein){return?false;}}}}}else{//新插入數據庫保存$token=$this->getAccessToken();$model=M('token');if(!empty($token)){$data=array();$token=json_decode($token);if(!isset($token['errcode'])?or?!$token['errcode']){if(isset($token['access_token'])?&&?$token['access_token']){$data['access_token']=$token['access_token'];$data['createtime']=$time;$data['ex_time']=$token['expires_in'];//$sql='insert?into?ly_token()?vlaues()';$data['rate']=1;$in=$model->data($data)->add();if($ein){$token['access_token'];}}}else{//微信返回的錯誤信息$data['errcode']=$token['errcode'];$data['errmsg']=$token['errmsg'];$data['appid']=$this->AppID;$data['secret']=$this->AppSecret;$data['createtime']=time();$data['rate']=1;$ein=$model->data($data)->add();if($ein){return?false;}}}}return?false;} }?>轉載于:https://blog.51cto.com/yipianlvye/1915337
總結
以上是生活随笔為你收集整理的微信现金红包接口实现红包发放的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JS字符串处理函数
- 下一篇: Java代码03-打印一个菱形