PHP微信红包生成代码分享


Posted in PHP onOctober 06, 2016

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

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

<!--?php
/**
 * 发送红包接口
 * Created by PhpStorm.
 * User: ADKi
 * Date: 2016/4/25 0025
 * Time: 15:25
 */

class wechat_packet{
 private $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';//请求URL
 private $mch_id;//商户号
 private $weixin_appid;//公众账号appid
 private $send_name;//商户名称
 private $total_num = 1;//发送红包总人数
 private $wishing;//红包祝福语
 private $client_ip;//调用接口的机器Ip地址
 private $act_name;//活动名称
 private $remark;//备注信息
 private $nonce_str;//随机字符串,不长于32位
 private $api_password;
 private $arraytoxml;//数组转xml
 /**
 * 公钥
 */
 private $public_key = "/api/wechat/cert/apiclient_cert.pem";
 /**
 * 私钥
 */
 private $private_key = '/api/wechat/cert/apiclient_key.pem';
 /**
 * ca证书
 */
 private $rootca = 'api/wechat/cert/rootca.pem';
 public function __construct()
 {
 //初始化红包设置信息
 $this--->weixin_appid = C('wap_weixin_appid');
 $this->mch_id = C('wechat_mch_id');
 $this->send_name = C('wechat_send_name');
 $this->wishing = C('wechat_wishing');
 $this->act_name = C('wechat_act_name');
 $this->client_ip = $_SERVER['SERVER_ADDR'];
 $this->remark = C('wechat_remark');
 $this->nonce_str = $this->create_nonce_str(32);
 $this->api_password = C('wechat_api_password');
 $inc_file = BASE_PATH.DS.'api'.DS.'wechat'.DS.'arraytoxml.php';
 if(is_file($inc_file)) {
 require($inc_file);
 }
 $this->arraytoxml = new ArrayToXML();
 }
 
 public function send_post($mch_billno,$re_openid,$total_amount){
 $sign = $this->create_sign($mch_billno,$re_openid,$total_amount);
 $send_array = array(
 'nonce_str' => $this->nonce_str,
 'mch_billno' => $mch_billno,
 'mch_id' => $this->mch_id,
 'wxappid' => $this->weixin_appid,
 'send_name' => $this->send_name,
 're_openid' => $re_openid,
 'total_amount' => $total_amount,
 'total_num' => $this->total_num,
 'wishing' => $this->wishing,
 'client_ip' => $this->client_ip,
 'act_name' => $this->act_name,
 'remark' => $this->remark,
 'sign' => $sign,
 );
 $send_xml = $this->arraytoxml->toXml($send_array,'');
 $data = $this->curl_post_ssl($this->url, $send_xml);
 $data = $this->xmlToArray($data);
 file_put_contents('adki',var_export($data,true),FILE_APPEND);
 }
 /*
 请确保您的libcurl版本是否支持双向认证,版本高于7.20.1
 */
 private function curl_post_ssl($url, $vars, $second=30,$aHeader=array()){
 $ch = curl_init();
 //超时时间
 curl_setopt($ch,CURLOPT_TIMEOUT,$second);
 curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
 //这里设置代理,如果有的话
 //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
 //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
 curl_setopt($ch,CURLOPT_URL,$url);
 curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
 curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
 //以下两种方式需选择一种
 //第一种方法,cert 与 key 分别属于两个.pem文件
 //默认格式为PEM,可以注释
 curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
 curl_setopt($ch,CURLOPT_SSLCERT,getcwd().$this->public_key);
 //默认格式为PEM,可以注释
 curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
 curl_setopt($ch,CURLOPT_SSLKEY,getcwd().$this->private_key);
 //ca证书
 curl_setopt($ch,CURLOPT_CAINFO,$this->rootca);
 //第二种方式,两个文件合成一个.pem文件
 //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');
 if( count($aHeader) >= 1 ){
 curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
 }
 curl_setopt($ch,CURLOPT_POST, 1);
 curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
 $data = curl_exec($ch);
 if($data){
 curl_close($ch);
 return $data;
 }
 else {
 $error = curl_errno($ch);
 echo "call faild, errorCode:$error\n\n\n\n";
 curl_close($ch);
 return false;
 }
 }
 //生成签名
 private function create_sign($mch_billno,$re_openid,$total_amount){
 $string_array = array(
 'act_name' => $this->act_name,
 'client_ip' => $this->client_ip,
 'mch_billno' => $mch_billno,
 'mch_id' => $this->mch_id,
 'nonce_str' => $this->nonce_str,
 're_openid' => $re_openid,
 'remark' => $this->remark,
 'send_name' => $this->send_name,
 'total_amount' => $total_amount,
 'total_num' => $this->total_num,
 'wishing' => $this->wishing,
 'wxappid' => $this->weixin_appid,
 );
 foreach ($string_array as $key => $value){

 if(!empty($value)){

 $stringA .= "$key=$value";
 if($key != 'wxappid'){

  $stringA .= '&';
 }
 }
 }
 //转成UTF-8
 $stringA = $this->gbkToUtf8($stringA);
 $stringSignTemp="$stringA&key=$this->api_password";
 $sign = MD5($stringSignTemp);

 $sign = strtoupper($sign);
 return $sign;
 }
 //生成随机字符串
 private function create_nonce_str($length){
 $str = null;
 $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
 $max = strlen($strPol)-1;
 for($i=0;$i<$length;$i++){
 $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
 }

 return $str;
 }
 /**
 *自动判断把gbk或gb2312编码的字符串转为utf8
 *能自动判断输入字符串的编码类,如果本身是utf-8就不用转换,否则就转换为utf-8的字符串
 *支持的字符编码类型是:utf-8,gbk,gb2312
 *@$str:string 字符串
 */
 private function gbkToUtf8($str){
 $charset = mb_detect_encoding($str,array('ASCII','UTF-8','GBK','GB2312'));
 $charset = strtolower($charset);
 if("utf-8" != $charset){
 $str = iconv('UTF-8',$charset,$str);
 }
 return $str;

 }
 private function xmlToArray($postStr){
 $msg = array();
 $msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
 return $msg;
 }
}

