【亚洲必赢官网】ci框架做的,完美应用Yii2微信后台开发的成千成万总括

/**
     * 组合微信app支付  得到prepayid
     * @param int $order_num
     */
    private function _wxpay_request($order_num = 0)
    {
        
        //判断订单号码必须是数组并且不为0
        check_order_num($order_num);

/**
     * 组合微信app支付  获得prepayid
     * @param int $order_num
     */
    private function _wxpay_request($order_num = 0)
    {
        
        //判断订单号码必须是数组并且不为0
        check_order_num($order_num);

不赘述直接上代码

网上有好多有关YII2.0微信支付教程,可是太过复杂凌乱,所未来天在那边给我们整理计算运用Yii2微信后台开发的千家万户了,给急需的伴儿们参考。

        //引入微信支付类    
        libraries_include(“wxpay/”, “WxPayHelper.app.php”);
        
        //支付接口发起url
        $pay_url = $this->config->item(“PAY_URL”);
        
        //通知地址
        $notify_url =
$this->config->item(“WEIXIN_NOTIFY_URL”);
        
        
        //微信配置
        $pay_config = $this->config->item(“WEIXIN_PAY_NEED”);

        //引入微信支付类    
        libraries_include(“wxpay/”, “WxPayHelper.app.php”);
        
        //支付接口发起url
        $pay_url = $this->config->item(“PAY_URL”);
        
        //通告地址
        $notify_url =
$this->config->item(“WEIXIN_NOTIFY_URL”);
        
        
        //微信配置
        $pay_config = $this->config->item(“WEIXIN_PAY_NEED”);

先来微信SDK

一:接入微信

        
        $helper = new WxPayHelper();
        //随机字符串
        $nonce_str = $helper->getRandChar(32);

        
        $helper = new WxPayHelper();
        //随机字符串
        $nonce_str = $helper->getRandChar(32);

class WeixinPay{ protected $appid =””; //小程序APPID protected $mch_id =””; //商家号 protected $Key = “”; //商家秘钥 protected $openid; //用户openid protected $out_trade_no; //商家编号 protected $body; //商品详情 protected $total_fee; //金额 protected $orderBuy; //商户号 function __亚洲必赢官网,construct( $openid=””,$body=””,$total_fee=””,$orderBuy=””) { $this->openid =$openid; $this->body = $body; $this->total_fee =$total_fee; $this->orderBuy = $orderBuy; } public function pay(){ $return = $this->weixinapp(); return $return; } //统一下单接口 private function unifiedorder() { $url = ”; $parameters = array( ‘appid’ => $this->appid, //小程序ID ‘mch_id’ => $this->mch_id, //商户号 ‘nonce_str’ => $this->createNoncestr(), //随机字符串 //’sign_type’=>”MD5″, //商品描述 ‘body’ => $this->body, //商家订单号 ‘out_trade_no’=> $this->mch_id.time(), //总金额 单位 分 ‘total_fee’ =>$this->total_fee, ‘spbill_create_ip’ => $_SERVER[‘REMOTE_ADDR’], //终端IP ‘notify_url’ => ”, //公告地址 确定保证外网能平常访问 // ‘spbill_create_ip’ => ‘192.168.0.161’, //终端IP //’notify_url’ => ”, ‘trade_type’ => ‘JSAPI’,//交易类型 ‘openid’ => $this->openid, //用户id ); //统一下单签名 $parameters[‘sign’] = $this->getSign($parameters); $xmlData = $this->arrayToXml($parameters); $return = $this->xmlToArray($this->postXmlCurl($xmlData, $url)); return $return; } private static function postXmlCurl($xml, $url) { $ch = curl_init(); $this_header = array( “content-type: application/x-www-form-urlencoded;charset=UTF-8” ); //设置超时 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VE酷路泽IFYHOST, FALSE); //严酷校验 //设置header curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header); //供给结果为字符串且输出到荧屏上 curl_setopt($ch, CURLOPT_RETUMuranoNTRANSFE智跑, 1); //post提交格局 curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt($ch, CURLOPT_TIMEOUT, 40); set_time_limit(0); //运行curl $data = curl_exec($ch); //重临结果 if ($data) { curl_close($ch); return $data; } else { $error = curl_errno($ch); curl_close($ch); throw new WxPayException(“curl出错,错误码:$error”); } } //数组转换来xml protected function arrayToXml($arr){ ksort($arr); $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; } //xml转换来数组 private function xmlToArray($xml) { //禁止引用外部xml实体 libxml_disable_entity_loader(true); $xmlstring = simplexml_load_string($xml, ‘SimpleXMLElement’, LIBXML_NOCDATA); $val = json_decode(json_encode($xmlstring), true); return $val; } //微信小程序接口 private function weixinapp() { //统一下单接口 $unifiedorder = $this->unifiedorder(); if(isset($unifiedorder[‘prepay_id’])){ $parameters = array( ‘appId’ => $this->appid, //小程序ID ‘timeStamp’ => ” . time() . ”, //时间戳 ‘nonceStr’ => $this->createNoncestr(), //随机串 ‘package’ => ‘prepay_id=’ . $unifiedorder[‘prepay_id’], //数据包 ‘signType’ => ‘MD5’//签有名的模特式 ); //签名 $parameters[‘paySign’] = $this->getSign($parameters); return $parameters; }else{ return $unifiedorder; } } //作用:发生随机字符串,非常短于叁13位 private function createNoncestr($length = 32) { $chars = “abcdefghijklmnopqrstuvwxyz0123456789”; $str = “”; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) – 1), 1); } return $str; } //生成签名 public function getSign($Obj) { foreach ($Obj as $k => $v) { $Parameters[$k] = $v; } //签名步骤一:按字典序排序参数 ksort($Parameters); $String = $this->formatBizQueryParaMap($Parameters, false); //签名步骤二:在string后参预KEY $String = $String . “&key=” . $this->Key; //签名步骤三:MD5加密 $String = MD5($String); //签名步骤四:全体字符转为大写 $result_ = strtoupper($String); return $result_; } //格式化参数,签名进度须求动用 private function formatBizQueryParaMap($paraMap, $urlencode) { $buff = “”; ksort($paraMap); foreach ($paraMap as $k => $v) { if ($urlencode) { $v = urlencode($v); } $buff .= $k . “=” . $v . “&”; } $reqPar =””; if (strlen($buff) > 0) { $reqPar = substr($buff, 0, strlen($buff) – 1); } return $reqPar; }}

回调地址

 

Yii2后台配置

        
        //获得订单数量
        $order_data =
$this->order_model->get_one($order_num);
        
        $data[“appid”]           =
$pay_config[‘appid’];//微信开放平台审核通过的应用APPID
        $data[“body”]           =
$pay_config[‘body’];//商品或开发单简要描述
        $data[“mch_id”]       = $pay_config[‘mch_id’];//商户号
        $data[“nonce_str”]       = $nonce_str;//随机字符串
        $data[“notify_url”]   = $notify_url;//通告地址
        $data[“out_trade_no”] =
$order_data[“order_num”];//商行订单号
        $data[“spbill_create_ip”] =
$helper->get_client_ip();//终端IP
        $data[“total_fee”]        = $order_data[‘total’] *
100;//总金额
        $data[“trade_type”]         = “APP”;//交易类型
        $data[“sign”]               = $helper->getSign($data,
$pay_config[‘partner’]);//签名

        
        //得到订单数量
        $order_data =
$this->order_model->get_one($order_num);
        
        $data[“appid”]           =
$pay_config[‘appid’];//微信开放平台审核通过的应用APPID
        $data[“body”]           =
$pay_config[‘body’];//商品或开发单简要描述
        $data[“mch_id”]       = $pay_config[‘mch_id’];//商户号
        $data[“nonce_str”]       = $nonce_str;//随机字符串
        $data[“notify_url”]   = $notify_url;//通告地址
        $data[“out_trade_no”] =
$order_data[“order_num”];//商家订单号
        $data[“spbill_create_ip”] =
$helper->get_client_ip();//终端IP
        $data[“total_fee”]        = $order_data[‘total’] *
100;//总金额
        $data[“trade_type”]         = “APP”;//交易类型
        $data[“sign”]               = $helper->getSign($data,
$pay_config[‘partner’]);//签名

$postXml = file_get_contents(“php://input”); // if($postXml){ $attr = $this->xmlToArray($postXml); if($attr[‘return_code’] ==”SUCCESS”){ $total_fee = $attr[‘total_fee’]; $open_id = $attr[‘openid’]; $out_trade_no = $attr[‘out_trade_no’]; $time = $attr[‘time_end’]; $transaction_id = $attr[‘transaction_id’];

1.在app/config/params.php中配置token参数

        $xml         = $helper->arrayToXml($data);

        $xml         = $helper->arrayToXml($data);

对数据库得写入即可 }

 

return [
 //微信接入
 'wechat' =>[
 'token' => 'your token',
 ],
];

        $response     = $helper->postXmlCurl($xml, $pay_url);

        $response     = $helper->postXmlCurl($xml, $pay_url);

2.在app/config/main.php中配备路由

        
        //将微信重回的结果xml转成数组
        $responseArr = $helper->xmlToArray($response);
        if(isset($responseArr[“return_code”]) &&
$responseArr[“return_code”]==’SUCCESS’ &&
isset($responseArr[‘result_code’]) &&
$responseArr[【亚洲必赢官网】ci框架做的,完美应用Yii2微信后台开发的成千成万总括。”result_code”]==’SUCCESS’){
           
            
            $data_pay[“appid”]         = $pay_config[‘appid’];
            $data_pay[“noncestr”]     = $nonce_str;
            $data_pay[“package”]     = “Sign=WXPay”;
            $data_pay[“partnerid”]     = $pay_config[‘mch_id’];
            $data_pay[“prepayid”]     =
$responseArr[‘prepay_id’];
            $data_pay[“timestamp”]     = time();
            $data_pay[“sign”]         =
$helper->getSign($data_pay, $pay_config[‘partner’]);//一遍签订契约
            
            
            $this->response = array(‘status’=>0,
‘msg’=>’success’, ‘data’=>$data_pay);
        }else{
        
            $return_msg = $responseArr[‘err_code_des’];    
             $this->response = array(‘status’=>0,
‘msg’=>$return_msg, ‘data’=>$responseArr);
        }
      
        
        
               
    }

        
        //将微信再次来到的结果xml转成数组
        $responseArr = $helper->xmlToArray($response);
        if(isset($responseArr[“return_code”]) &&
$responseArr[“return_code”]==’SUCCESS’ &&
isset($responseArr[‘result_code’]) &&
$responseArr[“result_code”]==’SUCCESS’){
           
            
            $data_pay[“appid”]         = $pay_config[‘appid’];
            $data_pay[“noncestr”]     = $nonce_str;
            $data_pay[“package”]     = “Sign=WXPay”;
            $data_pay[“partnerid”]     = $pay_config[‘mch_id’];
            $data_pay[“prepayid”]     =
$responseArr[‘prepay_id’];
            $data_pay[“timestamp”]     = time();
            $data_pay[“sign”]         =
$helper->getSign($data_pay, $pay_config[‘partner’]);//贰次签订契约
            
            
            $this->response = array(‘status’=>0,
‘msg’=>’success’, ‘data’=>$data_pay);
        }else{
        
            $return_msg = $responseArr[‘err_code_des’];    
             $this->response = array(‘status’=>0,
‘msg’=>$return_msg, ‘data’=>$responseArr);
        }
      
        
        
               
    }

因为接口模块使用的RESTful API,所以须要定义路由规则。

//helper.php

//helper.php

'urlManager' => [
 'enablePrettyUrl' => true,
 'enableStrictParsing' => true,
 'showScriptName' => false,
 'rules' => [
 [
  'class' => 'yii\rest\UrlRule',
  'controller' => 'wechat',
  'extraPatterns' => [
  'GET valid' => 'valid',
  ],
 ],
 ],
],

<?php

<?php

3.在app/controllers中新建WechatController

class WxPayHelper{
    
    /**
     * 验证签名
     * @param array $data
     * @param string $key
     * @return string
     */
    function getVerifySign($data, $key)
    {
        $String = $this->formatParameters($data, false);
        //签名步骤二:在string后加盟KEY
        $String = $String . “&key=” . $key;
        //签名步骤三:MD5加密
        $String = md5($String);
        //签名步骤四:全体字符转为大写
        $result = strtoupper($String);
        return $result;
    }
    
    function formatParameters($paraMap, $urlencode)
    {
        $buff = “”;
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if($k==”sign”){
                continue;
            }
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . “=” . $v . “&”;
        }
        $reqPar;
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) – 1);
        }
        return $reqPar;
    }
    
    /**
     * 获得签名
     * @param object $obj
     * @param string $api_key
     * @return string
     */
    function getSign($obj, $api_key)
    {
        foreach ($obj as $k => $v)
        {
            $Parameters[strtolower($k)] = $v;
        }
        //签名步骤一:按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二:在string后进入KEY
        $String = $String.”&key=”.$api_key;
        //签名步骤三:MD5加密
        $result = strtoupper(md5($String));
        return $result;
    }

