GVKun编程网logo

PHP:微信小程序 微信支付服务端集成实例详解及源码下载(微信支付php开发流程)

8

对于想了解PHP:微信小程序微信支付服务端集成实例详解及源码下载的读者,本文将提供新的信息,我们将详细介绍微信支付php开发流程,并且为您提供关于golang实现微信小程序支付服务端、golang微信

对于想了解PHP:微信小程序 微信支付服务端集成实例详解及源码下载的读者,本文将提供新的信息,我们将详细介绍微信支付php开发流程,并且为您提供关于golang实现微信小程序支付服务端、golang微信支付服务端、php 官方微信接口大全:微信支付、微信红包、微信摇一摇、微信小店的完整代码、PHP开发小程序支付服务端集成的步骤详解的有价值信息。

本文目录一览:

PHP:微信小程序 微信支付服务端集成实例详解及源码下载(微信支付php开发流程)

PHP:微信小程序 微信支付服务端集成实例详解及源码下载(微信支付php开发流程)

微信小程序 微信支付服务端集

理论上集成微信支付的全部工作可以在小程序端完成,因为小程序js有访问网络的能力,但是为了安全,不暴露敏感key,而且可以使用官方提供的现成PHP demo更省力,于是在服务端完成签名与发起请求,小程序端只做一个wx.requestPayment(OBJECT)接口的对接。

整体集成过程与JSAPI、APP类似,先统一下单,然后拿返回的结果来请求支付。

一共三步:

1.小程序端通过wx.login的返回的code换取openid 2.服务端向微信统一下单 3.小程序端发起支付

事先准备好这几样东西:

rush:js;"> APPID = 'wx426b3015555a46be'; MCHID = '1900009851'; KEY = '8934e7d15453e97507ef794cf7b0519d'; APPSECRET = '7813490da6f1265e4901ffb80afaa36f';

PHP SDK,下载链接见文尾

第1、4样是申请小程序时获得的,第2、3样是申请开通微信支付时获得的,注意第3、4样长得比较像,其实是2个东西,

两者混淆将导致签名通不过

向微信端下单,得到prepay_id

1. 创建一个Controller,引并WxPay.Api.PHP类

rush:PHP;"> PHP require_once __DIR__ . '/BaseController.PHP'; require_once __DIR__ . '/../third_party/wxpay/WxPay.Api.PHP';

class WXPay extends BaseController {
function index() {
}
}

之后可以通过index.PHP/wxpay来作访问请求

2. 修改配置文件WxPay.Config.PHP

改成自己申请得到相应key

3. 实现index方法

SetBody("灵动商城-手机"); // 订单号应该是由小程序端传给服务端的,在用户下单时即生成,demo中取值是一个生成的时间戳 $input->Setout_Trade_no('123123123'); // 费用应该是由小程序端传给服务端的,在用户下单时告知服务端应付金额,demo中取值是1,即1分钱 $input->SetTotal_fee("1"); $input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.PHP"); $input->SetTrade_type("JSAPI"); // 由小程序端传给服务端 $input->Setopenid($this->input->post('openId')); // 向微信统一下单,并返回order,它是一个array数组 $order = WxPayApi::unifiedOrder($input); // json化返回给小程序端 header("Content-Type: application/json"); echo json_encode($order); }

说明1:

文档上提到的nonce_str不是没提交,而是sdk帮我们填上的

出处在WxPay.Api.PHP第55行

SetNonce_str(self::getNoncestr());//随机字符串

说明2:

sign也已经好心地给setSign了,出处在WxPay.Data.PHP第111行,MakeSign()中

values); $string = $this->ToUrlParams(); //签名步骤二:在string后加入KEY $string = $string . "&key=".WxPayConfig::KEY; //签名步骤三:MD5加密 $string = md5($string); //签名步骤四:所有字符转为大写 $result = strtoupper($string); return $result; }

4. 小程序内调用登录接口,获取openid

向微信登录请求,拿到code,再将code提交换取openId

rush:PHP;"> wx.login({ success: function(res) { if (res.code) { //发起网络请求 wx.request({ url: 'https://api.weixin.qq.com/sns/jscode2session?appid=wx9114b997bd86f***&secret=d27551c7803cf16015e536b192******&js_code='+res.code+'&grant_type=authorization_code',data: { code: res.code },success: function (response) { console.log(response); } }) } else { console.log('获取用户登录态失败!' + res.errMsg) } } });

从控制台看到已经成功拿到openid,剩下的事情就是将它传到服务端就好了,服务端那边$this->input->post('openId')等着收呢。

5. 小程序端向https://lendoo.leanapp.cn/index.PHP/WXPay发起请求,作统一下单

rush:js;"> //统一下单接口对接 wx.request({ url: 'https://lendoo.leanapp.cn/index.PHP/WXPay',data: { openId: openId },success: function (response) { console.log(response);
        },header: {
        'content-type': 'application/x-www-form-urlencoded'
    },});</pre>

得到如下结果

rush:PHP;"> { "appid": "wx9114b997bd86f8ed","mch_id": "1414142302","nonce_str": "eEICgYFuGqxFRK6f","prepay_id": "wx201701022235141fc713b8f80137935406","result_code": "SUCCESS","return_code": "SUCCESS","return_msg": "OK","sign": "63E60C8CD90394FB50E612D085F5362C","Trade_type": "JSAPI" }

前提是https://lendoo.leanapp.cn已经在白名单:

6. 小程序端调起支付API

