All Projects → wenewzhang → Mixin_labs Php Bot

wenewzhang / Mixin_labs Php Bot

PHP7 bot for Mixin Network

Labels

Projects that are alternatives of or similar to Mixin labs Php Bot

Sdk Php
PHP SDK for Authorize.Net API
Stars: ✭ 343 (+2043.75%)
Mutual labels:  payment
Payumbundle
Payum offers everything you need to work with payments. From simplest use cases to very advanced ones.
Stars: ✭ 509 (+3081.25%)
Mutual labels:  payment
Coiniumserv
Next-gen crypto currency mining pool software
Stars: ✭ 651 (+3968.75%)
Mutual labels:  payment
Crater
Open Source Invoicing Solution for Individuals & Businesses
Stars: ✭ 4,897 (+30506.25%)
Mutual labels:  payment
Wxpay Sdk
最新最全微信支付集成SDK,一行代码调用微信支付,包含基础支付功能(网页授权、各种签名、统一下单、退款、对账单、用户信息获取)、验收用例指引(沙箱支付、支付验收、免充值产品开通)、商户平台(现金红包、企业付款到用户、代金券或立减优惠)、公众平台(微信卡券、社交立减金活动)、小程序(生成永久二维码、发送模版消息)等等更多丰富接口注释和例子。
Stars: ✭ 443 (+2668.75%)
Mutual labels:  payment
Pay
个人网站即时到账收款解决方案 / Personal website instant payment solution
Stars: ✭ 558 (+3387.5%)
Mutual labels:  payment
Payment
simple laravel payment package , supports multiple drivers
Stars: ✭ 328 (+1950%)
Mutual labels:  payment
Paysdk
PHP 集成支付 SDK ,集成了支付宝、微信支付的支付接口和其它相关接口的操作。支持 php-fpm 和 Swoole,所有框架通用。宇润PHP全家桶技术支持群:17916227
Stars: ✭ 723 (+4418.75%)
Mutual labels:  payment
Payment
💰 A jQuery-free general purpose library for building credit card forms, validating inputs and formatting numbers.
Stars: ✭ 467 (+2818.75%)
Mutual labels:  payment
Vue Interactive Paycard
Credit card form with smooth and sweet micro-interactions
Stars: ✭ 5,451 (+33968.75%)
Mutual labels:  payment
Gringotts
A complete payment library for Elixir and Phoenix Framework
Stars: ✭ 396 (+2375%)
Mutual labels:  payment
Pay
可能是我用过的最优雅的 Alipay 和 WeChat 的支付 SDK 扩展包了
Stars: ✭ 4,176 (+26000%)
Mutual labels:  payment
Omnipay Alipay
Alipay driver for the Omnipay PHP payment processing library
Stars: ✭ 559 (+3393.75%)
Mutual labels:  payment
Mfcard
Easily integrate Credit Card payments module in iOS App. Swift 4.0
Stars: ✭ 356 (+2125%)
Mutual labels:  payment
Vue Stripe
Stripe Checkout & Elements for Vue.js
Stars: ✭ 669 (+4081.25%)
Mutual labels:  payment
Yaldash
👻 It's never been easier to build and customize admin panels. Yah! yaldash is a beautifully designed administration panel for Laravel.
Stars: ✭ 338 (+2012.5%)
Mutual labels:  payment
Flutter Dribbble Challenge
A Flutter ui kit made with designs from dribbble.
Stars: ✭ 514 (+3112.5%)
Mutual labels:  payment
Moyasar Php
Moyasar PHP client library
Stars: ✭ 5 (-68.75%)
Mutual labels:  payment
Wmzdialog
功能最多样式最多的弹窗,支持普通/微信底部/日期/地区/日历/选择/编辑/分享/菜单/自定义弹窗等,支持多种动画,链式编程调用(Pop-up windows with the most functions and styles, support normal/WeChat bottom/date/region/calendar/select/edit/share/menu/custom pop-up windows, etc., support multiple animations, chain programming calls)
Stars: ✭ 673 (+4106.25%)
Mutual labels:  payment
Rxpay
一个集成支付宝微信的支付工具
Stars: ✭ 576 (+3500%)
Mutual labels:  payment