class WxPayHelper{
    
    /**
     * 验证签名
     * @param array $data
     * @param string $key
     * @return string
     */
    function getVerifySign($data, $key)
    {
        $String = $this->formatParameters($data, false);
        //签名步骤二:在string后投入KEY
        $String = $String . “&key=” . $key;
        //签名步骤三:MD5加密
        $String = md5($String);
        //签名步骤四:全数字符转为大写
        $result = strtoupper($String);
        return $result;
    }
    
    function formatParameters($paraMap, $urlencode)
    {
        $buff = “”;
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if($k==”sign”){
                continue;
            }
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . “=” . $v . “&”;
        }
        $reqPar;
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) – 1);
        }
        return $reqPar;
    }
    
    /**
     * 获得签名
     * @param object $obj
     * @param string $api_key
     * @return string
     */
    function getSign($obj, $api_key)
    {
        foreach ($obj as $k => $v)
        {
            $Parameters[strtolower($k)] = $v;
        }
        //签名步骤一:按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二:在string后进入KEY
        $String = $String.”&key=”.$api_key;
        //签名步骤三:MD5加密
        $result = strtoupper(md5($String));
        return $result;
    }

<?php

namespace api\controllers;

use Yii;
use yii\rest\ActiveController;

class WechatController extends ActiveController
{

