左右逢源应用Yii2微信后台开发的层层计算,支付宝地铁SDK使用失利记录

动用PHP版的SDK,没处理好,发现有个test/TestImage.php的测试文件,起初改,发现情状码$request ->
getCode()一向为0,一路调节上去,发现是getContents函数里curl错误!输出curl_errno($ch),SSL certificate problem: unable to get local
issuer certificate 使用焚林而猎办法是证书难点。

利用PHP版的SDK,没处理好,发现有个test/TestImage.php的测试文件,开头改,发现情状码$request ->
getCode()一贯为0,一路调节上去,发现是getContents函数里curl错误!输出curl_errno($ch),SSL certificate problem: unable to get local
issuer certificate 使用解决办法是证书难点。

那一个生活在研讨和支出微信产品,超过半数官网提供的文档我个人感觉依然比较详细的,可是对不当的解决办法提供的手腕并不多,作为第三回接受小程序开发的本人,在初阶阶段就蒙受了一个相比较初级的标题:调用小程序登陆API时能回来code,可是用code换取session_key和OPENid时总是提醒【40029】错误代码,微信官网给的答案是code失效,而自己从网络上找到的资料说是code被二次调用了,我反省了代码,并从未二次调用?

网上有许多有关YII2.0微信支付教程,可是太过复杂凌乱,所以前日在此间给大家整理计算运用Yii2微信后台开发的比比皆是了,给急需的同伴们参考。

错误代码 invalid-method 错误原因:
不存在的方法名 一向未缓解,可能是$request应该是文档中的AlipayCommerceCityfacilitatorVoucherGenerateRequest类实例仍旧测试文件中的$alipayClient
-> getContents() 再次来到值(AlipayMobilePublicMultiMediaExecute实例)还有Warning:
openssl_sign(): supplied key param cannot be coerced into a private key
in… 好多难点,又回头看API发现页面API下有以身作则代码,哟吼吼吼。

错误代码 invalid-method 错误原因:
不设有的主意名 平昔未缓解,可能是$request应该是文档中的AlipayCommerceCityfacilitatorVoucherGenerateRequest类实例仍旧测试文件中的$alipayClient
-> getContents() 再次回到值(AlipayMobilePublicMultiMediaExecute实例)还有Warning:
openssl_sign(): supplied key param cannot be coerced into a private key
in… 好多难点,又回头看API发现页面API下有演示代码,哟吼吼吼。

上代码:【app.js】

一:接入微信

配备好之后有荒唐{“code”:”40006″,”msg”:”Insufficient
Permissions”,”sub_code”:”isv.insufficient-isv-permissions”,”sub_msg”:”ISV权限不足”}www.30064.com 1

布署好未来有错误{“code”:”40006″,”msg”:”Insufficient
Permissions”,”sub_code”:”isv.insufficient-isv-permissions”,”sub_msg”:”ISV权限不足”}www.30064.com 2

