PHP微信红包生成代码分享

本文实例为大家分享PHP微信公众号自动发送红包API代码分享给大家供大家参考。具体如下:

贴出核心接口代码至于数据自己填写,接口测试OK

wechat_packet.PHP

rush:PHP;"> '; foreach ($data as $key => $value){ if (is_numeric($value)){ $xml .= "<".$key.">".$value.""; }else{ $xml .= "<".$key.">"; } } $xml .= ''; return $xml; }

}

重写了一下PHP下面的微信API接口,

微信红包支持,JSAPI的动态参数接口支持

PHP">http://git.oschina.net/youkuiyuan/yky_test/blob/master/class/wxapi.class.PHP

微信API类 - 增加红包支持

rush:PHP;"> PHP /******************************************************** * @author Kyler You * @link http://mp.weixin.qq.com/wiki/home/index.html * @version 2.0.1 * @uses $wxApi = new WxApi(); * @package 微信API接口 陆续会继续进行更新 ********************************************************/

class WxApi {
const appId = "";
const appSecret = "";
const mchid = ""; //商户号
const privatekey = ""; //私钥
public $parameters = array();

public function __construct(){

}

/****

  • 微信提交API方法,返回微信指定JSON
    ****/

public function wxHttpsRequest($url,$data = null){
$curl = curl_init();
curl_setopt($curl,$url);
curl_setopt($curl,FALSE);
curl_setopt($curl,FALSE);
if (!empty($data)){
curl_setopt($curl,1);
curl_setopt($curl,$data);
}
curl_setopt($curl,1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}

/****

  • 微信带证书提交数据 - 微信红包使用
    ****/

public function wxHttpsRequestPem($url,$aHeader=array()){
$ch = curl_init();
//超时时间
curl_setopt($ch,$second);
curl_setopt($ch,1);
//这里设置代理,如果有的话
//curl_setopt($ch,'10.206.30.98');
//curl_setopt($ch,8080);
curl_setopt($ch,$url);
curl_setopt($ch,false);
curl_setopt($ch,false);

//以下两种方式需选择一种

//第一种方法,cert 与 key 分别属于两个.pem文件
//认格式为PEM,可以注释
curl_setopt($ch,'PEM');
curl_setopt($ch,getcwd().'/apiclient_cert.pem');
//认格式为PEM,可以注释
curl_setopt($ch,getcwd().'/apiclient_key.pem');

curl_setopt($ch,getcwd().'/rootca.pem');

//第二种方式,两个文件合成一个.pem文件
//curl_setopt($ch,getcwd().'/all.pem');

if( count($aHeader) >= 1 ){
curl_setopt($ch,$aHeader);
}

curl_setopt($ch,1);
curl_setopt($ch,$vars);
$data = curl_exec($ch);
if($data){
curl_close($ch);
return $data;
}
else {
$error = curl_errno($ch);
echo "call faild,errorCode:$error\n";
curl_close($ch);
return false;
}
}

/****

  • 微信获取Accesstoken 返回指定微信公众号的at信息
    ****/

public function wxAccesstoken($appId = NULL,$appSecret = NULL){
$appId = is_null($appId) ? self::appId : $appId;
$appSecret = is_null($appSecret) ? self::appSecret : $appSecret;
//echo $appId,$appSecret;
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
$result = $this->wxHttpsRequest($url);
//print_r($result);
$jsoninfo = json_decode($result,true);
$access_token = $jsoninfo["access_token"];
return $access_token;
}

/****

public function wxGetUser($openId){
$wxAccesstoken = $this->wxAccesstoken();
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$wxAccesstoken."&openid=".$openId."&lang=zh_CN";
$result = $this->wxHttpsRequest($url);
$jsoninfo = json_decode($result,true);
return $jsoninfo;
}

/****

  • 微信通过指定模板信息发送给指定用户,发送完成后返回指定JSON数据
    ****/

public function wxSendTemplate($jsonData){
$wxAccesstoken = $this->wxAccesstoken();
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$wxAccesstoken;
$result = $this->wxHttpsRequest($url,$jsonData);
return $result;
}

/****

public function wxSetSend($touser,$template_id,$url,$data,$topcolor = '#7B68EE'){
$template = array(
'touser' => $touser,'template_id' => $template_id,'url' => $url,'topcolor' => $topcolor,'data' => $data
);
$jsonData = json_encode($template);
$result = $this->wxSendTemplate($jsonData);
return $result;
}

/****

  • 微信设置OAUTH跳转URL,返回字符串信息 - ScopE = snsapi_base //验证时不返回确认页面,只能获取OPENID
    ****/

public function wxOauthBase($redirectUrl,$state = "",$appId = NULL){
$appId = is_null($appId) ? self::appId : $appId;
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appId."&redirect_uri=".$redirectUrl."&response_type=code&scope=snsapi_base&state=".$state."#wechat_redirect";
return $url;
}

/****

  • 微信设置OAUTH跳转URL,返回字符串信息 - ScopE = snsapi_userinfo //获取用户完整信息
    ****/

public function wxOauthUserinfo($redirectUrl,$appId = NULL){
$appId = is_null($appId) ? self::appId : $appId;
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appId."&redirect_uri=".$redirectUrl."&response_type=code&scope=snsapi_userinfo&state=".$state."#wechat_redirect";
return $url;
}

/****

  • 微信OAUTH跳转指定URL
    ****/

public function wxHeader($url){
header("location:".$url);
}

/****

public function wxOauthAccesstoken($code,$appId = NULL,$appSecret = NULL){
$appId = is_null($appId) ? self::appId : $appId;
$appSecret = is_null($appSecret) ? self::appSecret : $appSecret;
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appId."&secret=".$appSecret."&code=".$code."&grant_type=authorization_code";
$result = $this->wxHttpsRequest($url);
//print_r($result);
$jsoninfo = json_decode($result,true);
//$access_token = $jsoninfo["access_token"];
return $jsoninfo;
}

/****

  • 微信通过OAUTH的Access_Token的信息获取当前用户信息 // 只执行在snsapi_userinfo模式运行
    ****/

public function wxOauthUser($OauthAT,$openId){
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$OauthAT."&openid=".$openId."&lang=zh_CN";
$result = $this->wxHttpsRequest($url);
$jsoninfo = json_decode($result,true);
return $jsoninfo;
}

/*****

  • 生成随机字符串 - 最长为32位字符串
    *****/
    public function wxNonceStr($length = 16,$type = FALSE) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMnopQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
    $str .= substr($chars,mt_rand(0,strlen($chars) - 1),1);
    }
    if($type == TRUE){
    return strtoupper(md5(time() . $str));
    }
    else {
    return $str;
    }
    }

