圆满应用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 使用竭泽而渔办法是证书难点。

网上有很多关于YII2.0微信支付教程,可是太过复杂凌乱,所以后天在此间给我们整理计算运用Yii2微信后台开发的千千万万了,给急需的同伴们参考。

那些日子在切磋和付出微信产品,大多数官网提供的文档我个人感觉照旧相比详细的,不过对错误的解决办法提供的手法并不多,作为第三遍收受小程序开发的自身,在上马阶段就遇到了一个相比初级的难点:调用小程序登陆API时能回去code,不过用code换取session_key和OPENid时老是提醒【40029】错误代码,微信官网给的答案是code失效,而自我从网络上找到的材料说是code被二次调用了,我反省了代码,并没有二次调用?

错误代码 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权限不足”}澳门葡京备用网址 1

安排好之后有荒唐{“code”:”40006″,”msg”:”Insufficient
Permissions”,”sub_code”:”isv.insufficient-isv-permissions”,”sub_msg”:”ISV权限不足”}澳门葡京备用网址 2

Yii2后台配置

wx.login({

换了沙箱账号,提醒别的一个荒唐{“code”:”40004″,”msg”:”Business
Failed”,”sub_code”:”unknown-sub-code”,”sub_msg”:”未知的错误码”},但都是验签函数checkResponseSign()内失误。澳门葡京备用网址 3

换了沙箱账号,提醒此外一个错误{“code”:”40004″,”msg”:”Business
Failed”,”sub_code”:”unknown-sub-code”,”sub_msg”:”未知的错误码”},但都是验签函数checkResponseSign()内失误。澳门葡京备用网址 4

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

success: function (res){

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)
return [
 //微信接入
 'wechat' =>[
 'token' => 'your token',
 ],
];

if(res.code){

 追溯curl函数,url=

 追溯curl函数,url=

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

console.log(res.code)//彰显一下取得的code

地方加重的【×tamp=】很迷惑啊,×怎么可以在其间,前面应该query就甘休了解后应该是岁月参数&timestamp这一个啊,改成&timestamp=就足足可以回来了而不是其一颠倒是非:错误代码
invalid-method 错误原因: 不设有的方法名 了。看看何地构造url出错的。

地点加重的【×tamp=】很纳闷啊,×怎么可以在中间,前面应该query就停止了接下来应该是时刻参数&timestamp这几个啊,改成&timestamp=就至少可以回去了而不是这几个错误:错误代码
invalid-method 错误原因: 不存在的办法名 了。看看哪个地方构造url出错的。

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

if(res.code){

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)
'urlManager' => [
 'enablePrettyUrl' => true,
 'enableStrictParsing' => true,
 'showScriptName' => false,
 'rules' => [
 [
  'class' => 'yii\rest\UrlRule',
  'controller' => 'wechat',
  'extraPatterns' => [
  'GET valid' => 'valid',
  ],
 ],
 ],
],

wx.request({

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

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

3.在app/controllers中新建WechatController

url: ‘

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)) . "&";
        }
<?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;
  }
 }
 }

}

data:{

&改为&好激动。澳门葡京备用网址 5

&改为&好激动。澳门葡京备用网址 6

微信公众号后台配置

code:res.code

不过,页面怎么也从没,错误也从没,空白,空。继续调

不过,页面怎么也未曾,错误也未曾,空白,空。继续调

在微信公众号后台配置URL和Token,然后交由认证即可。

}

澳门葡京备用网址 7 
没头绪提了难点回复也没头绪。

澳门葡京备用网址 8 
没头绪提了难点回答也没头绪。

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

success: function (re) {

10/28

10/28

二:获取用户音讯

console.log(re.data)

明日蒙受的参数难点,我把timestamp提到了最前头,发现时间参数还差了6个钟头,不说了直接time()+6*3600。然后[签字无效]。又调了多少个钟头,暂时搁置。澳门葡京备用网址 9

明天碰到的参数难题,我把timestamp提到了最前边,发现时间参数还差了6个小时,不说了直白time()+6*3600。然后[签名无效]。又调了多少个钟头,暂时搁置。澳门葡京备用网址 10

用户表设计

},

复制代码 代码如下:

fail:function(){

CREATE TABLE `wechat_圆满应用Yii2微信后台开发的触目皆是统计,支付宝地铁SDK使用败北记录。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`);

console.log(‘shiban’)

赢得用户新闻的连锁接口

}

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

})

复制代码 代码如下:

}

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

}else{

2.从微信获取用户资料

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

复制代码 代码如下:

}

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

}

3.获取用户资料接口

自身要好服务器上的公文【request_code.php】

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

$APPID=’XXXXXXXX’;

 

$AppSecret=”xxxxxxxxxxxxxxxxxxxxx”;

三:微信支付

$code=$_REQUEST[‘code’];

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

$request_https=”

复制代码 代码如下:

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.收到微信发送的异步支付结果通告

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

复制代码 代码如下:

$ch=curl_init();

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_URL,$request_https);

3.微信支付类 WechatPay.php

curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);

复制代码 代码如下:

curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);

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

curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

四:获取JS-SDK的config参数

$output=curl_exec($ch);

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

curl_close($ch);

具有必要采用JS-SDK的页面必须先注入配置音信,否则将不可能调用(同一个url仅需调用一遍,对于变化url的SPA的web
app可在每一趟url变化时举行调用,目前Android微信客户端不帮衬pushState的H5新特性,所以选拔pushState来达成web
app的页面会导致签名失败,此题材会在Android6.2中修复)。

$jsoninfo=$output;

即:

澳门葡京备用网址,//提交到接口的代码

复制代码 代码如下:

如此那般回去就是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);
        }
        //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原理实例分析

相关文章

发表评论

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

*
*
Website