wx.login({

Yii2后台配置

换了沙箱账号,提示此外一个荒谬{“code”:”40004″,”msg”:”Business
Failed”,”sub_code”:”unknown-sub-code”,”sub_msg”:”未知的错误码”},但都是验签函数checkResponseSign()内失误。www.30064.com 3

换了沙箱账号,提醒其余一个不当{“code”:”40004″,”msg”:”Business
Failed”,”sub_code”:”unknown-sub-code”,”sub_msg”:”未知的错误码”},但都是验签函数checkResponseSign()内失误。www.30064.com 4

success: function (res){

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

object(SignData)[5]
  public 'signSourceData' => string '{"code":"40004","msg":"Business Failed","sub_code":"unknown-sub-code","sub_msg":"未知的错误码"}' (length=101)
  public 'sign' => string 'EfXcLt1HDYQFHnfJRy31/S9+AeCd7J4jw/Zrphi2ImHgCIBGIbyZ8+Ch2yoiGeKN/tqdTPSEOosEI9QF1Nx53fHKHZG1SkrodwVzSSdkVPM9pxCszCn4u0ktTi925BazTFfNoq****JTHflEJ91GOhX19sbFYSnvD6RWus4YeFo=' (length=172)
object(SignData)[5]
  public 'signSourceData' => string '{"code":"40004","msg":"Business Failed","sub_code":"unknown-sub-code","sub_msg":"未知的错误码"}' (length=101)
  public 'sign' => string 'EfXcLt1HDYQFHnfJRy31/S9+AeCd7J4jw/Zrphi2ImHgCIBGIbyZ8+Ch2yoiGeKN/tqdTPSEOosEI9QF1Nx53fHKHZG1SkrodwVzSSdkVPM9pxCszCn4u0ktTi925BazTFfNoq****JTHflEJ91GOhX19sbFYSnvD6RWus4YeFo=' (length=172)

if(res.code){

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

 追溯curl函数,url=

 追溯curl函数,url=

console.log(res.code)//展现一下收获的code

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

地点加重的【×tamp=】很猜忌啊,×怎么可以在里面,前面应该query就得了了接下来应该是光阴参数&timestamp那些啊,改成&timestamp=就足足可以重返了而不是以此指鹿为马:错误代码
invalid-method 错误原因: 不设有的法子名 了。看看哪个地方构造url出错的。

地方加重的【×tamp=】很迷惑啊,×怎么可以在里边,后面应该query就停止了然后应该是时间参数&timestamp这一个啊,改成&timestamp=就足足可以回来了而不是其一荒唐:错误代码
invalid-method 错误原因: 不设有的点子名 了。看看何地构造url出错的。

if(res.code){

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

array (size=15)
  'app_id' => string '2016091000478468' (length=16)
  'version' => string '1.0' (length=3)
  'format' => string 'json' (length=4)
  'sign_type' => string 'RSA' (length=3)
  'method' => string 'alipay.commerce.cityfacilitator.station.query' (length=45)
  'timestamp' => string '2016-10-27 08:48:32' (length=19)
  'auth_token' => null
  'alipay_sdk' => string 'alipay-sdk-php-20160411' (length=23)
  'terminal_type' => null
  'terminal_info' => null
  'prod_code' => null
  'notify_url' => null
  'charset' => string 'UTF-8' (length=5)
  'app_auth_token' => null
  'sign' => string 'f6ufUiSHCb7LNaXJvTdPEdDzfxKgepILJiKaM3wqueGojpOTZrVFRhVFqAQAxCEze9bVX77fpS/bvT8IVoD+/DMikZrje8SqkrSQvIHG8r1VhucgWplpgJU7HzViE*****************/MoG5OqfPf+H+rU+Eui7+bfYXtTDY=' (length=172)
array (size=15)
  'app_id' => string '2016091000478468' (length=16)
  'version' => string '1.0' (length=3)
  'format' => string 'json' (length=4)
  'sign_type' => string 'RSA' (length=3)
  'method' => string 'alipay.commerce.cityfacilitator.station.query' (length=45)
  'timestamp' => string '2016-10-27 08:48:32' (length=19)
  'auth_token' => null
  'alipay_sdk' => string 'alipay-sdk-php-20160411' (length=23)
  'terminal_type' => null
  'terminal_info' => null
  'prod_code' => null
  'notify_url' => null
  'charset' => string 'UTF-8' (length=5)
  'app_auth_token' => null
  'sign' => string 'f6ufUiSHCb7LNaXJvTdPEdDzfxKgepILJiKaM3wqueGojpOTZrVFRhVFqAQAxCEze9bVX77fpS/bvT8IVoD+/DMikZrje8SqkrSQvIHG8r1VhucgWplpgJU7HzViE*****************/MoG5OqfPf+H+rU+Eui7+bfYXtTDY=' (length=172)

wx.request({

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

可以看出来确实应该是timestamp,&times的html转义字符就是×,所以 echo “&timestamp=”;会输出×tamp那种幺蛾子。

可以看出来确实应该是timestamp,&times的html转义字符就是×,所以 echo “&timestamp=”;会输出×tamp那种幺蛾子。

url: ‘

3.在app/controllers中新建WechatController

foreach ($sysParams as $sysParamKey => $sysParamValue) {
   $requestUrl .= "$sysParamKey=" . urlencode($this->characet($sysParamValue, $this->postCharset)) . "&";
  }
foreach ($sysParams as $sysParamKey => $sysParamValue) {
            $requestUrl .= "$sysParamKey=" . urlencode($this->characet($sysParamValue, $this->postCharset)) . "&";
        }

data:{

<?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;
  }
 }
 }

}

&改为&好激动。www.30064.com 5

&改为&好激动。www.30064.com 6

code:res.code

微信公众号后台配置

而是,页面怎么也一直不,错误也从没,空白,空。继续调

可是,页面怎么也未曾,错误也未尝,空白,空。继续调

}

在微信公众号后台配置URL和Token,然后提交评释即可。

www.30064.com 7 
没头绪提了难点答疑也没头绪。

www.30064.com 8 
没头绪提了难点答疑也没头绪。

success: function (re) {

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

10/28

10/28

console.log(re.data)

二:获取用户音讯

明日境遇的参数难点,我把timestamp提到了最前方,发现时间参数还差了6个小时,不说了一向time()+6*3600。然后[署名无效]。又调了多少个钟头,暂时搁置。www.30064.com 9

昨天遇见的参数难点,我把timestamp提到了最前边,发现时间参数还差了6个小时,不说了直白time()+6*3600。然后[署名无效]。又调了多少个钟头,暂时搁置。www.30064.com 10

},

用户表设计

fail:function(){

复制代码 代码如下:

console.log(‘shiban’)

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`);

}

得到用户新闻的相干接口

})

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

}

复制代码 代码如下:

}else{

public function actionAccesstoken()
{
    $code = $_GET[“code”];
    $state = $_GET[“state”];
    $appid = Yii::$app->params[‘wechat’][‘appid’];
    $appsecret = Yii::$app->params[‘wechat’][‘appsecret’];
    $request_url =
”;
    //开端化一个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);
    }
}

console.log(‘获取用户登录态失利!’ + res.errMsg)

2.从微信获取用户资料

}

复制代码 代码如下:

}

public function getUserInfo($access_token,$openid)
{
    $request_url =
”;
    //初步化一个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;
}

本人要好服务器上的文书【request_code.php】

3.拿走用户资料接口

$APPID=’XXXXXXXX’;

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;
}

$AppSecret=”xxxxxxxxxxxxxxxxxxxxx”;

 

$code=$_REQUEST[‘code’];

三:微信支付

$request_https=”

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

复制代码 代码如下:

public function actionPay(){
   
if(isset($_REQUEST[“uid”])&&isset($_REQUEST[左右逢源应用Yii2微信后台开发的层层计算,支付宝地铁SDK使用失利记录。”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;
}

//获取session_key和openid的接口地址

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

$ch=curl_init();

复制代码 代码如下:

curl_setopt($ch,CURLOPT_URL,$request_https);

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>’;
    }
}

curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);

3.微信支付类 WechatPay.php

curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);

复制代码 代码如下:

curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

<?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);
//设置cURL允许实施的最长秒数
        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;
    }
}

$output=curl_exec($ch);

四:获取JS-SDK的config参数

curl_close($ch);

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

$jsoninfo=$output;

具备要求选择JS-SDK的页面必须先注入配置音信,否则将不可能调用(同一个url仅需调用一遍,对于变化url的SPA的web
app可在每一遍url变化时举行调用,近期Android微信客户端不协理pushState的H5新特性,所以选用pushState来兑现web
app的页面会造成签名败北,此题材会在Android6.2中修复)。

//提交到接口的代码

即:

那般回去就是40029指鹿为马,后台无意中自己将appid和secret的值直接写在底下的接口地址里,竟然神奇的起功能了,换回了session_key和openid:

复制代码 代码如下:

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);
//设置cURL允许实施的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
www.30064.com,        //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中设置与收获别名的函数(setAlias和getAlias)用法分析
  • Yii2中YiiBase自动加载类、引用文件措施分析(autoload)
  • Yii2创设控制器(createController)方法详解
  • Yii2主题(Theme)用法详解
  • Yii2成立表单(ActiveForm)方法详解
  • Yii2验证器(Validator)用法分析
  • yii2
    RBAC使用DbManager完毕后台权限判断的艺术
  • Yii2不难完成多语言配置的格局
  • yii2控制器Controller
    Ajax操作示例
  • Yii2中Restful
    API原理实例分析

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图