数组转xml:arraytoxml.php

<!--?php
/**
 * Created by PhpStorm.
 * User: ADKi
 * Date: 2016/4/26 0026
 * Time: 12:19
 */
class ArrayToXML
{
 public function toXml($data){
 $xml = '<xml-->';
 foreach ($data as $key => $value){
 if (is_numeric($value)){
 $xml .= "<".$key.">".$value."<!--".$key."-->";
 }else{
 $xml .= "<".$key."><!--[CDATA[".$value."]]--><!--".$key."-->";
 }
 }
 $xml .= '';
 return $xml;
 }

}

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

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

http://git.oschina.net/youkuiyuan/yky_test/blob/master/class/wxapi.class.php

微信API类 - 增加红包支持

<?php
 /********************************************************
 * @author Kyler You <QQ:2444756311>
 * @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, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  if (!empty($data)){
   curl_setopt($curl, CURLOPT_POST, 1);
   curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  }
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  $output = curl_exec($curl);
  curl_close($curl);
  return $output;
 }
 
 /****************************************************
  * 微信带证书提交数据 - 微信红包使用
  ****************************************************/
 
 public function wxHttpsRequestPem($url, $vars, $second=30,$aHeader=array()){
  $ch = curl_init();
  //超时时间
  curl_setopt($ch,CURLOPT_TIMEOUT,$second);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
  //这里设置代理,如果有的话
  //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
  //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
  curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
 
  //以下两种方式需选择一种
 
  //第一种方法,cert 与 key 分别属于两个.pem文件
  //默认格式为PEM,可以注释
  curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
  curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/apiclient_cert.pem');
  //默认格式为PEM,可以注释
  curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
  curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/apiclient_key.pem');
 
  curl_setopt($ch,CURLOPT_CAINFO,'PEM');
  curl_setopt($ch,CURLOPT_CAINFO,getcwd().'/rootca.pem');
 
  //第二种方式,两个文件合成一个.pem文件
  //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');
 
  if( count($aHeader) >= 1 ){
   curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
  }
 
  curl_setopt($ch,CURLOPT_POST, 1);
  curl_setopt($ch,CURLOPT_POSTFIELDS,$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;
 }
 
 /****************************************************
  * 微信通过OPENID获取用户信息,返回数组
  ****************************************************/
 
 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,$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_userinfo&state=".$state."#wechat_redirect";
  return $url;
 }
 
 /****************************************************
  * 微信OAUTH跳转指定URL
  ****************************************************/
 
 public function wxHeader($url){
  header("location:".$url);
 }
 
 /****************************************************
  * 微信通过OAUTH返回页面中获取AT信息
  ****************************************************/
 
 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),0,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, 0, 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 = "<xml>";
  foreach ($arr as $key=>$val)
  {
  if (is_numeric($val))
  {
   $xml.="<".$key.">".$val."</".$key.">"; 
  }
  else
   $xml.="<".$key."><![CDATA[".$val."]]></".$key.">"; 
  }
  $xml.="</xml>";
  return $xml; 
 }
  
 }

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