/***

  • 微信商户订单号 - 最长28位字符串
    ***/

public function wxMchBillno($mchid = NULL) {
if(is_null($mchid)){
if(self::mchid == "" || is_null(self::mchid)){
$mchid = time();
}
else{
$mchid = self::mchid;
}
}
else{
$mchid = substr(addslashes($mchid),10);
}
return date("Ymd",time()).time().$mchid;
}

/***

  • 微信格式化数组变成参数格式 - 支持url加密
    ***/

public function wxSetParam($parameters){
if(is_array($parameters) && !empty($parameters)){
$this->parameters = $parameters;
return $this->parameters;
}
else{
return array();
}
}

/***

  • 微信格式化数组变成参数格式 - 支持url加密
    ***/

public function wxFormatArray($parameters = NULL,$urlencode = FALSE){
if(is_null($parameters)){
$parameters = $this->parameters;
}
$restr = "";//初始化空
ksort($parameters);//排序参数
foreach ($parameters as $k => $v){//循环定制参数
if (null != $v && "null" != $v && "sign" != $k) {
if($urlencode){//如果参数需要增加URL加密就增加,不需要则不需要
$v = urlencode($v);
}
$restr .= $k . "=" . $v . "&";//返回完整字符串
}
}
if (strlen($restr) > 0) {//如果存在数据则将最后“&”删除
$restr = substr($restr,strlen($restr)-1);
}
return $restr;//返回字符串
}

/***

  • 微信MD5签名生成器 - 需要将参数数组转化成为字符串[wxFormatArray方法]
    ***/
    public function wxMd5Sign($content,$privatekey){
    try {
    if (is_null($key)) {
    throw new Exception("财付通签名key不能为空!");
    }
    if (is_null($content)) {
    throw new Exception("财付通签名内容不能为空");
    }
    $signStr = $content . "&key=" . $key;
    return strtoupper(md5($signStr));
    }
    catch (Exception $e)
    {
    die($e->getMessage());
    }
    }

/***

  • 微信Sha1签名生成器 - 需要将参数数组转化成为字符串[wxFormatArray方法]
    ***/
    public function wxSha1Sign($content,$privatekey){
    try {
    if (is_null($key)) {
    throw new Exception("财付通签名key不能为空!");
    }
    if (is_null($content)) {
    throw new Exception("财付通签名内容不能为空");
    }
    $signStr = $content . "&key=" . $key;
    return strtoupper(sha1($signStr));
    }
    catch (Exception $e)
    {
    die($e->getMessage());
    }
    }

/***

  • 将数组解析XML - 微信红包接口
    ***/

public function wxArrayToXml($parameters = NULL){
if(is_null($parameters)){
$parameters = $this->parameters;
}

if(!is_array($parameters) || empty($parameters)){
die("参数不为数组无法解析");
}

$xml = "";
foreach ($arr as $key=>$val)
{
if (is_numeric($val))
{
$xml.="<".$key.">".$val."</".$key.">";
}
else
$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
}
$xml.="
";
return $xml;
}

}