PHP Bitcoin tutorial based on Mixin Network

A Mixin messenger bot will be created in this tutorial. The bot is powered by PHP and echo message and Bitcoin from user.

Mixin network resource

What you will learn from this tutorial

  1. How to create bot in Mixin messenger and reply message to user| Chinese |Indonesian|Portuguese
  2. How to receive Bitcoin and send Bitcoin in Mixin Messenger| Chinese
  3. Create Bitcoin wallet, read balance and send Bitcoin by PHP based on Mixin Network| Chinese
  4. How to trade bitcoin through PHP language: Pay to ExinCore | Chinese
  5. How to trade bitcoin through PHP: List your order on Ocean.One | Chinese
  6. How to trade ERC-20 compliant coins on OceanOne through PHP | Chinese

Create bot in Mixin messenger and reply message to user

PHP environment setup:

This tutorial is written in PHP 7. So you need to install PHP and Composer.

On macOS

brew update
brew install [email protected]
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
//install composer to /usr/local/opt/[email protected]/bin and give a brief name 'composer'
php composer-setup.php --install-dir=/usr/local/opt/[email protected]/bin --filename=composer
php -r "unlink('composer-setup.php');"

If you install a old php 7.1 before, execute brew unlink [email protected] to remove the symbol links, and then execute brew link [email protected] to link php 7.3 to php default

wenewzha:mixin_labs-php-bot wenewzhang$ brew unlink [email protected]
Unlinking /usr/local/Cellar/php/7.1.23... 24 symlinks removed
wenewzha:mixin_labs-php-bot wenewzhang$ brew link [email protected]
Warning: [email protected] is keg-only and must be linked with --force

If you need to have this software first in your PATH instead consider running:
  echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> ~/.bash_profile
  echo 'export PATH="/usr/local/opt/[email protected]/sbin:$PATH"' >> ~/.bash_profile

After the php 7.3 installed and symlinks created, according your OS environment settings, if php -v prompt "command not found", issue echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' to bash_profile.

echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> ~/.bash_profile
echo 'export PATH="/usr/local/opt/[email protected]/sbin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile

On Ubuntu

apt update
apt upgrade

//install php 7.2
apt-get install software-properties-common python-software-properties
add-apt-repository -y ppa:ondrej/php
apt-get update
apt-get install php7.2 php7.2-cli php7.2-common
//install composer
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
//install composer to /usr/local/bin and give a brief name 'composer'
php composer-setup.php --install-dir=/usr/local/bin --filename=composer
php -r "unlink('composer-setup.php');"

The latest composer can be download from here Make sure the the $PATH variable contains install directory, following command can be used to check the installation

wenewzha:minecraft wenewzhang$ php -v
PHP 7.2.13 (cli) (built: Dec  7 2018 10:41:23) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.13, Copyright (c) 1999-2018, by Zend Technologies
wenewzha:minecraft wenewzhang$ composer -V
Composer version 1.8.0 2018-12-03 10:31:16

Create the project

Go to your documents folder then create a directory, for example: mixin_labs-php-bot

mkdir mixin_labs-php-bot
mixin_labs-php-bot

Execute composer init in your project directory, follow the instruction to create the composer.json,

[email protected]:~/mixin_labs-php-bot# composer init
 Welcome to the Composer config generator
This command will guide you through creating your composer.json config.
Package name (<vendor>/<name>) [user/mixin_labs-php-bot]:
Description []: PHP 7 bot for Mixin Messenger
Author [, n to skip]: JimmyZhang <[email protected]>
Minimum Stability []:
Package Type (e.g. library, project, metapackage, composer-plugin) []:
License []:
Define your dependencies.
Would you like to define your dependencies (require) interactively [yes]? no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no
{
   "name": "user/mixin_labs-php-bot",
   "description": "PHP 7 bot for Mixin Messenger",
   "authors": [
       {
           "name": "JimmyZhang",
           "email": "[email protected]"
       }
   ],
   "require": {}
}
Do you confirm generation [yes]? yes