 public $modelClass = '';

 public function actionValid()
 {
 $echoStr = $_GET["echostr"];
 $signature = $_GET["signature"];
 $timestamp = $_GET["timestamp"];
 $nonce = $_GET["nonce"];
 //valid signature , option
 if($this->checkSignature($signature,$timestamp,$nonce)){
  echo $echoStr;
 }
 }

 private function checkSignature($signature,$timestamp,$nonce)
 {
 // you must define TOKEN by yourself
 $token = Yii::$app->params['wechat']['token'];
 if (!$token) {
  echo 'TOKEN is not defined!';
 } else {
  $tmpArr = array($token, $timestamp, $nonce);
  // use SORT_STRING rule
  sort($tmpArr, SORT_STRING);
  $tmpStr = implode( $tmpArr );
  $tmpStr = sha1( $tmpStr );

  if( $tmpStr == $signature ){
  return true;
  }else{
  return false;
  }
 }
 }

}

    /**
     * 获取内定长度的妄动字符串
     * @param int $length
     * @return Ambigous <NULL, string>
     */
    function getRandChar($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;
    }

    /**
     * 获取钦赐长度的自由字符串
     * @param int $length
     * @return Ambigous <NULL, string>
     */
    function getRandChar($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;
    }

微信公众号后台配置

    /**
     * 数组转xml
     * @param array $arr
     * @return string
     */
    function arrayToXml($arr)
    {

    /**
     * 数组转xml
     * @param array $arr
     * @return string
     */
    function arrayToXml($arr)
    {

在微信公众号后台配置U索罗德L和Token,然后交由认证即可。

        header(“Content-type: text/xml”);            
        
        $xml = ‘<xml>’;    
    
        foreach ($arr as $key=>$val)
        {
             if (is_numeric($val))
             {
                $xml.=”<“.$key.”>”.$val.”</”.$key.”>”;

        header(“Content-type: text/xml”);            
        
        $xml = ‘<xml>’;    
    
        foreach ($arr as $key=>$val)
        {
             if (is_numeric($val))
             {
                $xml.=”<“.$key.”>”.$val.”</”.$key.”>”;

URL:http://app.demo.com/wechats/valid
Token:your token

             }
             else
               
$xml.=”<“.$key.”><![CDATA[“.$val.”]]></”.$key.”>”;
 
        }
        $xml.= ‘</xml>’;
        return $xml;
    }
    
    /**
     * 以post方式提交xml到对应的接口url
     *
     * @param string $xml  需要post的xml数据
     * @param string $url  url
     * @param bool $useCert 是不是必要注明,暗中同意不供给
     * @param int $second   url执行超时时间,暗中认可30s
     * @throws WxPayException
     */
    function postXmlCurl($xml, $url, $second=30, $useCert=false,
$sslcert_path=”, $sslkey_path=”)
    {

             }
             else
               
$xml.=”<“.$key.”><![CDATA[“.$val.”]]></”.$key.”>”;
 
        }
        $xml.= ‘</xml>’;
        return $xml;
    }
    
    /**
     * 以post情势提交xml到相应的接口url
     *
     * @param string $xml  需要post的xml数据
     * @param string $url  url
     * @param bool $useCert 是或不是供给申明,私下认可不要求
     * @param int $second   url执行超时时间,暗中认可30s
     * @throws WxPayException
     */
    function postXmlCurl($xml, $url, $second=30, $useCert=false,
$sslcert_path=”, $sslkey_path=”)
    {

二:获取用户新闻

        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch,CURLOPT_URL, $url);

        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch,CURLOPT_URL, $url);