再来一份:

首先给大家看一看这个表格:

PHP微信红包生成代码分享

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

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

class Wxapi {
 private $app_id = 'wxXXXXXXXXXXXX'; //公众账号appid,首先申请与之配套的公众账号
 private $app_secret = 'XXXXXXXXXXXXXXXXXXXXXXXX';//公众号secret,用户获取用户授权token
 private $app_mchid = 'XXXXXXXX';//商户号id
 function __construct(){
 //do sth here....
 }
 /**
 * 微信支付
 * @param string $openid 用户openid
 */
 public function pay($re_openid)
 {
 include_once('WxHongBaoHelper.php');
 $commonUtil = new CommonUtil();
 $wxHongBaoHelper = new WxHongBaoHelper();
 $wxHongBaoHelper->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, 'SimpleXMLElement', LIBXML_NOCDATA);
 return $responseObj->return_code;
 }

获取随机字符串方法:

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

签名算法:

/**
例如:
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("密钥不能为空!" . "<br>");
 }
 if($this->check_sign_parameters() == false) { //检查生成签名参数
 throw new SDKRuntimeException("生成签名参数缺失!" . "<br>");
 }
 $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请求以及发送证书:

function curl_post_ssl($url, $vars, $second=30,$aHeader=array())
{
 $ch = curl_init();
 //超时时间
 curl_setopt($ch,CURLOPT_TIMEOUT,$second);
 curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
 //这里设置代理,如果有的话
 curl_setopt($ch,CURLOPT_URL,$url);
 curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
 curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); 
 //cert 与 key 分别属于两个.pem文件
 //请确保您的libcurl版本是否支持双向认证,版本高于7.20.1
 curl_setopt($ch,CURLOPT_SSLCERT,dirname(__FILE__).DIRECTORY_SEPARATOR.'zhengshu'.DIRECTORY_SEPARATOR.'apiclient_cert.pem');
 curl_setopt($ch,CURLOPT_SSLKEY,dirname(__FILE__).DIRECTORY_SEPARATOR.'zhengshu'.DIRECTORY_SEPARATOR.'apiclient_key.pem');
 curl_setopt($ch,CURLOPT_CAINFO,dirname(__FILE__).DIRECTORY_SEPARATOR.'zhengshu'.DIRECTORY_SEPARATOR.'rootca.pem');
 if( count($aHeader) >= 1 ){
 curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
 }
 curl_setopt($ch,CURLOPT_POST, 1);
 curl_setopt($ch,CURLOPT_POSTFIELDS,$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;
 }
}

入口文件:

@require "pay.php";
//获取用户信息
$get = $_GET['param'];
$code = $_GET['code'];
//判断code是否存在
if($get=='access_token' && !empty($code)){
 $param['param'] = 'access_token';
 $param['code'] = $code;
 $packet = new Packet();
 //获取用户openid信息
 $userinfo = $packet->_route('userinfo',$param);
 if(empty($userinfo['openid'])){
 exit("NOAUTH");
 }
 //调取支付方法
 $packet->_route('wxpacket',array('openid'=>$userinfo['openid']));
}else{
 $packet->_route('userinfo');
}

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

PHP 相关文章推荐
深入解析yii权限分级式访问控制的实现(非RBAC法)
Jun 13 PHP
php json_encode()函数返回json数据实例代码
Oct 10 PHP
php实现mysql事务处理的方法
Dec 25 PHP
PHP扩展开发入门教程
Feb 26 PHP
php将12小时制转换成24小时制的方法
Mar 31 PHP
ThinkPHP文件缓存类代码分享
Apr 22 PHP
fsockopen pfsockopen函数被禁用,SMTP发送邮件不正常的解决方法
Sep 20 PHP
PHP匿名函数和use子句用法实例
Mar 16 PHP
PHP正则表达式过滤html标签属性(DEMO)
May 04 PHP
Yii中srbac权限扩展模块工作原理与用法分析
Jul 14 PHP
PHP asXML()函数讲解
Feb 03 PHP
PHP超级全局变量【$GLOBALS,$_SERVER,$_REQUEST等】用法实例分析
Dec 11 PHP
php下载文件超时时间的设置方法
Oct 06 #PHP
详谈php静态方法及普通方法的区别
Oct 04 #PHP
php操作路径的经典方法(必看篇)
Oct 04 #PHP
php将文件夹打包成zip文件的简单实现方法
Oct 04 #PHP
浅谈PHP中静态方法和非静态方法的相互调用
Oct 04 #PHP
PHP图片添加水印功能示例小结
Oct 03 #PHP
PHP通过CURL实现定时任务的图片抓取功能示例
Oct 03 #PHP
You might like
自制短波长线天线频率预选器 - 成功消除B2K之流的镜像
2021/03/02 无线电
使用NetBeans + Xdebug调试PHP程序的方法
2011/04/12 PHP
通达OA公共代码 php常用检测函数
2011/12/14 PHP
注册页面之前先验证用户名是否存在的php代码
2012/07/14 PHP
php使用正则表达式提取字符串中尖括号、小括号、中括号、大括号中的字符串
2020/04/05 PHP
php实现面包屑导航例子分享
2015/12/19 PHP
PHP实现接收二进制流转换成图片的方法
2017/01/10 PHP
PDO::lastInsertId讲解
2019/01/29 PHP
Js中sort()方法的用法
2006/11/04 Javascript
jQuery 常见操作实现方式和常用函数方法总结
2011/05/06 Javascript
全面兼容的javascript时间格式化函数(比较实用)
2014/05/14 Javascript
深入理解JavaScript程序中内存泄漏
2016/03/17 Javascript
原生js获取iframe中dom元素--父子页面相互获取对方dom元素的方法
2016/08/05 Javascript
jQuery插件echarts实现的循环生成图效果示例【附demo源码下载】
2017/03/04 Javascript
微信小程序 图片加载(本地,网路)实例详解
2017/03/10 Javascript
HTML5+Canvas调用手机拍照功能实现图片上传(上)
2017/04/21 Javascript
webstorm+vue初始化项目的方法
2018/10/18 Javascript
vue 解决form表单提交但不跳转页面的问题
2019/10/30 Javascript
javascript实现移动端轮播图
2020/12/09 Javascript
Python使用代理抓取网站图片(多线程)
2014/03/14 Python
python元组操作实例解析
2014/09/23 Python
浅谈scrapy 的基本命令介绍
2017/06/13 Python
python通过opencv实现批量剪切图片
2017/11/13 Python
对pandas进行数据预处理的实例讲解
2018/04/20 Python
使用Python 自动生成 Word 文档的教程
2020/02/13 Python
Python数据正态性检验实现过程
2020/04/18 Python
英国门销售网站:Green Tree Doors
2020/01/07 全球购物
思想政治教育专业个人求职信范文
2013/12/20 职场文书
市场开发计划书
2014/05/07 职场文书
项目建议书怎么写
2014/05/15 职场文书
项目经理任命书
2014/06/04 职场文书
田径运动会通讯稿
2014/09/13 职场文书
学习朴航瑛老师爱岗敬业先进事迹思想汇报
2014/09/17 职场文书
学校会议通知范文
2015/04/15 职场文书
想要创业,那么你做好准备了吗?
2019/07/01 职场文书
MySql重置root密码 --skip-grant-tables
2022/04/11 MySQL