This tutorial requires two libraries.

In composer.json file, add the two libraries in the "require" code block.

"require": {
    "exinone/mixin-sdk-php": "^1.1",
    "ratchet/pawl": "^0.3.3",
},

Save composer.json file and then execute composer install to download required libraries.

composer install

A vendor directory is created in the project directory after all libraries are downloaded.

ls
composer.json  composer.lock  vendor

If you clone this repository from Github repo, you only need to execute composer install to download all libraries.

Create your first app in Mixin Network developer dashboard

You need to create an app in dashboard. This tutorial can help you.

Generate parameter of your app in dashboard

After app is created in dashboard, you still need to generate parameter and write down required content, these content will be written into config.php file.

mixin_network-keys In project folder, create a file: config.php. Copy the following content into it.

config.php

<?php
return [
    'mixin_id'      => '7000101716',
    'client_id'     => 'a1ce2967-a534-417d-bf12-c86571e4eefa',
    'client_secret' => '7339866727d24eeec1c4ebb6c634fd25a7b9057ee6d5939cca9b6b9fc15f4d1f',
    'pin'           => '512772',
    'pin_token'     => 'abRdNq6soRALRG434IgR7WS/qP7LOcpfviqSfWfABdIKyZGLnWXFMrVCHpChIkBRGRAcsUguni0OoNsShddPVL3qoD5fxbF5dRUiRv14urH1Pmdl6zIZdCH159QMr5wLmmSHSGu2AihNkUHUo3bAJsrvOW0nke5y6R5YE/pNNfo=',
    'session_id'    => '51faabbf-48ff-4df2-898d-e9b318afae35',
    'private_key'   => <<<EOF
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCuKI65sJR9lQ1+kyKouWu3CpmkPdJKaFqKVMEWk9RRH1Wgju9n
z/y5MiBVZKUeeIYtwrCNKbbdkSPqMoj1kLh5XUk4HaV9DUt+s9USBHOgU8m5Pxov
Km+HQ+Pam62lHWn6ClYaNrDihpcdDg9i7Y8hY1cgKiUcdkFQmDQ9lz2VHwIDAQAB
AoGANHJSSOk8TnVMkwmMLnNoVL8EdcmIQpAac/4CB+KM1cEx8CAbSJAB82N9CTo9
32c8QRuYP2qIf0DuJ+EADbN/Wc3o9zRY3dkbnLo144g3YaKwDccSgUMux03ANHlP
MEPDxOUbxJTRPXmKgUZmGJrkAClGbr3pPyQDDHDWRQc9JUECQQDT7pUYcXtu+hSc
nAlZllzqkBG2gZrDYpPJ0JirpfNhaApBo+CGZYKQ1961o6+HcI9gZmZA8hPEhT6p
PlubjqxbAkEA0l89du8TIUGrY9/sxyfZif6aeEztXPwBHZ9r8dm0L8Mlu5zTrOX2
SUgu3znM6djmuRMS45iPHJbPkvw9ilaljQJBAJRN323Ec/D79ZKGKpDThN/rw0lo
tolFoU/Xtg5fycl/CbZXXFYQEOcU+Nc43Ss1HFAEOEf4Xtbluyyp42ce1wMCQElv
P4htyhK41rglaYTXr0NRYeCOkej8evM5PDgPU6u8hkZoZyeamo9YKCx6A8K5mUiP
lO9nyMUlC852SJEqz90CQQDBguGg5GGcfehpIZwERlMJgKGg1+13/9GfnEPdAW2v
px7DZoMG/pQ/SEa53tJHmGGD9+qyp93z/fEPXsD5RSwx
-----END RSA PRIVATE KEY-----
EOF
    ,  //import your private_key
];