用户表设计

        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //供给结果为字符串且输出到荧屏上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
    
        if($useCert == true){
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
            curl_setopt($ch,CURLOPT_SSL_VE科雷傲IFYHOST,2);//严谨校验
            //设置证书
            //使用证书:cert 与 key 分别属于多个.pem文件
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,’PEM’);
            curl_setopt($ch,CURLOPT_SSLCERT, $sslcert_path);
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,’PEM’);
            curl_setopt($ch,CURLOPT_SSLKEY, $sslkey_path);
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        
        //再次回到结果
        if($data){
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
    
            curl_close($ch);
            return false;
        }
    }
    
    /**
     * 获取当前服务器的IP
     * @return Ambigous <string, unknown>
     */
    function get_client_ip()
    {
        if (isset($_SERVER[‘REMOTE_ADDR’])) {
            $cip = $_SERVER[‘REMOTE_ADDR’];
        } elseif (getenv(“REMOTE_ADDR”)) {
            $cip = getenv(“REMOTE_ADDR”);
        } elseif (getenv(“HTTP_CLIENT_IP”)) {
            $cip = getenv(“HTTP_CLIENT_IP”);
        } else {
            $cip = “127.0.0.1”;
        }
        return $cip;
    }
 
    /**
     * 将数组转成uri字符串
     * @param array $paraMap
     * @param bool $urlencode
     * @return string
     */
    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = “”;
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
               $v = urlencode($v);
            }
            $buff .= strtolower($k) . “=” . $v . “&”;
        }
        $reqPar;
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }
    
    /**
     * XML转数组
     * @param unknown $xml
     * @return mixed
     */
    function xmlToArray($xml)
    {
        //将XML转为array
        $array_data =
json_decode(json_encode(simplexml_load_string($xml,
‘SimpleXMLElement’, LIBXML_NOCDATA)), true);
        return $array_data;
    }
    
}
    
    
?>

        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //供给结果为字符串且输出到显示屏上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
    
        if($useCert == true){
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
            curl_setopt($ch,CURLOPT_SSL_VEPRADOIFYHOST,2);//严酷校验
            //设置证书
            //使用证书:cert 与 key 分别属于多个.pem文件
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,’PEM’);
            curl_setopt($ch,CURLOPT_SSLCERT, $sslcert_path);
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,’PEM’);
            curl_setopt($ch,CURLOPT_SSLKEY, $sslkey_path);
        }
        //post提交格局
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        
        //再次回到结果
        if($data){
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
    
            curl_close($ch);
            return false;
        }
    }
    
    /**
     * 获取当前服务器的IP
     * @return Ambigous <string, unknown>
     */
    function get_client_ip()
    {
        if (isset($_SERVER[‘REMOTE_ADDR’])) {
            $cip = $_SERVER[‘REMOTE_ADDR’];
        } elseif (getenv(“REMOTE_ADDR”)) {
            $cip = getenv(“REMOTE_ADDR”);
        } elseif (getenv(“HTTP_CLIENT_IP”)) {
            $cip = getenv(“HTTP_CLIENT_IP”);
        } else {
            $cip = “127.0.0.1”;
        }
        return $cip;
    }
 
    /**
     * 将数组转成uri字符串
     * @param array $paraMap
     * @param bool $urlencode
     * @return string
     */
    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = “”;
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
               $v = urlencode($v);
            }
            $buff .= strtolower($k) . “=” . $v . “&”;
        }
        $reqPar;
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }
    
    /**
     * XML转数组
     * @param unknown $xml
     * @return mixed
     */
    function xmlToArray($xml)
    {
        //将XML转为array
        $array_data =
json_decode(json_encode(simplexml_load_string($xml,
‘SimpleXMLElement’, LIBXML_NOCDATA)), true);
        return $array_data;
    }
    
}
    
    
?>