后期还是会增加在一起的把这个CLASS做起来,网上资源很多,但是都是有一定基础的人去看看改改可以,对于没有接触刚刚接触的新手还是需要给予支持的。帮助用户屡屡思路。

根据微信高级红包接口,开发PHP版本的API接口,现在进行主要代码分析。

红包接口调用请求代码,所有请求参数为必填参数与文档对应:

setParameter("nonce_str",$this->great_rand());//随机字符串,丌长于 32 位 $wxHongBaoHelper->setParameter("mch_billno",$this->app_mchid.date('YmdHis').rand(1000,9999));//订单号 $wxHongBaoHelper->setParameter("mch_id",$this->app_mchid);//商户号 $wxHongBaoHelper->setParameter("wxappid",$this->app_id); $wxHongBaoHelper->setParameter("nick_name",'红包');//提供方名称 $wxHongBaoHelper->setParameter("send_name",'红包');//红包发送者名称 $wxHongBaoHelper->setParameter("re_openid",$re_openid);//相对于医脉互通的openid $wxHongBaoHelper->setParameter("total_amount",100);//付款金额,单位分 $wxHongBaoHelper->setParameter("min_value",100);//最小红包金额,单位分 $wxHongBaoHelper->setParameter("max_value",100);//最大红包金额,单位分 $wxHongBaoHelper->setParameter("total_num",1);//红包収放总人数 $wxHongBaoHelper->setParameter("wishing",'感谢您参与红包派发活动,祝您新年快乐!');//红包祝福诧 $wxHongBaoHelper->setParameter("client_ip",'127.0.0.1');//调用接口的机器 Ip 地址 $wxHongBaoHelper->setParameter("act_name",'红包活动');//活劢名称 $wxHongBaoHelper->setParameter("remark",'快来抢!');//备注信息 $postXml = $wxHongBaoHelper->create_hongbao_xml(); $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack'; $responseXml = $wxHongBaoHelper->curl_post_ssl($url,$postXml); //用作结果调试输出 //echo htmlentities($responseXml,ENT_COMPAT,'UTF-8'); $responSEObj = simplexml_load_string($responseXml,LIBXML_NOCDATA); return $responSEObj->return_code; }

获取随机字符串方法

rush:PHP;"> /** * 生成随机数 */ public function great_rand(){ $str = '1234567890abcdefghijklmnopqrstuvwxyz'; for($i=0;$i<30;$i++){ $j=rand(0,35); $t1 .= $str[$j]; } return $t1; }

签名算法:

rush:PHP;"> /** 例如: appid: wxd111665abv58f4f mch_id: 10000100 device_info: 1000 Body: test nonce_str: ibuaiVcKdpRxkhJA 第一步:对参数按照 key=value 的格式,并按照参数名 ASCII 字典序排序如下: stringA="appid=wxd930ea5d5a258f4f&body=test&device_info=1000&mch_i d=10000100&nonce_str=ibuaiVcKdpRxkhJA"; 第二步:拼接支付密钥: stringSignTemp="stringA&key=192006250b4c09247ec02edce69f6a2d" sign=MD5(stringSignTemp).toupperCase()="9A0A8659F005D6984697E2CA0A 9CF3B7" */ protected function get_sign(){ define('PARTNERKEY',"QSRXXXXXXXXXXXXXXXXXXXXX"); try { if (null == PARTNERKEY || "" == PARTNERKEY ) { throw new SDKRuntimeException("密钥不能为空!" . "
"); } if($this->check_sign_parameters() == false) { //检查生成签名参数 throw new SDKRuntimeException("生成签名参数缺失!" . "
"); } $commonUtil = new CommonUtil(); ksort($this->parameters); $unSignParaString = $commonUtil->formatQueryParaMap($this->parameters,false); $md5SignUtil = new MD5SignUtil(); return $md5SignUtil->sign($unSignParaString,$commonUtil->trimstring(PARTNERKEY)); }catch (SDKRuntimeException $e) { die($e->errorMessage()); }

}

CURL请求以及发送证书:

= 1 ){ curl_setopt($ch,$vars); $data = curl_exec($ch); if($data){ curl_close($ch); return $data; } else { $error = curl_errno($ch); //echo "call faild,errorCode:$error\n"; curl_close($ch); return false; } }

入口文件

_route('userinfo',$param); if(empty($userinfo['openid'])){ exit("NOAUTH"); } //调取支付方法 $packet->_route('wxpacket',array('openid'=>$userinfo['openid'])); }else{ $packet->_route('userinfo'); }

以上就是本文的全部内容,希望对大家学习PHP程序设计有所帮助,也希望大家多多支持编程之家。

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...