Replace the value with content generated in dashboard.

Hello world in PHP

Copy the following code into app.php, create app.php file if it is missing in your folder

<?php

require __DIR__ . '/vendor/autoload.php';
use ExinOne\MixinSDK\Traits\MixinSDKTrait;
use ExinOne\MixinSDK\MixinSDK;
use Ramsey\Uuid\Uuid;
use Ratchet\RFC6455\Messaging\Frame;

$loop = \React\EventLoop\Factory::create();
$reactConnector = new \React\Socket\Connector($loop, [
    'timeout' => 15
]);
$connector = new \Ratchet\Client\Connector($loop,$reactConnector);
class callTraitClass {
  use MixinSDKTrait;
  public $config;
  public function __construct()
  {
      $config = require(__DIR__.'/config.php');
      $this->config        = $config;
  }
}
$callTrait = new callTraitClass();
$Token = $callTrait->getToken('GET', '/', '');
// $connector('ws://127.0.0.1:9000', ['protocol' => 'Mixin-Blaze-1'], ['Origin' => 'http://localhost',
$connector('wss://blaze.mixin.one', ['protocol' => 'Mixin-Blaze-1'],[
                                    'Authorization' => 'Bearer '.$Token
                                      ])
->then(function(Ratchet\Client\WebSocket $conn) {
    $conn->on('message', function(\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
        $jsMsg = json_decode(gzdecode($msg));
        print_r($jsMsg);
        if ($jsMsg->action === 'CREATE_MESSAGE' and property_exists($jsMsg,'data')) {
          echo "\nNeed reply server a receipt!\n";
          $RspMsg = generateReceipt($jsMsg->data->message_id);
          $msg = new Frame(gzencode(json_encode($RspMsg)),true,Frame::OP_BINARY);
          $conn->send($msg);

          if ($jsMsg->data->category === 'PLAIN_TEXT') {
                $msgData = sendPlainText($jsMsg->data->conversation_id,
                                          base64_decode($jsMsg->data->data));
                $msg = new Frame(gzencode(json_encode($msgData)),true,Frame::OP_BINARY);
                $conn->send($msg);
          } //end of PLAIN_TEXT
        } //end of CREATE_MESSAGE

    });
    $conn->on('close', function($code = null, $reason = null) {
        echo "Connection closed ({$code} - {$reason})\n";
    });
/*                   start listen for the incoming message          */
    $message = [
        'id'     => Uuid::uuid4()->toString(),
        'action' => 'LIST_PENDING_MESSAGES',
    ];
    print_r(json_encode($message));
    $msg = new Frame(gzencode(json_encode($message)),true,Frame::OP_BINARY);
    $conn->send($msg);
    // $conn->send(gzencode($msg,1,FORCE_DEFLATE));
}, function(\Exception $e) use ($loop) {
    echo "Could not connect: {$e->getMessage()}\n";
    $loop->stop();
});

$loop->run();


function sendPlainText($conversation_id,$msgContent):Array {

   $msgParams = [
     'conversation_id' => $conversation_id,
     'category'        => 'PLAIN_TEXT',
     'status'          => 'SENT',
     'message_id'      => Uuid::uuid4()->toString(),
     'data'            => base64_encode($msgContent),//base64_encode("hello!"),
   ];
   $msgPayButton = [
     'id'     =>  Uuid::uuid4()->toString(),
     'action' =>  'CREATE_MESSAGE',
     'params' =>   $msgParams,
   ];
   return $msgPayButton;
}

function generateReceipt($msgID):Array {
  $IncomingMsg = ["message_id" => $msgID, "status" => "READ"];
  $RspMsg = ["id" => Uuid::uuid4()->toString(), "action" => "ACKNOWLEDGE_MESSAGE_RECEIPT",
              "params" => $IncomingMsg];
  return $RspMsg;
}

Run the code

php app.php

The following content will be displayed in console.