复制代码 代码如下:

 

 

CREATE TABLE `wechat_user` (
  `id` int(11) NOT NULL,
  `openid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `nickname` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT
‘微信昵称’,
  `sex` tinyint(4) NOT NULL COMMENT ‘性别’,
  `headimgurl` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT
‘头像’,
  `country` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT
‘国家’,
  `province` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT
‘省份’,
  `city` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT
‘城市’,
  `access_token` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `refresh_token` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
COLLATE=utf8_unicode_ci;
ALTER TABLE `wechat_user`
  ADD PRIMARY KEY (`id`);

//异步公告

//异步布告

获得用户音讯的连锁接口

/**
     * 微信消息地址
     */
    public function weixin_notify()
    {
        
        
        libraries_include(“wxpay/”, “WxPayHelper.app.php”);
        $helper = new WxPayHelper();        
        //微信配置
        $pay_config = $this->config->item(“WEIXIN_PAY_NEED”);  
 
       

/**
     * 微信音信地址
     */
    public function weixin_notify()
    {
        
        
        libraries_include(“wxpay/”, “WxPayHelper.app.php”);
        $helper = new WxPayHelper();        
        //微信配置
        $pay_config = $this->config->item(“WEIXIN_PAY_NEED”);  
 
       

1.用户授权接口:获取access_token、openId等;获取并保存用户资料到数据库

        $xml = file_get_contents(“php://input”);
       
        if(!$xml){
          
 exit(‘<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>’);
        }
       
        $wx_back = $helper->xmlToArray($xml);
        
    
        if(empty($wx_back)){
          
 exit(‘<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>’);
        }
        $checkSign = $helper->getVerifySign($wx_back,
$pay_config[‘partner’]);
        
        //验证签名        
        if($checkSign==$wx_back[‘sign’]){
            
            if (isset($wx_back[‘result_code’]) &&
$wx_back[‘result_code’]==’SUCCESS’) {
                $requestReturnData =
file_get_contents(“php://input”);
                //商家订单号
                $out_trade_no = $wx_back[‘out_trade_no’];

        $xml = file_get_contents(“php://input”);
       
        if(!$xml){
          
 exit(‘<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>’);
        }
       
        $wx_back = $helper->xmlToArray($xml);
        
    
        if(empty($wx_back)){
          
 exit(‘<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>’);
        }
        $checkSign = $helper->getVerifySign($wx_back,
$pay_config[‘partner’]);
        
        //验证签名        
        if($checkSign==$wx_back[‘sign’]){
            
            if (isset($wx_back[‘result_code’]) &&
$wx_back[‘result_code’]==’SUCCESS’) {
                $requestReturnData =
file_get_contents(“php://input”);
                //商行订单号
                $out_trade_no = $wx_back[‘out_trade_no’];

复制代码 代码如下:

              
                
                //第二方订单号码
                $third_order_num = $wx_back[“transaction_id”];
                
                //交易情状
                $trade_status = $wx_back[‘result_code’];
                
                //订单金额 保留小数点后两位
                $total_fee = sprintf(“%.2f”,
$wx_back[‘total_fee’]/100);

              
                
                //第3方订单号码
                $third_order_num = $wx_back[“transaction_id”];
                
                //交易处境
                $trade_status = $wx_back[‘result_code’];
                
                //订单金额 保留小数点后两位
                $total_fee = sprintf(“%.2f”,
$wx_back[‘total_fee’]/100);

public function actionAccesstoken()
{
    $code = $_GET[“code”];
    $state = $_GET[“state”];
    $appid = Yii::$app->params[‘wechat’][‘appid’];
    $appsecret = Yii::$app->params[‘wechat’][‘appsecret’];
    $request_url =
”;
    //起首化1个curl会话
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $request_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    $result = $this->response($result);
    //获取token和openid成功,数据解析
    $access_token = $result[‘access_token’];
    $refresh_token = $result[‘refresh_token’];
    $openid = $result[‘openid’];
    //请求微信接口,获取用户音信
    $userInfo = $this->getUserInfo($access_token,$openid);
    $user_check =
WechatUser::find()->where([‘openid’=>$openid])->one();
    if ($user_check) {
        //更新用户资料
    } else {
        //保存用户资料
    }
    //前端网页的重定向
    if ($openid) {
        return $this->redirect($state.$openid);
    } else {
        return $this->redirect($state);
    }
}

               //公司业务处理

               //公司业务处理

2.从微信获取用户资料

 

 

复制代码 代码如下:

                //处理后一只再次来到给微信
              
 exit(‘<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>’);
            }
            
            
        }
       
exit(‘<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>’);
        

                //处理后联手重返给微信
              
 exit(‘<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>’);
            }
            
            
        }
       
exit(‘<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>’);
        

public function getUserInfo($access_token,$openid)
{
    $request_url =
”;
    //发轫化3个curl会话
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $request_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    $result = $this->response($result);
    return $result;
}

    }

    }

3.赢得用户资料接口

 

 

public function actionUserinfo()
{
 if(isset($_REQUEST["openid"])){
  $openid = $_REQUEST["openid"];
  $user = WechatUser::find()->where(['openid'=>$openid])->one();
  if ($user) {
   $result['error'] = 0;
   $result['msg'] = '获取成功';
   $result['user'] = $user;
  } else {
   $result['error'] = 1;
   $result['msg'] = '没有该用户';
  }
 } else {
  $result['error'] = 1;
  $result['msg'] = 'openid为空';
 }
 return $result;
}

 

三:微信支付

1.微信付出接口:打包支付多少

复制代码 代码如下:

public function actionPay(){
   
if(isset($_REQUEST[“uid”])&&isset($_REQUEST[“oid”])&&isset($_REQUEST[“totalFee”])){
        //uid、oid、totalFee
        $uid = $_REQUEST[“uid”];
        $oid = $_REQUEST[“oid”];
        $totalFee = $_REQUEST[“totalFee”];
        $timestamp = time();
        //微信支付参数
        $appid = Yii::$app->params[‘wechat’][‘appid’];
        $mchid = Yii::$app->params[‘wechat’][‘mchid’];
        $key = Yii::$app->params[‘wechat’][‘key’];
        $notifyUrl = Yii::$app->params[‘wechat’][‘notifyUrl’];
        //支付打包
        $wx_pay = new WechatPay($mchid, $appid, $key);
        $package = $wx_pay->createJsBizPackage($uid, $totalFee,
$oid, $notifyUrl, $timestamp);
        $result[‘error’] = 0;
        $result[‘msg’] = ‘支付打包成功’;
        $result[‘package’] = $package;
        return $result;
    }else{
        $result[‘error’] = 1;
        $result[‘msg’] = ‘请求参数错误’;
    }
    return $result;
}

2.收受微信发送的异步支付结果通报

复制代码 代码如下:

public function actionNotify(){
    $postStr = $GLOBALS[“HTTP_RAW_POST_DATA”];
    $postObj = simplexml_load_string($postStr, ‘SimpleXMLElement’,
LIBXML_NOCDATA);
    //
    if ($postObj === false) {
        die(‘parse xml error’);
    }
    if ($postObj->return_code != ‘SUCCESS’) {
        die($postObj->return_msg);
    }
    if ($postObj->result_code != ‘SUCCESS’) {
        die($postObj->err_code);
    }
    //微信支付参数
    $appid = Yii::$app->params[‘wechat’][‘appid’];
    $mchid = Yii::$app->params[‘wechat’][‘mchid’];
    $key = Yii::$app->params[‘wechat’][‘key’];
    $wx_pay = new WechatPay($mchid, $appid, $key);
    //验证签名
    $arr = (array)$postObj;
    unset($arr[‘sign’]);
    if ($wx_pay->getSign($arr, $key) != $postObj->sign) {
        die(“签名错误”);
    }
    //支付处理正确-判断是还是不是已处理过支付处境
    $orders = Order::find()->where([‘uid’=>$postObj->openid,
‘oid’=>$postObj->out_trade_no, ‘status’ => 0])->all();
    if(count($orders) > 0){
        //更新订单状态
        foreach ($orders as $order) {
            //更新订单
            $order[‘status’] = 1;
            $order->update();
        }
        return
‘<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>’;
    } else {
        //订单状态已履新,间接再次回到
        return
‘<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>’;
    }
}

3.微信支付类 WechatPay.php

复制代码 代码如下:

<?php
namespace api\sdk;
use Yii;
class WechatPay
{
    protected $mchid;
    protected $appid;
    protected $key;
    public function __construct($mchid, $appid, $key){
        $this->mchid = $mchid;
        $this->appid = $appid;
        $this->key = $key;
    }
    public function createJsBizPackage($openid, $totalFee, $outTradeNo,
$orderName, $notifyUrl, $timestamp){
        $config = array(
            ‘mch_id’ => $this->mchid,
            ‘appid’ => $this->appid,
            ‘key’ => $this->key,
        );
        $unified = array(
            ‘appid’ => $config[‘appid’],
            ‘attach’ => ‘支付’,
            ‘body’ => $orderName,
            ‘mch_id’ => $config[‘mch_id’],
            ‘nonce_str’ => self::createNonceStr(),
            ‘notify_url’ => $notifyUrl,
            ‘openid’ => $openid,
            ‘out_trade_no’ => $outTradeNo,
            ‘spbill_create_ip’ => ‘127.0.0.1’,
            ‘total_fee’ => intval($totalFee * 100),
            ‘trade_type’ => ‘JSAPI’,
        );
        $unified[‘sign’] = self::getSign($unified,
$config[‘key’]);
        $responseXml =
self::curlPost(”,
self::arrayToXml($unified));
        $unifiedOrder = simplexml_load_string($responseXml,
‘SimpleXMLElement’, LIBXML_NOCDATA);
        if ($unifiedOrder === false) {
            die(‘parse xml error’);
        }
        if ($unifiedOrder->return_code != ‘SUCCESS’) {
            die($unifiedOrder->return_msg);
        }
        if ($unifiedOrder->result_code != ‘SUCCESS’) {
            die($unifiedOrder->err_code);
        }
        $arr = array(
            “appId” => $config[‘appid’],
            “timeStamp” => $timestamp,
            “nonceStr” => self::createNonceStr(),
            “package” => “prepay_id=” .
$unifiedOrder->prepay_id,
            “signType” => ‘MD5’,
        );
        $arr[‘paySign’] = self::getSign($arr, $config[‘key’]);
        return $arr;
    }
    public static function curlGet($url = ”, $options = array()){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不表明证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public static function curlPost($url = ”, $postData = ”, $options
= array()){
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//设置cU本田CR-VL允许实施的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不表达证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public static function createNonceStr($length = 16){
        $chars =
‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789’;
        $str = ”;
        for ($i = 0; $i<$length; $i++){
            $str .= substr($chars, mt_rand(0, strlen($chars) – 1),
1);
        }
        return $str;
    }
    public static function arrayToXml($arr){
        $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;
    }
    public static function getSign($params, $key){
        ksort($params, SORT_STRING);
        $unSignParaString = self::formatQueryParaMap($params, false);
        $signStr = strtoupper(md5($unSignParaString . “&key=” .
$key));
        return $signStr;
    }
    protected static function formatQueryParaMap($paraMap, $urlEncode =
false){
        $buff = “”;
        ksort($paraMap);
        foreach ($paraMap as $k => $v){
            if (null != $v && “null” != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . “=” . $v . “&”;
            }
        }
        $reqPar = ”;
        if (strlen($buff)>0) {
            $reqPar = substr($buff, 0, strlen($buff) – 1);
        }
        return $reqPar;
    }
}

四:获取JS-SDK的config参数

据悉微信公众平台开发者文书档案:

具有供给动用JS-SDK的页面必须先注入配置音讯,不然将无法调用(同2个url仅需调用1次,对于变化url的SPA的web
app可在每回url变化时展开调用,近年来Android微信客户端不帮忙pushState的H5新特点,所以选用pushState来贯彻web
app的页面会促成签名退步,此难点会在Android6.第22中学期维修复)。

即:

复制代码 代码如下:

wx.config({
    debug: true, //
开启调节和测试格局,调用的持有api的回来值会在客户端alert出来,若要查看传入的参数,能够在pc端打开,参数新闻会通过log打出,仅在pc端时才会打字与印刷。
    appId: ”, // 必填,公众号的绝无仅有标识
    timestamp: , // 必填,生成签名的年华戳
    nonceStr: ”, // 必填,生成签名的妄动串
    signature: ”,// 必填,签名,见附录1
    jsApiList: [] //
必填,须求运用的JS接口列表,全部JS接口列表见附录2
});

1.微信支付类 WechatPay.php

复制代码 代码如下:

<?php
namespace api\sdk;
use Yii;
class WechatPay
{
    public function getSignPackage($url) {
        $jsapiTicket = self::getJsApiTicket();
        $timestamp = time();
        $nonceStr = self::createNonceStr();
        // 那里参数的逐一要依照 key 值 ASCII 码升序排序
        $string =
“jsapi_ticket=”.$jsapiTicket.”&noncestr=”.$nonceStr.”&timestamp=”.$timestamp.”&url=”.$url;
        $signature = sha1($string);
        $signPackage = array(
            “appId”     => $this->appid,
            “nonceStr”  => $nonceStr,
            “timestamp” => $timestamp,
            “url”       => $url,
            “signature” => $signature,
            “rawString” => $string
        );
        return $signPackage;
    }
    public static function getJsApiTicket() {
        //使用Redis缓存 jsapi_ticket
        $redis = Yii::$app->redis;
        $redis_ticket = $redis->get(‘wechat:jsapi_ticket’);
        if ($redis_ticket) {
            $ticket = $redis_ticket;
        } else {
            $accessToken = self::getAccessToken();
            $url =
“;
            $res = json_decode(self::curlGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $redis->set(‘wechat:jsapi_ticket’, $ticket);
                $redis->expire(‘wechat:jsapi_ticket’, 7000);
            }
        }
        return $ticket;
    }
    public static function getAccessToken() {
        //使用Redis缓存 access_token
        $redis = Yii::$app->redis;
        $redis_token = $redis->get(‘wechat:access_token’);
        if ($redis_token) {
            $access_token = $redis_token;
        } else {
            $appid = Yii::$app->params[‘wechat’][‘appid’];
            $appsecret =
Yii::$app->params[‘wechat’][‘appsecret’];
            $url =
“;
            $res = json_decode(self::curlGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $redis->set(‘wechat:access_token’,
$access_token);
                $redis->expire(‘wechat:access_token’, 7000);
            }
        }
        return $access_token;
    }
    public static function curlGet($url = ”, $options = array()){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不表明证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public static function curlPost($url = ”, $postData = ”, $options
= array()){
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//设置cUHighlanderL允许实施的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不表明证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public static function createNonceStr($length = 16){
        $chars =
‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789’;
        $str = ”;
        for ($i = 0; $i<$length; $i++){
            $str .= substr($chars, mt_rand(0, strlen($chars) – 1),
1);
        }
        return $str;
    }
}

2.到手config参数接口

public function actionConfig(){
 if (isset($_REQUEST['url'])) {
 $url = $_REQUEST['url'];
 //微信支付参数
 $appid = Yii::$app->params['wechat']['appid'];
 $mchid = Yii::$app->params['wechat']['mchid'];
 $key = Yii::$app->params['wechat']['key'];
 $wx_pay = new WechatPay($mchid, $appid, $key);
 $package = $wx_pay->getSignPackage($url);
 $result['error'] = 0;
 $result['msg'] = '获取成功';
 $result['config'] = $package;
 } else {
 $result['error'] = 1;
 $result['msg'] = '参数错误';
 }
 return $result;
}

上述即是使用Yii2微信后台开发总体经过及示范代码,希望本文对大家基于php的微信公众平台支付具有扶助。

您大概感兴趣的文章:

  • Yii2
    RESTful中api的应用及开发实例详解
  • Yii2中装置与收获别名的函数(set阿里as和getAlias)用法分析
  • Yii第22中学YiiBase自动加载类、引用文件措施分析(autoload)
  • Yii2成立控制器(createController)方法详解
  • Yii2核心(Theme)用法详解
  • Yii2创立表单(ActiveForm)方法详解
  • Yii2验证器(Validator)用法分析
  • yii2
    RBAC使用DbManager完成后台权限判断的点子
  • Yii2简单达成多语言配置的法门
  • yii2控制器Controller
    Ajax操作示例
  • Yii第22中学Restful
    API原理实例分析
网站地图xml地图