rush:js;"> // 发起支付 var appId = response.data.appid; var timeStamp = (Date.parse(new Date()) / 1000).toString(); var pkg = 'prepay_id=' + response.data.prepay_id; var nonceStr = response.data.nonce_str; var paySign = md5.hex_md5('appId='+appId+'&nonceStr='+nonceStr+'&package='+pkg+'&signType=MD5&timeStamp='+timeStamp+"&key=d27551c7803cf16***e536b192d5d03b").toupperCase(); console.log(paySign); console.log(appId); wx.requestPayment({ 'timeStamp': timeStamp,'nonceStr': nonceStr,'package': pkg,'signType': 'MD5','paySign': paySign,'success':function(res){ console.log('success'); console.log(res); } });

模拟器测试,将弹出一个二维码供扫描

结果报了一个错误:

rush:js;"> errMsg:"requestPayment:fail" err_code:2 err_desc:"支付验证签名失败"

key需要加入到签名中!!!

'appId='+appId+'&nonceStr='+nonceStr+'&package='+pkg+'&signType=MD5&timeStamp='+timeStamp+"&key=d27551c7803cf16*e536b192d5d03b"这才是完整的。

可是文档里明明没提到key啊

支付成功截图

吐槽完文档再吐槽下命名规则,GetSpbill_create_ip()、Isspbill_create_ipSet()都是些什么鬼一会儿下划线分隔一会儿驼峰分隔,成员方法首字母还大写,unifiedOrder()这种正经写法也不忘来比划两下,看来网上说大公司的sdk都是实习生撰写是真事,可code reviewer又在哪里?

该demo源码地址:

otton-lendoo-wx-master(jb51.cc).rar">http://xiazai.jb51.cc/201701/yuanma/dotton-lendoo-wx-master(jb51.cc).rar,欢迎下载。

小程序端文档出处:https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-pay.html

微信支付服务端侧文档出处:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.PHP?chapter=9_1

类比文档出处:https://pay.weixin.qq.com/wiki/doc/api/app/app.PHP?chapter=9_1

开发步骤:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.PHP?chapter=7_3&index=1

sdk下载:https://pay.weixin.qq.com/wiki/doc/api/download/WxpayAPI_PHP_v3.zip

golang实现微信小程序支付服务端

golang实现微信小程序支付服务端

小程序支付的交互图如下:

小程序支付时序图

商户系统和微信支付系统主要交互:
1、小程序内调用登录接口,获取到用户的openid,api参见公共api【小程序登录API】
2、商户server调用支付统一下单,api参见公共api【统一下单API】
3、商户server调用再次签名,api参见公共api【再次签名】
4、商户server接收支付通知,api参见公共api【支付结果通知API】
5、商户server查询支付结果,api参见公共api【查询订单API】

以下是统一下单API

//响应信息
type WXPayResp struct {
    Return_code string `xml:"return_code"`
    Return_msg  string `xml:"return_msg"`
    Nonce_str   string `xml:"nonce_str"`
    Prepay_id   string `xml:"prepay_id"`
}
//微信支付
func (index *IndexController) WxPay(){
    info := make(map[string]interface{}, 0)

    fmt.Println("访问ip",index.Request.RemoteAddr)
    ip := utils.Substr(index.Request.RemoteAddr, 0,strings.Index(index.Request.RemoteAddr,":"))

    total_fee,_ := strconv.ParseFloat(index.GetString("total_fee"),64)  //单位 分
    openId := index.GetString("openId");        //"oKYr_0GkE-Izt9N9Wn43sapI9Pqw"
    body := "费用说明";
    //订单号
    orderNo := index.GetString("orderNo"); //"wx"+utils.ToStr(time.Now().Unix()) + string(utils.Krand(4,0))
    //随机数
    nonceStr := time.Now().Format("20060102150405") + string(utils.Krand(4, 0))
    var reqMap = make(map[string]interface{}, 0)
    reqMap["appid"] = utils.Wx_Appid//微信小程序appid
    reqMap["body"] = body           //商品描述
    reqMap["mch_id"] = utils.Wx_Mchid   //商户号
    reqMap["nonce_str"] = nonceStr      //随机数
    reqMap["notify_url"] = "http://test.com.cn/weixinNotice.jspx"   //通知地址
    reqMap["openid"] = openId       //商户唯一标识 openid
    reqMap["out_Trade_no"] = orderNo    //订单号
    reqMap["spbill_create_ip"] = ip     //用户端ip //订单生成的机器 IP
    reqMap["total_fee"] = total_fee * 100   //订单总金额,单位为分
    reqMap["Trade_type"] = "JSAPI"      //Trade_type=JSAPI时(即公众号支付),此参数必传,此参数为微信用户在商户对应appid下的唯一标识
    reqMap["sign"] = WxPayCalcSign(reqMap,utils.WX_KEY)

    reqStr := Map2Xml(reqMap)
    fmt.Println("请求xml",reqStr)

    client := &http.Client{}

    // 调用支付统一下单API
    req,err := http.NewRequest("POST","https://api.mch.weixin.qq.com/pay/unifiedorder",strings.NewReader(reqStr))
    if err != nil {
        // handle error
    }
    req.Header.Set("Content-Type","text/xml;charset=utf-8")

    resp,err := client.Do(req)
    defer resp.Body.Close()

    body2,err := IoUtil.ReadAll(resp.Body)
    if err != nil {
        // handle error
        fmt.Println("解析响应内容失败",err)
        return
    }
    fmt.Println("响应数据",string(body2))

    var resp1 WXPayResp
    err = xml.Unmarshal(body2,&resp1)
    if err != nil {
        panic(err)
        return
    }

    // 返回预付单信息
    if strings.toupper(resp1.Return_code) == "SUCCESS"{
        fmt.Println("预支付申请成功")
        // 再次签名
        var resMap = make(map[string]interface{}, 0)
        resMap["appId"] = utils.Wx_Appid
        resMap["nonceStr"] = resp1.Nonce_str            //商品描述
        resMap["package"] = "prepay_id=" + resp1.Prepay_id  //商户号
        resMap["signType"] = "MD5"              //签名类型
        resMap["timeStamp"] = utils.ToStr(time.Now().Unix())    //当前时间戳

        resMap["paySign"] = WxPayCalcSign(resMap,utils.WX_KEY)
        // 返回5个支付参数及sign 用户进行确认支付

        fmt.Println("支付参数",resMap)
        index.Console(resMap)
    }else{
        info["msg"] = "微信请求支付失败"
        index.Console(info)
    }
}
//微信支付计算签名的函数
func WxPayCalcSign(mReq map[string]interface{},key string) (sign string) {
    //STEP 1,对key进行升序排序.
    sorted_keys := make([]string,0)
    for k,_ := range mReq { sorted_keys = append(sorted_keys,k) }
    sort.Strings(sorted_keys)

    //STEP2,对key=value的键值对用&连接起来,略过空值
    var signStrings string
    for _,k := range sorted_keys {
        logger.Printf("k=%v,v=%v\n",k,mReq[k])
        value := fmt.Sprintf("%v",mReq[k])
        if value != "" {
            signStrings = signStrings + k + "=" + value + "&"
        }
    }

    //STEP3,在键值对的最后加上key=API_KEY
    if key != "" {
        signStrings = signStrings + "key=" + key
    }

    fmt.Println("加密前-----",signStrings)
    //STEP4,进行MD5签名并且将所有字符转为大写.
    md5Ctx := md5.New()
    md5Ctx.Write([]byte(signStrings)) //
    cipherStr := md5Ctx.Sum(nil)
    upperSign := strings.toupper(hex.EncodetoString(cipherStr))

    fmt.Println("加密后-----",upperSign)
    return upperSign
}
//微信支付计算签名的函数
func Map2Xml(mReq map[string]interface{}) (xml string) {
    sb := bytes.Buffer{}
    sb.WriteString("<xml>")
    for k,v := range mReq{
        sb.WriteString("<"+k+">"+utils.ToStr(v)+"</"+k+">")
    }
    sb.WriteString("</xml>")
    return sb.String()
}