wenewzha:mixin_labs-php-bot wenewzhang$ php helloworld.php
a1ce2967-a534-417d-bf12-c86571e4eefa{"id":"4454b6c5-4a89-440c-bd22-7a79cf4954ca","action":"LIST_PENDING_MESSAGES"}stdClass Object
(
    [id] => 4454b6c5-4a89-440c-bd22-7a79cf4954ca
    [action] => LIST_PENDING_MESSAGES
)

Add the bot(for example, this bot id is 7000101639) as your friend in Mixin Messenger and send your messages. mixin_messenger

Source code summary

The PHP code creates a websocket client.

$loop = \React\EventLoop\Factory::create();
$reactConnector = new \React\Socket\Connector($loop, [
    'timeout' => 15
]);
$connector = new \Ratchet\Client\Connector($loop,$reactConnector);

The code generates a valid token and creates connection between the websocket and Mixin Messenger server. Messages will be pushed to websocket client.

API of the operation, Guide of the operation

The mixin-sdk-php implements the getToken function, call it and generate a token.

class callTraitClass {
  use MixinSDKTrait;
  public $config;
  public function __construct()
  {
      $config = require(__DIR__.'/config.php');
      $this->config        = $config;
  }
}
$callTrait = new callTraitClass();
$Token = $callTrait->getToken('GET', '/', '');

Connect to Mixin messenger server with the correct token.

$connector('wss://blaze.mixin.one', ['protocol' => 'Mixin-Blaze-1'],[
                                    'Authorization' => 'Bearer '.$Token
                                      ])

Send "LIST_PENDING_MESSAGES" to server to receive pending messages.

/*                   start listen for the incoming message          */
    $message = [
        'id'     => Uuid::uuid4()->toString(),
        'action' => 'LIST_PENDING_MESSAGES',
    ];
    print_r(json_encode($message));
    $msg = new Frame(gzencode(json_encode($message)),true,Frame::OP_BINARY);
    $conn->send($msg);

onMessage function will be called when message is pushed to websocket client.

->then(function(Ratchet\Client\WebSocket $conn) {
    $conn->on('message', function(\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
        $jsMsg = json_decode(gzdecode($msg));
        print_r($jsMsg);
        if ($jsMsg->action === 'CREATE_MESSAGE' and property_exists($jsMsg,'data')) {
          echo "\nNeed reply server a receipt!\n";
          $RspMsg = generateReceipt($jsMsg->data->message_id);
          $msg = new Frame(gzencode(json_encode($RspMsg)),true,Frame::OP_BINARY);
          $conn->send($msg);

          if ($jsMsg->data->category === 'PLAIN_TEXT') {
                $msgData = sendPlainText($jsMsg->data->conversation_id,
                                          base64_decode($jsMsg->data->data));
                $msg = new Frame(gzencode(json_encode($msgData)),true,Frame::OP_BINARY);
                $conn->send($msg);
          } //end of PLAIN_TEXT
        } //end of CREATE_MESSAGE

    });
    $conn->on('close', function($code = null, $reason = null) {
        echo "Connection closed ({$code} - {$reason})\n";
    });                                      

Not only text, images and other type message will be pushed to your bot. You can find more details about Messenger message.

Send a READ operation message to the server let it knows this message has been read. The bot will receive the duplicated message when the bot connected to server again if bot don't send response.

echo "\nNeed reply server a receipt!\n";
$RspMsg = generateReceipt($jsMsg->data->message_id);
$msg = new Frame(gzencode(json_encode($RspMsg)),true,Frame::OP_BINARY);
$conn->send($msg);

function generateReceipt($msgID):Array {
  $IncomingMsg = ["message_id" => $msgID, "status" => "READ"];
  $RspMsg = ["id" => Uuid::uuid4()->toString(), "action" => "ACKNOWLEDGE_MESSAGE_RECEIPT",
              "params" => $IncomingMsg];
  return $RspMsg;
}

End

Now your bot worked, you can hack it.

Full code is here

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].