golang微信支付服务端

golang微信支付服务端

总结

以上是小编为你收集整理的golang微信支付服务端全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

php 官方微信接口大全:微信支付、微信红包、微信摇一摇、微信小店的完整代码

php 官方微信接口大全:微信支付、微信红包、微信摇一摇、微信小店的完整代码

感兴趣PHP 官方微信接口大全:微信支付、微信红包、微信摇一摇、微信小店的完整代码的小伙伴,下面一起跟随小编 jb51.cc的小编来看看吧。<br>
微信入口绑定,微信事件处理,微信API全部操作包含在这些文件中。
内容有:微信摇一摇接口/微信多客服接口/微信支付接口/微信红包接口/微信卡券接口/微信小店接口/JSAPI
/**
 * @param 
 * @author 小编 jb51.cc jb51.cc
**/
 class WxApi {
  const appId   = "";
  const appSecret  = "";
  const mchid   = ""; //商户号
  const privatekey = ""; //私钥
  public $parameters = array();
  public $jsApiTicket = NULL;
  public $jsApiTime = NULL;
  
  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,1);
    //这里设置代理,如果有的话
    //curl_setopt($ch,CURLOPT_PROXY,'10.206.30.98');
    //curl_setopt($ch,CURLOPT_PROXYPORT,8080);
    curl_setopt($ch,$url);
    curl_setopt($ch,false);
    curl_setopt($ch,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,CURLOPT_SSLKEY,getcwd().'/apiclient_key.pem');
  
    curl_setopt($ch,CURLOPT_CAINFO,getcwd().'/rootca.pem');
  
    //第二种方式,两个文件合成一个.pem文件
    //curl_setopt($ch,getcwd().'/all.pem');
  
    if( count($aHeader) >= 1 ){
      curl_setopt($ch,CURLOPT_HTTPHEADER,$aHeader);
    }
  
    curl_setopt($ch,1);
    curl_setopt($ch,$vars);
    $data = curl_exec($ch);
    if($data){
      curl_close($ch);
      return $data;
    }
    else { 
      $error = curl_errno($ch);
      echo "call faild,errorCode:$error\n"; 
      curl_close($ch);
      return false;
    }
  }
  
  /****************************************************
   * 微信获取Accesstoken 返回指定微信公众号的at信息
   ****************************************************/
  
  public function wxAccesstoken($appId = NULL,$appSecret = NULL){
    $appId   = is_null($appId) ? self::appId : $appId;
    $appSecret  = is_null($appSecret) ? self::appSecret : $appSecret;
      
    $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;
  }
  
  /****************************************************
   * 微信获取ApiTicket 返回指定微信公众号的at信息
   ****************************************************/
  
  public function wxJsApiTicket($appId = NULL,$appSecret = NULL){
    $appId   = is_null($appId) ? self::appId : $appId;
    $appSecret  = is_null($appSecret) ? self::appSecret : $appSecret;
      
    $url   = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".$this->wxAccesstoken();
    $result   = $this->wxHttpsRequest($url);
    $jsoninfo  = json_decode($result,true);
    $ticket   = $jsoninfo['ticket'];
    //echo $ticket . "<br />";
    return $ticket;
  }
    
  public function wxVerifyJsApiTicket($appId = NULL,$appSecret = NULL){
   if(!empty($this->jsApiTime) && intval($this->jsApiTime) > time() && !empty($this->jsApiTicket)){
    $ticket = $this->jsApiTicket;
   }
   else{
    $ticket = $this->wxJsApiTicket($appId,$appSecret);
    $this->jsApiTicket = $ticket;
    $this->jsApiTime = time() + 7200;
   }
   return $ticket;
  }
    
  /****************************************************
   * 微信通过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;
  }  
  
  /****************************************************
   * 微信生成二维码ticket
   ****************************************************/
  
  public function wxQrCodeTicket($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url  = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,$jsonData);
   return $result;
  }
    
  /****************************************************
   * 微信通过ticket生成二维码
   ****************************************************/
  public function wxQrCode($ticket){
   $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticket);
   return $url;
  }
    
  /****************************************************
   * 微信通过指定模板信息发送给指定用户,发送完成后返回指定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 = urldecode(json_encode($template));
    echo $jsonData;
    $result = $this->wxSendTemplate($jsonData);
    return $result;
  }
  
  /****************************************************
   * 微信设置OAUTH跳转URL,返回字符串信息 - ScopE = snsapi_base //验证时不返回确认页面,只能获取OPENID
   ****************************************************/
  
  public function wxOauthBase($redirectUrl,$state = "",$appId = NULL){
    $appId   = is_null($appId) ? self::appId : $appId;
    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appId."&redirect_uri=".$redirectUrl."&response_type=code&scope=snsapi_base&state=".$state."#wechat_redirect";
    return $url;
  }
  
  /****************************************************
   * 微信设置OAUTH跳转URL,返回字符串信息 - ScopE = snsapi_userinfo //获取用户完整信息
   ****************************************************/
  
  public function wxOauthUserinfo($redirectUrl,$appId = NULL){
    $appId   = is_null($appId) ? self::appId : $appId;
    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appId."&redirect_uri=".$redirectUrl."&response_type=code&scope=snsapi_userinfo&state=".$state."#wechat_redirect";
    return $url;
  }
  
  /****************************************************
   * 微信OAUTH跳转指定URL
   ****************************************************/
  
  public function wxHeader($url){
    header("location:".$url);
  }
  
  /****************************************************
   * 微信通过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;   
  }
  
  /****************************************************
   * 创建自定义菜单
   ****************************************************/
  
  public function wxMenuCreate($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,$jsonData);
   $jsoninfo  = json_decode($result,true);
   return $jsoninfo;   
  }
  
  /****************************************************
   * 获取自定义菜单
   ****************************************************/
  
  public function wxMenuGet(){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url);
   $jsoninfo  = json_decode($result,true);
   return $jsoninfo;
  }
  
  /****************************************************
   * 删除自定义菜单
   ****************************************************/
  
  public function wxMenuDelete(){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url);
   $jsoninfo  = json_decode($result,true);
   return $jsoninfo;
  }
  
  /****************************************************
   * 获取第三方自定义菜单
   ****************************************************/
  
  public function wxMenuGetInfo(){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url);
   $jsoninfo  = json_decode($result,true);
   return $jsoninfo;
  }
  
  
    
  /****************************************************
   * 微信客服接口 - Add 添加客服人员
   ****************************************************/
  
  public function wxServiceAdd($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/customservice/kfaccount/add?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
  
  /****************************************************
   * 微信客服接口 - Update 编辑客服人员
   ****************************************************/
  
  public function wxServiceUpdate($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/customservice/kfaccount/update?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
  
  
  /****************************************************
   * 微信客服接口 - Delete 删除客服人员
   ****************************************************/
  
  public function wxServiceDelete($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/customservice/kfaccount/del?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
    
  /*******************************************************
   *  微信客服接口 - 上传头像
   *******************************************************/
  public function wxServiceUpdateCover($kf_account,$media = '') {
   $wxAccesstoken = $this->wxAccesstoken();
   //$data['access_token'] = $wxAccesstoken;
   $data['media']  = '@D:\\workspace\\htdocs\\yky_test\\logo.jpg';
   $url   = "https:// api.weixin.qq.com/customservice/kfaccount/uploadheadimg?access_token=".$wxAccesstoken."&kf_account=".$kf_account;
   $result   = $this->wxHttpsRequest($url,$data);
   $jsoninfo  = json_decode($result,true);
   return $jsoninfo;
  }
    
  /****************************************************
   *  微信客服接口 - 获取客服列表
   ****************************************************/
  
  public function wxServiceList(){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url);
   $jsoninfo  = json_decode($result,true);
   return $jsoninfo;
  }
    
  /****************************************************
   *  微信客服接口 - 获取在线客服接待信息
   ****************************************************/
  
  public function wxServiceOnlineList(){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url);
   $jsoninfo  = json_decode($result,true);
   return $jsoninfo;
  }
    
  /****************************************************
   *  微信客服接口 - 客服发送信息
   ****************************************************/
  
  public function wxServiceSend($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
  
  /****************************************************
   *  微信客服会话接口 - 创建会话
   ****************************************************/
  
  public function wxServiceSessionAdd($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/customservice/kfsession/create?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
  
  /****************************************************
   *  微信客服会话接口 - 关闭会话
   ****************************************************/
  
  public function wxServiceSessionClose(){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/customservice/kfsession/close?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url);
   $jsoninfo  = json_decode($result,true);
   return $jsoninfo;
  }
  
  /****************************************************
   *  微信客服会话接口 - 获取会话
   ****************************************************/
  
  public function wxServiceSessionGet($openId){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/customservice/kfsession/getsession?access_token=".$wxAccesstoken."&openid=" . $openId;
   $result   = $this->wxHttpsRequest($url);
   $jsoninfo  = json_decode($result,true);
   return $jsoninfo;
  }
  
  /****************************************************
   *  微信客服会话接口 - 获取会话列表
   ****************************************************/
  
  public function wxServiceSessionList($kf_account){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/customservice/kfsession/getsessionlist?access_token=".$wxAccesstoken."&kf_account=" . $kf_account ;
   $result   = $this->wxHttpsRequest($url);
   $jsoninfo  = json_decode($result,true);
   return $jsoninfo;
  }
  
  /****************************************************
   *  微信客服会话接口 - 未接入会话
   ****************************************************/
  
  public function wxServiceSessionWaitCase(){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/customservice/kfsession/getwaitcase?access_token=".$wxAccesstoken;
   $result   = $this->wxHttpsRequest($url);
   $jsoninfo  = json_decode($result,true);
   return $jsoninfo;
  }
    
  /****************************************************
   *  微信摇一摇 - 申请设备ID
   ****************************************************/
  
  public function wxDeviceApply($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/shakearound/device/applyid?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
    
  /****************************************************
   *  微信摇一摇 - 编辑设备ID
   ****************************************************/
  
  public function wxDeviceUpdate($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/shakearound/device/update?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
    
  /****************************************************
   *  微信摇一摇 - 本店关联设备
   ****************************************************/
  
  public function wxDeviceBindLocation($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/shakearound/device/bindlocation?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
    
  /****************************************************
   *  微信摇一摇 - 查询设备列表
   ****************************************************/
  
  public function wxDeviceSearch($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/shakearound/device/search?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }  
  
  /****************************************************
   *  微信摇一摇 - 新增页面
   ****************************************************/
  
  public function wxPageAdd($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/shakearound/page/add?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
  
  /****************************************************
   *  微信摇一摇 - 编辑页面
   ****************************************************/
  
  public function wxPageUpdate($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/shakearound/page/update?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
  
  /****************************************************
   *  微信摇一摇 - 查询页面
   ****************************************************/
  
  public function wxPageSearch($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/shakearound/page/search?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }  
  
  /****************************************************
   *  微信摇一摇 - 删除页面
   ****************************************************/
  
  public function wxPageDelete($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/shakearound/page/delete?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
  
  /*******************************************************
   *  微信摇一摇 - 上传图片素材
   *******************************************************/
  public function wxMaterialAdd($media = '') {
   $wxAccesstoken = $this->wxAccesstoken();
   //$data['access_token'] = $wxAccesstoken;
   $data['media']  = '@D:\\workspace\\htdocs\\yky_test\\logo.jpg';
   $url   = "https://api.weixin.qq.com/shakearound/material/add?access_token=".$wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
  
  /****************************************************
   *  微信摇一摇 - 配置设备与页面的关联关系
   ****************************************************/
  
  public function wxDeviceBindPage($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/shakearound/device/bindpage?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
  
  /****************************************************
   *  微信摇一摇 - 获取摇周边的设备及用户信息
   ****************************************************/
  
  public function wxGetShakeInfo($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/shakearound/user/getshakeinfo?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
  
  /****************************************************
   *  微信摇一摇 - 以设备为维度的数据统计接口
   ****************************************************/
  
  public function wxGetShakeStatistics($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/shakearound/statistics/device?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
    
  /*****************************************************
   *  生成随机字符串 - 最长为32位字符串
   *****************************************************/
  public function wxNonceStr($length = 16,$type = FALSE) {
   $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMnopQRSTUVWXYZ0123456789";
   $str = "";
   for ($i = 0; $i < $length; $i++) {
    $str .= substr($chars,mt_rand(0,strlen($chars) - 1),1);
   }
   if($type == TRUE){
    return strtoupper(md5(time() . $str));
   }
   else {
    return $str;
   }
  }
    
  /*******************************************************
   *  微信商户订单号 - 最长28位字符串
   *******************************************************/
    
  public function wxMchBillno($mchid = NULL) {
   if(is_null($mchid)){
    if(self::mchid == "" || is_null(self::mchid)){
     $mchid = time();
    }
    else{
     $mchid = self::mchid;
    }
   }
   else{
    $mchid = substr(addslashes($mchid),10);
   }
   return date("Ymd",time()).time().$mchid;
  }
    
  /*******************************************************
   *  微信格式化数组变成参数格式 - 支持url加密
   *******************************************************/ 
    
  public function wxSetParam($parameters){
   if(is_array($parameters) && !empty($parameters)){
    $this->parameters = $parameters;
    return $this->parameters;
   }
   else{
    return array();
   }
  }
    
  /*******************************************************
   *  微信格式化数组变成参数格式 - 支持url加密
   *******************************************************/
    
  public function wxFormatArray($parameters = NULL,$urlencode = FALSE){
   if(is_null($parameters)){
    $parameters = $this->parameters;
   }
   $restr = "";//初始化空
   ksort($parameters);//排序参数
   foreach ($parameters as $k => $v){//循环定制参数
    if (null != $v && "null" != $v && "sign" != $k) {
     if($urlencode){//如果参数需要增加URL加密就增加,不需要则不需要
      $v = urlencode($v);
     }
     $restr .= $k . "=" . $v . "&";//返回完整字符串
    }
   }
   if (strlen($restr) > 0) {//如果存在数据则将最后“&”删除
    $restr = substr($restr,strlen($restr)-1);
   }
   return $restr;//返回字符串
  }
    
  /*******************************************************
   *  微信MD5签名生成器 - 需要将参数数组转化成为字符串[wxFormatArray方法]
   *******************************************************/
  public function wxMd5Sign($content,$privatekey){
  try {
    if (is_null($privatekey)) {
     throw new Exception("财付通签名key不能为空!");
    }
    if (is_null($content)) {
     throw new Exception("财付通签名内容不能为空");
    }
    $signStr = $content . "&key=" . $privatekey;
    return strtoupper(md5($signStr));
   }
   catch (Exception $e)
   {
    die($e->getMessage());
   }
  }
    
  /*******************************************************
   *  微信Sha1签名生成器 - 需要将参数数组转化成为字符串[wxFormatArray方法]
   *******************************************************/
  public function wxSha1Sign($content){
   try {
    if (is_null($content)) {
     throw new Exception("签名内容不能为空");
    }
    //$signStr = $content;
    return sha1($content);
   }
   catch (Exception $e)
   {
    die($e->getMessage());
   }
  }
    
  /*******************************************************
   *  微信jsApi整合方法 - 通过调用此方法获得jsapi数据
   *******************************************************/ 
  public function wxJsapiPackage(){
   $jsapi_ticket = $this->wxVerifyJsApiTicket();
     
   // 注意 URL 一定要动态获取,不能 hardcode.
   $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
   $url = $protocol.$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
     
   $timestamp = time();
   $nonceStr = $this->wxNoncestr();
     
   $signPackage = array(
    "jsapi_ticket" => $jsapi_ticket,"nonceStr" => $nonceStr,"timestamp" => $timestamp,"url"  => $url
   ); 
     
   // 这里参数的顺序要按照 key 值 ASCII 码升序排序
   $rawString = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr×tamp=$timestamp&url=$url";
     
   //$rawString = $this->wxFormatArray($signPackage);
   $signature = $this->wxSha1Sign($rawString);
     
   $signPackage['signature'] = $signature;
   $signPackage['rawString'] = $rawString;
   $signPackage['appId'] = self::appId;
     
   return $signPackage;
  }
  
    
  /*******************************************************
   *  微信卡券:JSAPI 卡券Package - 基础参数没有附带任何值 - 再生产环境中需要根据实际情况进行修改
   *******************************************************/ 
  public function wxCardPackage($cardId,$timestamp = ''){
   $api_ticket = $this->wxVerifyJsApiTicket();
   if(!empty($timestamp)){
    $timestamp = $timestamp;
   }
   else{
    $timestamp = time();
   }
     
   $arrays = array(self::appSecret,$timestamp,$cardId);
   sort($arrays,SORT_STRING);
   //print_r($arrays);
   //echo implode("",$arrays)."<br />";
   $string = sha1(implode($arrays));
   //echo $string;
   $resultArray['cardId'] = $cardId;
   $resultArray['cardExt'] = array();
   $resultArray['cardExt']['code'] = '';
   $resultArray['cardExt']['openid'] = '';
   $resultArray['cardExt']['timestamp'] = $timestamp;
   $resultArray['cardExt']['signature'] = $string;
   //print_r($resultArray);
   return $resultArray;
  }
    
  /*******************************************************
   *  微信卡券:JSAPI 卡券全部卡券 Package
   *******************************************************/
  public function wxCardAllPackage($cardIdArray = array(),$timestamp = ''){
   $reArrays = array();
   if(!empty($cardIdArray) && (is_array($cardIdArray) || is_object($cardIdArray))){
    //print_r($cardIdArray);
    foreach($cardIdArray as $value){
     //print_r($this->wxCardPackage($value,$openid));
     $reArrays[] = $this->wxCardPackage($value,$timestamp);
    }
    //print_r($reArrays);
   }
   else{
    $reArrays[] = $this->wxCardPackage($cardIdArray,$timestamp);
   }
   return strval(json_encode($reArrays));
  }
    
  /*******************************************************
   *  微信卡券:获取卡券列表
   *******************************************************/ 
  public function wxCardListPackage($cardType = "",$cardId = ""){
   //$api_ticket = $this->wxVerifyJsApiTicket();
   $resultArray = array();
   $timestamp = time();
   $nonceStr = $this->wxNoncestr();
   //$strings = 
   $arrays = array(self::appId,self::appSecret,$nonceStr);
   sort($arrays,SORT_STRING);
   $string = sha1(implode($arrays));
     
   $resultArray['app_id'] = self::appId;
   $resultArray['card_sign'] = $string;
   $resultArray['time_stamp'] = $timestamp;
   $resultArray['nonce_str'] = $nonceStr;
   $resultArray['card_type'] = $cardType;
   $resultArray['card_id'] = $cardId;
   return $resultArray;
  }
    
  /*******************************************************
   *  将数组解析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; 
  }
    
  /*******************************************************
   *  微信卡券:上传logo - 需要改写动态功能
   *******************************************************/
  public function wxCardUpdateImg() {
   $wxAccesstoken = $this->wxAccesstoken();
   //$data['access_token'] = $wxAccesstoken;
   $data['buffer']  = '@D:\\workspace\\htdocs\\yky_test\\logo.jpg';
   $url   = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=".$wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
   //array(1) { ["url"]=> string(121) "http://mmbiz.qpic.cn/mmbiz/ibuYxPHqeXePNTW4ATKyias1Cf3zTKiars9PFPzF1k5icvXD7xW0kXUAxHDzkEPd9micCMCN0dcTJfW6Tnm93MiaAfRQ/0" } 
  }
    
  /*******************************************************
   *  微信卡券:获取颜色
   *******************************************************/
  public function wxCardColor(){
   $wxAccesstoken = $this->wxAccesstoken();
   $url    = "https://api.weixin.qq.com/card/getcolors?access_token=".$wxAccesstoken;
   $result   = $this->wxHttpsRequest($url);
   $jsoninfo  = json_decode($result,true);
   return $jsoninfo;
  }
    
  /*******************************************************
   *  微信卡券:拉取门店列表
   *******************************************************/
  public function wxBatchGet($offset = 0,$count = 0){
   $jsonData = json_encode(array('offset' => intval($offset),'count' => intval($count)));
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/card/location/batchget?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;    
  }
    
  /*******************************************************
   *  微信卡券:创建卡券
   *******************************************************/
  public function wxCardCreated($jsonData) {
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/card/create?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
   
  /*******************************************************
   *  微信卡券:查询卡券详情
   *******************************************************/
  public function wxCardGetInfo($jsonData) {
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/card/get?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
  
  /*******************************************************
   *  微信卡券:设置白名单
   *******************************************************/
  public function wxCardWhiteList($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/card/testwhitelist/set?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;
  }
  
  
  /*******************************************************
   *  微信卡券:消耗卡券
   *******************************************************/
  public function wxCardConsume($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/card/code/consume?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;   
  }
  
  /*******************************************************
   *  微信卡券:删除卡券
   *******************************************************/
  public function wxCardDelete($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/card/delete?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;   
  }
    
  /*******************************************************
   *  微信卡券:选择卡券 - 解析CODE
   *******************************************************/ 
  public function wxCardDecryptCode($jsonData){
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/card/code/decrypt?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;    
  }
    
  /*******************************************************
   *  微信卡券:更改库存
   *******************************************************/
  public function wxCardModifyStock($cardId,$increase_stock_value = 0,$reduce_stock_value = 0){
   if(intval($increase_stock_value) == 0 && intval($reduce_stock_value) == 0){
    return false;
   }
     
   $jsonData = json_encode(array("card_id" => $cardId,'increase_stock_value' => intval($increase_stock_value),'reduce_stock_value' => intval($reduce_stock_value)));
     
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/card/modifystock?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;    
  }
  
  /*******************************************************
   *  微信卡券:查询用户CODE
   *******************************************************/ 
  public function wxCardQueryCode($code,$cardId = ''){
     
   $jsonData = json_encode(array("code" => $code,'card_id' => $cardId ));
     
   $wxAccesstoken = $this->wxAccesstoken();
   $url   = "https://api.weixin.qq.com/card/code/get?access_token=" . $wxAccesstoken;
   $result   = $this->wxHttpsRequest($url,true);
   return $jsoninfo;    
  }
 }
 

PHP开发小程序支付服务端集成的步骤详解

PHP开发小程序支付服务端集成的步骤详解

这篇文章主要介绍了微信小程序 微信支付服务端集成实例详解及源码下载的相关资料,需要的朋友可以参考下

微信小程序 微信支付服务端集

理论上集成微信支付的全部工作可以在小程序端完成,因为小程序js有访问网络的能力,但是为了安全,不暴露敏感key,而且可以使用官方提供的现成php demo更省力,于是在服务端完成签名与发起请求,小程序端只做一个wx.requestPayment(OBJECT)接口的对接。

整体集成过程与JSAPI、APP类似,先统一下单,然后拿返回的结果来请求支付。

一共三步:

立即学习“PHP免费学习笔记(深入)”;

1.小程序端通过wx.login的返回的code换取openid 2.服务端向微信统一下单 3.小程序端发起支付

事先准备好这几样东西:


APPID = &#39;wx426b3015555a46be&#39;;
MCHID = &#39;1900009851&#39;;
KEY = &#39;8934e7d15453e97507ef794cf7b0519d&#39;;
APPSECRET = &#39;7813490da6f1265e4901ffb80afaa36f&#39;;
登录后复制

PHP SDK,下载链接见文尾

第1、4样是申请小程序时获得的,第2、3样是申请开通微信支付时获得的,注意第3、4样长得比较像,其实是2个东西,两者混淆将导致签名通不过

向微信端下单,得到prepay_id

1. 创建一个Controller,引并WxPay.Api.php类


<?php
require_once DIR . &#39;/BaseController.php&#39;;
require_once DIR . &#39;/../third_party/wxpay/WxPay.Api.php&#39;;

class WXPay extends BaseController {
  function index() {
  }
}
登录后复制

之后可以通过index.php/wxpay来作访问请求

2. 修改配置文件WxPay.Config.php

改成自己申请得到相应key

3. 实现index方法


function index() {
//     初始化值对象
    $input = new WxPayUnifiedOrder();
//     文档提及的参数规范:商家名称-销售商品类目
    $input->SetBody("灵动商城-手机");
//     订单号应该是由小程序端传给服务端的,在用户下单时即生成,demo中取值是一个生成的时间戳
    $input->SetOut_trade_no(&#39;123123123&#39;);
//     费用应该是由小程序端传给服务端的,在用户下单时告知服务端应付金额,demo中取值是1,即1分钱
    $input->SetTotal_fee("1");
    $input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
    $input->SetTrade_type("JSAPI");
//     由小程序端传给服务端
    $input->SetOpenid($this->input->post(&#39;openId&#39;));
//     向微信统一下单,并返回order,它是一个array数组
    $order = WxPayApi::unifiedOrder($input);
//     json化返回给小程序端
    header("Content-Type: application/json");
    echo json_encode($order);
  }
登录后复制

说明1:文档上提到的nonce_str不是没提交,而是sdk帮我们填上的

出处在WxPay.Api.php第55行


$inputObj->SetNonce_str(self::getNonceStr());//随机字符串
登录后复制

说明2:sign也已经好心地给setSign了,出处在WxPay.Data.php第111行,MakeSign()中


 /**
   * 生成签名
   * @return 签名,本函数不覆盖sign成员变量,如要设置签名需要调用SetSign方法赋值
   */
  public function MakeSign()
  {
    //签名步骤一:按字典序排序参数
    ksort($this->values);
    $string = $this->ToUrlParams();
    //签名步骤二:在string后加入KEY
    $string = $string . "&key=".WxPayConfig::KEY;
    //签名步骤三:MD5加密
    $string = md5($string);
    //签名步骤四:所有字符转为大写
    $result = strtoupper($string);
    return $result;
  }
登录后复制

4. 小程序内调用登录接口,获取openid

向微信登录请求,拿到code,再将code提交换取openId


wx.login({
     success: function(res) {
      if (res.code) {
       //发起网络请求
       wx.request({
        url: &#39;https://api.weixin.qq.com/sns/jscode2session?appid=wx9114b997bd86f***&secret=d27551c7803cf16015e536b192******&js_code=&#39;+res.code+&#39;&grant_type=authorization_code&#39;,
        data: {
         code: res.code
        },
        success: function (response) {
          console.log(response);
        }
       })
      } else {
       console.log(&#39;获取用户登录态失败!&#39; + res.errMsg)
      }
     }
    });
登录后复制

从控制台看到已经成功拿到openid,剩下的事情就是将它传到服务端就好了,服务端那边$this->input->post(''openId'')等着收呢。

5. 小程序端向lendoo.leanapp.cn/index.php/WXPay发起请求,作统一下单


    //统一下单接口对接
          wx.request({
            url: &#39;https://lendoo.leanapp.cn/index.php/WXPay&#39;,
            data: {
              openId: openId
            },
            success: function (response) {
              console.log(response);

            },
                header: {
            &#39;content-type&#39;: &#39;application/x-www-form-urlencoded&#39;
        },
          });
登录后复制

得到如下结果


{
 "appid": "wx9114b997bd86f8ed",
 "mch_id": "1414142302",
 "nonce_str": "eEICgYFuGqxFRK6f",
 "prepay_id": "wx201701022235141fc713b8f80137935406",
 "result_code": "SUCCESS",
 "return_code": "SUCCESS",
 "return_msg": "OK",
 "sign": "63E60C8CD90394FB50E612D085F5362C",
 "trade_type": "JSAPI"
}
登录后复制

前提是https://lendoo.leanapp.cn已经在白名单:

6. 小程序端调起支付API


// 发起支付
var appId = response.data.appid;
var timeStamp = (Date.parse(new Date()) / 1000).toString();
var pkg = &#39;prepay_id=&#39; + response.data.prepay_id;
var nonceStr = response.data.nonce_str;
var paySign = md5.hex_md5(&#39;appId=&#39;+appId+&#39;&nonceStr=&#39;+nonceStr+&#39;&package=&#39;+pkg+&#39;&signType=MD5&timeStamp=&#39;+timeStamp+"&key=d27551c7803cf16***e536b192d5d03b").toUpperCase();
console.log(paySign);
console.log(appId);
wx.requestPayment({
  &#39;timeStamp&#39;: timeStamp,
  &#39;nonceStr&#39;: nonceStr,
  &#39;package&#39;: pkg,
  &#39;signType&#39;: &#39;MD5&#39;,
  &#39;paySign&#39;: paySign,
  &#39;success&#39;:function(res){
    console.log(&#39;success&#39;);
    console.log(res);
  }
});
登录后复制

模拟器测试,将弹出一个二维码供扫描

结果报了一个错误:


errMsg:"requestPayment:fail"
err_code:2
err_desc:"支付验证签名失败"
登录后复制

key需要加入到签名中!!!''appId=''+appId+''&nonceStr=''+nonceStr+''&package=''+pkg+''&signType=MD5&timeStamp=''+timeStamp+"&key=d27551c7803cf16*e536b192d5d03b"这才是完整的。

可是文档里明明没提到key啊

支付成功截图

吐槽完文档再吐槽下命名规则,GetSpbill_create_ip()、IsSpbill_create_ipSet()都是些什么鬼一会儿下划线分隔一会儿驼峰分隔,成员方法首字母还大写,unifiedOrder()这种正经写法也不忘来比划两下,看来网上说大公司的sdk都是实习生撰写是真事,可code reviewer又在哪里?

【相关推荐】

1. 微信小程序完整源码下载

2. 微信小程序demo:仿商城

以上就是PHP开发小程序支付服务端集成的步骤详解的详细内容,更多请关注php中文网其它相关文章!

今天的关于PHP:微信小程序 微信支付服务端集成实例详解及源码下载微信支付php开发流程的分享已经结束,谢谢您的关注,如果想了解更多关于golang实现微信小程序支付服务端、golang微信支付服务端、php 官方微信接口大全:微信支付、微信红包、微信摇一摇、微信小店的完整代码、PHP开发小程序支付服务端集成的步骤详解的相关知识,请在本站进行查询。

本文标签: